<?php
session_start();
$_SESSION["user_id"] = 1;
$_GET["id"] = 1;
require_once __DIR__ . "/includes/functions.php";
require_once __DIR__ . "/vendor/autoload.php";
use Dompdf\Dompdf;
use Dompdf\Options;
$db = getDB();
$id = (int)($_GET['id'] ?? 0);
$stmt = $db->prepare("SELECT i.*, c.name as cust_name, c.address as cust_address, c.city as cust_city, c.state as cust_state, c.pincode as cust_pincode, c.email as cust_email, c.phone as cust_phone, c.gstin as cust_gstin FROM invoices i JOIN customers c ON i.customer_id = c.id WHERE i.id = ?");
$stmt->execute([$id]);
$inv = $stmt->fetch();
$items = $db->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
$items->execute([$id]);
$lineItems = $items->fetchAll();
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice <?= sanitize($inv['invoice_number']) ?></title>
<style>
body { font-family: 'DejaVu Sans', sans-serif; }
.items-table { width: 100%; border-collapse: collapse; }
.items-table th, .items-table td { padding: 12px; text-align: left; border-bottom: 1px solid #e9ecef; }
</style>
</head>
<body>
<table class="items-table">
<thead>
<tr><th>Description</th><th>Qty</th><th>Rate</th><th>GST%</th><th class="text-right">Amount</th></tr>
</thead>
<tbody>
<?php foreach ($lineItems as $item): ?>
<tr>
<td><?= sanitize($item['product_name']) ?></td>
<td><?= (int)$item['quantity'] ?></td>
<td><?= number_format($item['unit_price'], 2) ?></td>
<td><?= number_format($item['gst_percent'], 2) ?>%</td>
<td class="text-right"><?= number_format($item['line_total'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<?php
$html = ob_get_clean();
file_put_contents(__DIR__ . '/tmp_pdf_test.html', $html);
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', false);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
try {
    $dompdf->render();
    echo "RENDER_OK";
} catch (Exception $e) {
    echo "ERROR:" . get_class($e) . "|" . $e->getMessage();
}
