<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\SessionAuth;
use App\Repositories\InvoiceRepository;

final class InvoicePdfController
{
    public function generate(): void
    {
        app()->get(SessionAuth::class)->requireLogin();

        $autoloadCandidates = [
            dirname(__DIR__, 2) . '/vendor/autoload.php',
            dirname(__DIR__, 3) . '/vendor/autoload.php',
        ];

        $autoloadFound = null;
        foreach ($autoloadCandidates as $candidate) {
            if (is_file($candidate)) {
                $autoloadFound = $candidate;
                break;
            }
        }

        if ($autoloadFound === null) {
            http_response_code(500);
            echo '<h2 style="font-family:Arial,sans-serif;color:#b91c1c">Dompdf غير مثبت</h2>';
            echo '<p style="font-family:Arial,sans-serif">يرجى تنفيذ الأمر التالي داخل المشروع:</p>';
            echo '<pre style="background:#f8fafc;border:1px solid #cbd5e1;padding:16px">composer require dompdf/dompdf</pre>';
            return;
        }

        require_once $autoloadFound;

        if (!class_exists(\Dompdf\Dompdf::class)) {
            http_response_code(500);
            echo '<h2 style="font-family:Arial,sans-serif;color:#b91c1c">تعذر تحميل Dompdf</h2>';
            return;
        }

        $id = (int)($_GET['id'] ?? 0);
        $repo = new InvoiceRepository();
        $invoice = $repo->find($id);
        if (!$invoice) {
            http_response_code(404);
            include __DIR__ . '/../Views/errors/404.php';
            return;
        }

        $lines = $repo->lines($id);

        ob_start();
        include __DIR__ . '/../Views/invoices/pdf.php';
        $html = (string)ob_get_clean();

        $options = new \Dompdf\Options();
        $options->set('isRemoteEnabled', true);
        $options->set('isHtml5ParserEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');

        $dompdf = new \Dompdf\Dompdf($options);
        $dompdf->loadHtml($html, 'UTF-8');
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $dompdf->stream('invoice-' . ($invoice['invoice_no'] ?? $id) . '.pdf', ['Attachment' => false]);
    }
}
