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

$id = (int)($_GET['id'] ?? 0);
$type = $_GET['type'] ?? 'invoice';   // invoice | transport
$paper = $_GET['paper'] ?? 'thermal'; // a4 | thermal

$inv = $conn->query("SELECT * FROM sales_invoices WHERE id=$id")->fetch_assoc();
$company = getCompany($conn, $inv['company_id'] ?? null);
$client = $conn->query("SELECT * FROM clients WHERE id={$inv['client_id']}")->fetch_assoc();

$items = $conn->query("
    SELECT 
        si.*, 
        si.description AS item_description,
        p.name  AS product_name,
        p.hsn_code,
        p.brand,
        p.unit,
        pi.mrp
    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
");

$total_cgst = 0;
$total_sgst = 0;

if ($paper === 'a4' && $type === 'invoice') {
    require 'layout_a4_tally.php';
}
elseif ($paper === 'a4' && $type === 'transport') {
    require 'layout_a4_transport.php';
}
elseif ($paper === 'thermal' && $type === 'invoice') {
    require 'layout_thermal.php';
}
elseif ($paper === 'thermal' && $type === 'transport') {
    require 'layout_thermal_transport.php';
}
