<?php

declare(strict_types=1);

namespace App\Modules\Inventory\Presentation\Controllers;

use App\Modules\Inventory\Application\Services\WarehouseDocsPageService;

final class WarehouseDocPrintController
{
    public function __construct(private ?WarehouseDocsPageService $pages = null)
    {
        $this->pages ??= new WarehouseDocsPageService();
    }

    public function __invoke(): void
    {
        require_permission('stock.vouchers.view');

        $format = strtolower((string)($_GET['format'] ?? ''));
        $id = (int)($_GET['id'] ?? 0);

        if ($format === '') {
            print_format_chooser(
                \App\Modules\Inventory\Application\Services\WarehouseDocsRouteContext::print($id, 'a4'),
                \App\Modules\Inventory\Application\Services\WarehouseDocsRouteContext::print($id, 'receipt'),
                'طباعة إذن مخزن'
            );
            return;
        }

        if ($id <= 0) {
            http_response_code(400);
            exit('Invalid document id');
        }

        if (!in_array($format, ['a4', 'receipt'], true)) {
            $format = 'a4';
        }

        $payload = $this->pages->buildPrintPayload(db(), $id);
        print_view($format, 'wh_doc', array_merge([
            'title' => $payload['title'],
            'meta' => $payload['meta'],
            'company' => $payload['company'],
            'footer' => $payload['footer'],
            'print_format' => $format,
        ], $payload['payload']));
    }
}
