<?php
require_once '../db.php';
require_once '../includes/company.php';

$id       = (int)($_GET['id'] ?? 0);
$type     = $_GET['type'] ?? 'invoice';
$template = $_GET['template'] ?? 'simple';

if ($id <= 0) {
    exit('Invalid Invoice ID');
}

/* =======================
   LOAD DATA (MANDATORY)
   ======================= */

$inv = $conn->query(
    "SELECT * FROM sales_invoices WHERE id = $id"
)->fetch_assoc();

if (!$inv) {
    exit('Invoice not found');
}

$company = getCompany($conn, $inv['company_id']);

$client = $conn->query(
    "SELECT * FROM clients WHERE id = {$inv['client_id']}"
)->fetch_assoc();

$items = $conn->query("
    SELECT
        si.*,

        -- product master
        p.name       AS product_name,
        p.hsn_code,
        p.unit,

        -- batch / purchase data
        pi.mrp,

        -- safety aliases (future proof)
        pi.batch_no,
        pi.purchase_price

    FROM sales_items si

    JOIN products p 
        ON p.id = si.product_id

    LEFT JOIN purchase_items pi
        ON pi.id = si.purchase_item_id

    WHERE si.sales_invoice_id = $id
");

/* =======================
   TEMPLATE RESOLUTION
   ======================= */

$templatePath = __DIR__ . "/templates/$template/layout.php";

if (!file_exists($templatePath)) {
    exit("Template not found: $template");
}

/* =======================
   RENDER TEMPLATE
   ======================= */
require $templatePath;
