<?php
require 'session-master.php';
require 'functions.php';
require './PDFvendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

/* ======================================================
   HARD STOP: CLEAR ALL OUTPUT
====================================================== */
ini_set('display_errors', 0);
error_reporting(0);

while (ob_get_level()) {
    ob_end_clean();
}
ob_start();

/* ======================================================
   SESSION & COMPANY CONTEXT
====================================================== */
if (!isset($_SESSION['company_id'])) {
    exit; // DO NOT echo or die
}

$company_id = (int) $_SESSION['company_id'];

/* ======================================================
   DB CONNECTION (PDO)
====================================================== */
try {
    $pdo = new PDO(
        "mysql:host=" . DATABASE_HOST . ";dbname=" . DATABASE_NAME . ";charset=utf8mb4",
        DATABASE_USER,
        DATABASE_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (Throwable $e) {
    exit;
}

/* ======================================================
   FETCH COMPANY
====================================================== */
$stmt = $pdo->prepare("
    SELECT company_name, company_address, company_state, currency
    FROM company
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$company_id]);
$company = $stmt->fetch();

if (!$company) {
    exit;
}

/* ======================================================
   FETCH INVOICES
====================================================== */
$stmt = $pdo->prepare("
    SELECT 
        i.invoice,
        i.invoice_date,
        i.invoice_due_date,
        i.invoice_type,
        i.total,
        i.status,
        c.name AS customer_name
    FROM invoices i
    JOIN customers c 
        ON c.invoice = i.invoice 
       AND c.company_id = i.company_id
    WHERE i.company_id = ?
    ORDER BY i.invoice_date DESC
");
$stmt->execute([$company_id]);
$invoices = $stmt->fetchAll();

/* ======================================================
   BUILD HTML (NO PHP OUTPUT AFTER THIS)
====================================================== */
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: DejaVu Sans, sans-serif; font-size: 12px; }
table { width:100%; border-collapse:collapse; }
th, td { border:1px solid #000; padding:5px; }
th { background:#f0f0f0; }
h3 { text-align:center; margin:6px 0; }
</style>
</head>
<body>

<h3><?= htmlspecialchars($company['company_name']) ?></h3>
<h3>Invoice List</h3>

<table>
<thead>
<tr>
    <th>#</th>
    <th>Invoice</th>
    <th>Customer</th>
    <th>Issue</th>
    <th>Due</th>
    <th>Type</th>
    <th>Amount (<?= htmlspecialchars($company['currency']) ?>)</th>
    <th>Status</th>
</tr>
</thead>
<tbody>
<?php if (!$invoices): ?>
<tr>
    <td colspan="8" align="center">No invoices found</td>
</tr>
<?php else: $i=1; foreach ($invoices as $row): ?>
<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($row['invoice']) ?></td>
    <td><?= htmlspecialchars($row['customer_name']) ?></td>
    <td><?= htmlspecialchars($row['invoice_date']) ?></td>
    <td><?= htmlspecialchars($row['invoice_due_date']) ?></td>
    <td><?= strtoupper(htmlspecialchars($row['invoice_type'])) ?></td>
    <td><?= number_format($row['total'], 2) ?></td>
    <td><?= strtoupper(htmlspecialchars($row['status'])) ?></td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>

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

/* ======================================================
   DOMPDF (LET IT HANDLE HEADERS)
====================================================== */
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$options->set('isRemoteEnabled', false);

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

$date = date('dmY'); // daymonthyear e.g. 01122026

$dompdf->stream(
    "invoicepdf-$date.pdf",
    ['Attachment' => true]
);

exit;
