<?php
require_once __DIR__ . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
require_once __DIR__ . '/../inc/db.php';

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    die('Invalid invoice ID.');
}

// ---- fetch the row that contains your products_data JSON ----
$stmt = $conn->prepare("SELECT * FROM tempaccountinvoice WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if (!$row) {
    die('Invoice not found.');
}
$stmt->close();

// ---- decode the products JSON you stored ----
$products = json_decode($row['products_data'], true);
if (json_last_error() !== JSON_ERROR_NONE || empty($products)) {
    die('Invalid or empty products JSON');
}

// we assume first item has header details
$first       = $products[0];
$invoiceNo   = htmlspecialchars($first['bill_number']);
$invoiceDate = date('d-m-Y', strtotime($first['bill_date']));
$partyName   = htmlspecialchars($first['customer_name']);
$businessName= htmlspecialchars($first['shop_name']);

// ===== Build table rows =====
$itemsHtml = '';
$total = 0;
foreach ($products as $p) {
    $name   = htmlspecialchars($p['product_name']);
    $qty    = (float)$p['quantity'];
    $price  = (float)$p['price'];
    $hsn    = htmlspecialchars($p['hsn_code'] ?? '');
    $amount = (float)$p['total_amount'];
    $total += $amount;

    $itemsHtml .= "<tr>
        <td style='width:40%;'>{$name}</td>
        <td style='width:20%; text-align:center;'>{$hsn}</td>
        <td style='width:10%; text-align:center;'>{$qty}</td>
        <td style='width:15%; text-align:center;'>".number_format($price,2)."</td>
        <td style='width:15%; text-align:center;'>".number_format($amount,2)."</td>
    </tr>";
}

// taxes & grand total
$cgst = $total * 0.09;
$sgst = $total * 0.09;
$grandTotal = $total + $cgst + $sgst;

// number to words helper
function numberToWords($num) {
    $ones = ['', 'One','Two','Three','Four','Five','Six','Seven','Eight','Nine',
             'Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen',
             'Seventeen','Eighteen','Nineteen'];
    $tens = ['', '', 'Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'];
    if ($num == 0) return 'Zero';
    if ($num < 20) return $ones[$num];
    if ($num < 100) return $tens[intval($num/10)] . ($num%10 ? ' '.$ones[$num%10] : '');
    if ($num < 1000) return $ones[intval($num/100)].' Hundred'.($num%100 ? ' and '.numberToWords($num%100) : '');
    if ($num < 100000) return numberToWords(intval($num/1000)).' Thousand'.($num%1000 ? ' '.numberToWords($num%1000) : '');
    if ($num < 10000000) return numberToWords(intval($num/100000)).' Lakh'.($num%100000 ? ' '.numberToWords($num%100000) : '');
    return numberToWords(intval($num/10000000)).' Crore'.($num%10000000 ? ' '.numberToWords($num%10000000) : '');
}
$grandWords = numberToWords(round($grandTotal)).' Rupees Only';

// ===== HTML for PDF =====
$html = "
<html>
<head>
<meta charset='utf-8'>
<style>
body { font-family: DejaVu Sans, sans-serif; font-size:12px; }
table { border-collapse:collapse; width:100%; }
th,td { border:1px solid #000; padding:6px; }
.header { background:#8ee1e8; text-align:center; padding:8px; }
.grand-total { background:#007070; color:#fff; font-weight:bold; text-align:right; }
</style>
</head>
<body>
<table width='100%'>
<tr>
  <td style='border:none;'>M. 8104333664</td>
  <td style='border:none; text-align:right;'>INVOICE NO : {$invoiceNo}<br>DATE : {$invoiceDate}</td>
</tr>
<tr><td colspan='2' class='header'>
  <h1>Kumawat Computer & Cyber Cafe</h1>
  Behind Vedanta College, Reengus (Sikar) Raj. 332404<br>
  All Type of Computer, Laptop, Parts & Printer Sale & Service
</td></tr>
<tr><td colspan='2'><strong>{$partyName}</strong><br>{$businessName}</td></tr>
</table>

<table width='100%'>
<tr>
  <th>Description</th>
  <th>HSN Code</th>
  <th>Qty</th>
  <th>Rate</th>
  <th>Amount</th>
</tr>
{$itemsHtml}
<tr>
  <td colspan='3'></td>
  <td>Total</td>
  <td>".number_format($total,2)."</td>
</tr>
<tr>
  <td colspan='3'></td>
  <td>CGST 9%</td>
  <td>".number_format($cgst,2)."</td>
</tr>
<tr>
  <td colspan='3'></td>
  <td>SGST 9%</td>
  <td>".number_format($sgst,2)."</td>
</tr>
<tr>
  <td colspan='3'>Rs in Words: <strong>{$grandWords}</strong></td>
  <td class='grand-total'>Grand Total</td>
  <td class='grand-total'>".number_format($grandTotal,2)."</td>
</tr>
</table>
</body>
</html>
";

// ---- Output PDF ----
$dompdf = new Dompdf();
$dompdf->set_option('isRemoteEnabled', true);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("invoice-$id.pdf", ["Attachment"=>false]);
