<?php
use Dompdf\Dompdf;
use Dompdf\Options;

function generateInvoicePdf(
    mysqli $mysqli,
    int $company_id,
    string $invoice
): string {

    /* =========================
       FETCH INVOICE (same query)
    ========================== */
    $stmt = $mysqli->prepare("
        SELECT i.*, c.*
        FROM invoices i
        JOIN customers c
          ON c.invoice = i.invoice
         AND c.company_id = i.company_id
        WHERE i.invoice = ?
          AND i.company_id = ?
        LIMIT 1
    ");
    $stmt->bind_param("si", $invoice, $company_id);
    $stmt->execute();
    $invoiceData = $stmt->get_result()->fetch_assoc();

    if (!$invoiceData) {
        throw new Exception("Invoice not found");
    }

    /* =========================
       FETCH COMPANY
    ========================== */
    $stmt = $mysqli->prepare("SELECT * FROM company WHERE id = ?");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();
    $company = $stmt->get_result()->fetch_assoc();

    /* =========================
       BUILD HTML (reuse your HTML)
    ========================== */
    ob_start();
    require __DIR__ . '/invoice-template.php'; // move your HTML here
    $html = ob_get_clean();

    /* =========================
       DOMPDF
    ========================== */
    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $options->set('defaultFont', 'DejaVu Sans');

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

    return $dompdf->output(); // 🔥 RETURN RAW PDF
}
