<?php
declare(strict_types=1);

/** Turns a valid booking into invoice lines and totals (tax-inclusive maths kept in cents). */
final class Invoice
{
    public const TAX_RATE = 0.10;

    /** @param array<string,mixed> $b */
    public static function fromBooking(array $b, int $seq, DateTimeImmutable $issued): array
    {
        $svc = Validator::SERVICES[$b['service']];
        $unitCents = (int)round($svc['price'] * 100);
        $netCents = $unitCents * (int)$b['qty'];
        $taxCents = (int)round($netCents * self::TAX_RATE);
        return [
            'number' => sprintf('INV-%s-%04d', $issued->format('Y'), $seq),
            'issued' => $issued->format('Y-m-d'),
            'due'    => $issued->modify('+14 days')->format('Y-m-d'),
            'customer' => $b['name'], 'email' => $b['email'],
            'lines'  => [[
                'desc' => $svc['label'] . ' on ' . $b['date'] . ' at ' . $b['time'],
                'qty' => (int)$b['qty'], 'unit' => $unitCents / 100, 'net' => $netCents / 100,
            ]],
            'net' => $netCents / 100, 'tax' => $taxCents / 100, 'gross' => ($netCents + $taxCents) / 100,
        ];
    }

    public static function money(float $v): string { return number_format($v, 2); }
}
