<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application\Services;

use PDO;

final class SalesViewService
{
    public function __construct(private PDO $pdo)
    {
    }

    public function load(int $id): array
    {
        $statement = $this->pdo->prepare('SELECT * FROM sales_invoices WHERE id=?');
        $statement->execute([$id]);
        $invoice = $statement->fetch();
        if (!$invoice) {
            return ['inv' => null, 'lines' => []];
        }

        $linesStatement = $this->pdo->prepare(
            'SELECT si.*, i.name FROM sales_items si JOIN items i ON i.id = si.item_id WHERE si.invoice_id=?'
        );
        $linesStatement->execute([$id]);

        return [
            'inv' => $invoice,
            'lines' => $linesStatement->fetchAll() ?: [],
        ];
    }
}
