<?php
require 'session-master.php';
require 'includes/config.php';
require 'pdf/invoice-pdf-generator.php';

/* =========================
   SESSION VALIDATION
========================= */
if (!isset($_SESSION['company_id'])) {
    	echo "
        <script>
            alert('Company context missing. Please re-login.');
            window.location.href = 'sign-in.php';
        </script>
        ";
        exit;
}

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

/* =========================
   INPUT VALIDATION
========================= */
if (empty($_GET['id'])) {
    	echo "
        <script>
            alert('Invalid ID');
            window.location.href = 'invoice-list.php';
        </script>
        ";
        exit;
}

$invoice = trim($_GET['id']);

  /* =========================
       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");
    }
$invoice_prefix = htmlspecialchars($company['invoice_prefix']);

/* =========================
   DB CONNECTION
========================= */
$mysqli = new mysqli(
    DATABASE_HOST,
    DATABASE_USER,
    DATABASE_PASS,
    DATABASE_NAME
);

if ($mysqli->connect_error) {
    die('Database connection failed');
}

/* =========================
   GENERATE PDF
========================= */
try {

    $pdfData = generateInvoicePdf(
        $mysqli,
        $company_id,
        $invoice
    );

} catch (Throwable $e) {
    die($e->getMessage());
}

$mysqli->close();

/* =========================
   OUTPUT PDF
========================= */
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="Invoice-' . $invoice_prefix . '-' . $invoice . '.pdf"');
header('Content-Length: ' . strlen($pdfData));

echo $pdfData;
exit;
