<?php
chdir('../');
ob_start();
session_start();

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once("public/connection.php");
require_once("public/functions.php");
require_once("assets/vendor/tcpdf/tcpdf.php");

$invoice_id = isset($_GET['invoice_id']) ? (int)$_GET['invoice_id'] : 0;
if ($invoice_id <= 0) {
    die("Invalid invoice ID.");
}

// Fetch invoice
$invoice_query = $connection->query("SELECT * FROM inventory_invoices WHERE id = $invoice_id");
if (!$invoice_query || $invoice_query->num_rows === 0) {
    die("Invoice not found.");
}
$invoice = $invoice_query->fetch_assoc();
$amount_paid = $invoice['amount_paid'];
$grand_tot = $invoice['total_amount'];
$discount = isset($invoice['Discount']) ? (float)$invoice['Discount'] : 0.00;
$grand_total = $grand_tot + $discount;
$final_total = $grand_total - $discount;
$balance = $final_total - $amount_paid;

// Fetch invoice items
$items = $connection->query("SELECT * FROM inventory_invoice_items WHERE invoice_id = $invoice_id");

// Fetch school details
$school_query = $connection->query("SELECT school_name, school_motto, school_address, school_phone, school_website, school_logo 
    FROM administratives LIMIT 1");
if (!$school_query || $school_query->num_rows === 0) {
    die("School details not found.");
}
$school = $school_query->fetch_assoc();

$issued_date = date('Y-m-d H:i', strtotime($invoice['issued_at']));
$created_by = $invoice['created_by'];
$status = $invoice['payment_status'];
$logo_path = file_exists("uploads/{$school['school_logo']}") ? "uploads/{$school['school_logo']}" : "";

// Sanitize student name for file name
$student_name = preg_replace('/[^A-Za-z0-9\-]/', '_', $invoice['student_name']); 
$student_name = trim($student_name, '_'); 

// Estimate height for thermal
$baseHeight = 50; 
$itemHeight = 5; 
$footerHeight = 30; 
$itemCount = $items->num_rows;
$estimatedHeight = $baseHeight + ($itemCount * $itemHeight) + $footerHeight;

// Detect printer type
$printer_type = $_GET['printer'] ?? 'normal';

// Init TCPDF
if ($printer_type === 'thermal') {
    $pageWidth = 80; 
    $pageHeight = max(160, $estimatedHeight);
    $pdf = new TCPDF('P', 'mm', [$pageWidth, $pageHeight], true, 'UTF-8', false);
    $pdf->SetMargins(5, 5, 5);
    $pdf->SetAutoPageBreak(FALSE);
    $pdf->SetFont('helvetica', '', 9);
} else {
    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetMargins(15, 20, 15);
    $pdf->SetAutoPageBreak(TRUE, 20);
    $pdf->SetFont('helvetica', '', 11);
}

$pdf->SetTitle($invoice['invoice_no']);
$pdf->AddPage();

// School Logo + Header
if ($logo_path) {
    if ($printer_type === 'thermal') {
        $pdf->Image($logo_path, 25, 5, 30, '', '', '', 'T', false, 300);
        $pdf->Ln(22);
    } else {
        $pdf->Image($logo_path, 85, 10, 40, '', '', '', 'T', false, 300);
        $pdf->Ln(35);
    }
}

if ($printer_type === 'thermal') {
    $html = '<div style="text-align:center;">
        <strong style="font-size:12px;">' . htmlspecialchars($school['school_name']) . '</strong><br>
        <em>' . htmlspecialchars($school['school_motto']) . '</em><br>
        ' . htmlspecialchars($school['school_address']) . '<br>
        Tel: ' . htmlspecialchars($school['school_phone']) . '<br>
        ' . htmlspecialchars($school['school_website']) . '
    </div><hr>';
} else {
    $html = '<div style="text-align:center;">
        <strong style="font-size:16px;">' . htmlspecialchars($school['school_name']) . '</strong><br>
        <em>' . htmlspecialchars($school['school_motto']) . '</em><br>
        ' . htmlspecialchars($school['school_address']) . '<br>
        Tel: ' . htmlspecialchars($school['school_phone']) . ' | ' . htmlspecialchars($school['school_website']) . '
    </div><hr><br>';
}

// Invoice details
$html .= '<div style="font-size:' . ($printer_type === 'thermal' ? '9px' : '11px') . ';">
Created By: ' . htmlspecialchars($created_by) . '<br>
Issued At: ' . $issued_date . '<br>
Invoice #: ' . htmlspecialchars($invoice['invoice_no']) . '<br>
Student: ' . htmlspecialchars($invoice['student_name']) . '<br>
Reg No: ' . htmlspecialchars($invoice['reg_number']) . '<br>
Class: ' . htmlspecialchars($invoice['student_class']) . '<br>
Payment Status: ' . htmlspecialchars($status) . '
</div><hr>';

// Items Table
if ($printer_type === 'thermal') {
    $html .= '<table width="100%" cellpadding="2" style="font-size:9px;">
    <thead>
    <tr>
        <td><b>Item</b></td>
        <td align="center"><b>Qty</b></td>
        <td align="right"><b>Price</b></td>
        <td align="right"><b>Total</b></td>
    </tr>
    </thead><tbody>';
} else {
    $html .= '<table width="100%" border="1" cellpadding="5" cellspacing="0" style="font-size:11px;">
    <thead style="background-color:#f0f0f0;">
    <tr>
        <th><b>Item</b></th>
        <th align="center"><b>Qty</b></th>
        <th align="right"><b>Price</b></th>
        <th align="right"><b>Total</b></th>
    </tr>
    </thead><tbody>';
}

while ($item = $items->fetch_assoc()) {
    $html .= '<tr>
        <td>' . htmlspecialchars($item['item_name']) . '</td>
        <td align="center">' . $item['quantity'] . '</td>
        <td align="right">' . number_format($item['unit_price'], 2) . '</td>
        <td align="right">' . number_format($item['total_price'], 2) . '</td>
    </tr>';
}

$html .= '</tbody></table><hr>';

// Totals Section
$html .= '
<table width="100%" style="font-size:' . ($printer_type === 'thermal' ? '9px' : '11px') . '; margin-top:10px;">
<tr>
    <td><b>Subtotal</b></td>
    <td align="right">' . number_format($grand_total, 2) . '</td>
</tr>
<tr>
    <td><b>Discount</b></td>
    <td align="right">-' . number_format($discount, 2) . '</td>
</tr>
<tr>
    <td><b>Final Total</b></td>
    <td align="right"><b>' . number_format($final_total, 2) . '</b></td>
</tr>
<tr>
    <td>Amount Paid</td>
    <td align="right">' . number_format($amount_paid, 2) . '</td>
</tr>
<tr>
    <td>Balance</td>
    <td align="right">' . ($balance <= 0 ? 'Fully Paid' : number_format($balance, 2)) . '</td>
</tr>
</table>
<hr>
<div style="text-align:center;font-size:' . ($printer_type === 'thermal' ? '9px' : '11px') . '; margin-top:10px;">
    <em>Thank you for your patronage!</em><br>
</div>';

// Write HTML
$pdf->writeHTML($html, true, false, true, false, '');

// Barcode
$pdf->Ln(2);
$pdf->write1DBarcode($invoice['invoice_no'], 'C128', '', '', '', 18, 0.4, array(
    'position' => 'C',
    'align' => 'C',
    'stretch' => false,
    'fitwidth' => true,
    'border' => false,
    'hpadding' => 'auto',
    'vpadding' => 'auto',
    'fgcolor' => array(0,0,0),
    'bgcolor' => false,
    'text' => true,
    'font' => 'helvetica',
    'fontsize' => 8,
    'stretchtext' => 4
), 'N');

// Cut line only on thermal
if ($printer_type === 'thermal') {
    $pdf->Ln(3);
    $pdf->SetLineStyle(array('width' => 0.3, 'dash' => '2,2'));
    $pdf->Line(5, $pdf->GetY(), $pageWidth - 5, $pdf->GetY());
    $pdf->Ln(2);
    $pdf->Cell(0, 5, '----- CUT HERE -----', 0, 1, 'C');
}

// Auto-print + close
$js = <<<EOD
print(true);
this.closeDoc();
EOD;
$pdf->IncludeJS($js);

ob_end_clean();
$pdf->Output($student_name . '.pdf', 'I');
?>
