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

/**
 * Generate Invoice PDF (RAW BINARY)
 *
 * @param mysqli $mysqli
 * @param int    $company_id
 * @param string $invoice
 * @return string PDF binary data
 * @throws Exception
 */
function generateInvoicePdf(mysqli $mysqli, int $company_id, string $invoice): string
{
    /* =========================
       FETCH INVOICE + CUSTOMER
    ========================== */
    $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 or access denied");
    }

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

    if (!$company) {
        throw new Exception("Company not found");
    }

    /* =========================
       FETCH ITEMS
    ========================== */
    $items = [];
    $stmt = $mysqli->prepare("
        SELECT *
        FROM invoice_items
        WHERE invoice = ?
          AND company_id = ?
        ORDER BY item_order ASC
    ");
    $stmt->bind_param("si", $invoice, $company_id);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {
        $items[] = $row;
    }

    /* =========================
       COMPANY LOGO (BASE64)
    ========================== */
    $base64_logo = '';
    if (!empty($company['company_logo'])) {
        $logoPath = dirname(__DIR__) . '/images/' . $company['company_logo'];
        if (file_exists($logoPath)) {
            $type = pathinfo($logoPath, PATHINFO_EXTENSION);
            $data = file_get_contents($logoPath);
            $base64_logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
        }
    }

    /* =========================
       BUILD HTML
    ========================== */
    ob_start();
    ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Invoice <?= htmlspecialchars($invoiceData['invoice']) ?></title>

<style>
body { font-family: DejaVu Sans, sans-serif; font-size: 12px; }

.table { width:100%; border-collapse:collapse; }
.table th, .table td { padding:6px; border-bottom:1px solid #eee; }

.header h1 { margin:0; }
.right { text-align:right; }

.total-row td {
    background:#000;
    color:#fff;
    font-weight:bold;
}
</style>
</head>

<body>

<?php if (!empty($invoiceData['status'])): ?>
<div style="
    position:fixed;
    top:35%;
    left:0;
    width:100%;
    text-align:center;
    font-size:120px;
    color:rgba(0,0,0,0.05);
    transform:rotate(-30deg);
">
<?= strtoupper($invoiceData['status']) ?>
</div>
<?php endif; ?>

<table width="100%" class="header">
<tr>
<td width="50%">
<?php if ($base64_logo): ?>
<img src="<?= $base64_logo ?>" width="180">
<?php endif; ?>
</td>
<td width="50%" align="right">
<h1><?= strtoupper($invoiceData['invoice_type']) ?></h1>
</td>
</tr>
</table>

<br>

<table width="100%">
<tr>
<td width="60%"></td>
<td class="right"><b>Invoice No:</b></td>
<td class="right"><?= htmlspecialchars($company['invoice_prefix']) ?>-<?= htmlspecialchars($invoiceData['invoice']) ?></td>
</tr>
<tr>
<td></td>
<td class="right"><b>Date:</b></td>
<td class="right"><?= date("d M Y", strtotime($invoiceData['invoice_date'])) ?></td>
</tr>
<tr>
<td></td>
<td class="right"><b>Due:</b></td>
<td class="right"><?= date("d M Y", strtotime($invoiceData['invoice_due_date'])) ?></td>
</tr>
</table>

<br>

<table width="100%">
<tr>
<td width="33%">
<b><?= htmlspecialchars($company['company_name']) ?></b><br>
<?= nl2br(htmlspecialchars($company['company_address'])) ?><br>
<?= htmlspecialchars($company['company_email']) ?><br>
<?= htmlspecialchars($company['company_phone']) ?>
</td>

<td width="33%">
<b>Bill To</b><br>
<?= htmlspecialchars($invoiceData['name']) ?><br>
<?= htmlspecialchars($invoiceData['address_1']) ?><br>
<?= htmlspecialchars($invoiceData['town']) ?>
</td>

<td width="33%">
<b>Pay To</b><br>
Bank: <?= htmlspecialchars($company['bank_name']) ?><br>
Acc No: <?= htmlspecialchars($company['account_no']) ?><br>
<?= htmlspecialchars($company['account_name']) ?>
</td>
</tr>
</table>

<br>

<table class="table">
<thead>
<tr>
<th>Description</th>
<th width="10%">Qty</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
</tr>
</thead>

<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td>
<b><?= htmlspecialchars($item['product']) ?></b><br>
<small><?= htmlspecialchars($item['product_description']) ?></small>
</td>
<td class="right"><?= $item['qty'] ?></td>
<td class="right"><?= number_format($item['price'], 2) ?></td>
<td class="right"><?= number_format($item['subtotal'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>

<tfoot>
<tr>
<td colspan="2"></td>
<td class="right"><b>Subtotal</b></td>
<td class="right"><?= number_format($invoiceData['subtotal'], 2) ?></td>
</tr>
<tr>
<td colspan="2"></td>
<td class="right"><b>Discount</b></td>
<td class="right"><?= number_format($invoiceData['discount'], 2) ?></td>
</tr>
<tr>
<td colspan="2"></td>
<td class="right"><b>VAT</b></td>
<td class="right"><?= number_format($invoiceData['vat'], 2) ?></td>
</tr>
<tr class="total-row">
<td colspan="2"></td>
<td class="right">TOTAL</td>
<td class="right"><?= number_format($invoiceData['total'], 2) ?></td>
</tr>
</tfoot>
</table>

<br><br>

<b>Notes</b><br>
<?= nl2br(htmlspecialchars($company['terms'])) ?>

</body>
</html>
<?php
    $html = ob_get_clean();

    /* =========================
       DOMPDF
    ========================== */
    require_once dirname(__DIR__) . '../PDFvendor/autoload.php';

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

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

    return $dompdf->output();
}
