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

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

// ====== Fetch invoice ======
$stmt = $conn->prepare("SELECT * FROM invoices WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$result  = $stmt->get_result();
$invoice = $result->fetch_assoc();
if (!$invoice) die('Invoice not found.');

// ====== Basic invoice fields ======
$invoiceNo   = htmlspecialchars($invoice['invoice_id']);
$invoiceDate = date('d-m-Y', strtotime($invoice['invoice_date']));
$partyName   = htmlspecialchars($invoice['party_name']);
$businessName= htmlspecialchars($invoice['business_name']);
$partyAddr   = nl2br(htmlspecialchars($invoice['party_address']));
$partyGst    = htmlspecialchars($invoice['gst_number']);

// ====== Products JSON decode ======
$productsJson = $invoice['products_json'] ?? '';
$products = json_decode(stripslashes($productsJson), true);

$itemsHtml = '';
$total = 0;  

if (json_last_error() === JSON_ERROR_NONE && is_array($products)) {
    foreach ($products as $p) {
        $name   = htmlspecialchars($p['name']);
        $qty    = (float)$p['quantity'];
        $price  = (float)$p['sell_price'];
        $hsncode   = htmlspecialchars($p['hsn_code']);
        $amount = $qty * $price; 
        $total += $amount;

        $itemsHtml .= "<tr>
            <td style='width: 40%;'>{$name}</td>
            <td style='width: 20%; text-align:center;'>{$hsncode}</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>";
    }
} else {
    $itemsHtml = "<tr><td colspan='5'>No products found or invalid JSON</td></tr>";
}

// ===== Totals =====
$cgst = $total * 0.09;
$sgst = $total * 0.09;
$grandTotal = $total + $cgst + $sgst;

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 != 0 ? ' ' . $ones[$num % 10] : '');
    if ($num < 1000) return $ones[intval($num / 100)] . ' Hundred' . ($num % 100 != 0 ? ' and ' . numberToWords($num % 100) : '');
    if ($num < 100000) return numberToWords(intval($num / 1000)) . ' Thousand' . ($num % 1000 != 0 ? ' ' . numberToWords($num % 1000) : '');
    if ($num < 10000000) return numberToWords(intval($num / 100000)) . ' Lakh' . ($num % 100000 != 0 ? ' ' . numberToWords($num % 100000) : '');
    return numberToWords(intval($num / 10000000)) . ' Crore' . ($num % 10000000 != 0 ? ' ' . numberToWords($num % 10000000) : '');
}

$grandTotalRounded = round($grandTotal);
$grandTotalWords = numberToWords($grandTotalRounded) . ' Rupees Only';


$html = "
<!DOCTYPE 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; font-size:12px; }
.outer { border:2px solid #000; width:98%; margin:10px auto; }
.header { background:#8ee1e8; text-align:center; padding:8px; }
h1 { margin:0; font-size:22px; }
.grand-total { background:#007070; color:#fff; font-weight:bold; text-align:right; }
.section-light { background:#c3f4f9; }
</style>
</head>
<body>

<table class='outer'>
  <tr>
    <td style='border:none;'>
      <table width='100%'>
        <tr>
          <td style='border:none; font-weight:bold;'>M. 8104333664</td>
          <td style='border:none; text-align:right;'>INVOICE NO : {$invoiceNo}<br>DATE : {$invoiceDate}</td>
        </tr>
      </table>
    </td>
  </tr>

  <tr><td class='header'>
      <h1>Kumawat Computer & Cyber Cafe</h1>
      Behind of Vedanta College, Reengus (Sikar) Raj. 332404<br>
      All Type of Computer, Laptop, Parts & Printer Sale & Service 
  </td></tr>

  <tr><td class='section-light'>
      <strong>{$partyName}</strong><br>
      {$businessName}<br>
      {$partyAddr}<br>
      GSTIN: {$partyGst}
  </td></tr>

  <tr>
    <td>
      <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='2' style='text-align:justify; border-top:none;border-bottom:none;'><strong>Bank: HDFC Bank, Reengus</strong></td> 
          <td colspan='2' style='text-align:right;font-weight:bold;'>Total</td>
          <td style='text-align:center;'>{$total}</td>
        </tr>
        <tr> 
          <td colspan='2' style='text-align:justify; border-top:none;border-bottom:none;'><strong>A/c No.: 50200050229978</strong></td> 
          <td colspan='2' style='text-align:right;'>Add : CGST @ 9%</td>
          <td style='text-align:center;'>{$cgst}</td>
        </tr>
        <tr>
          <td colspan='2' style='text-align:justify; border-top:none;border-bottom:none;'><strong>IFSC: HDFC0008996</strong></td> 
          <td colspan='2' style='text-align:right; border-top:none;border-bottom:none;'>Add : SGST @ 9%</td>
          <td style='text-align:center;'>{$sgst}</td>
        </tr>
        <tr >
         <td colspan='2' style='text-align:justify; word-spacing: 0px;'><span style='word-spacing: 0px;'>Rs in Words:</span> <strong>{$grandTotalWords}</strong></td> 
          <td colspan='2' class='grand-total'>Grand Total</td>
          <td style='text-align:center;' class='grand-total'>{$grandTotal}</td>
        </tr>
      </table>
    </td>
  </tr>

  <tr>
  <table width='100%'>
  <tr>
    <td style='border:none; padding:6px;'>
      <strong>Terms & Conditions</strong><br>
      1. All Subject to Reengus Jurisdiction.<br>2. Interest @24%p.a. will charged after due date.<br>3. E.& O.E.
    </td> 
    <td style='border:none; padding:6px;'>
      <td style='border:none; padding:6px; text-align:right; vertical-align:top;'>
      For- <strong>Kumawat Computer & Cyber Cafe</strong><br>
        <img src='https://shivfood.clicksoft.in/kumawat/assets/images/sign/5.png' alt='Logo' style='max-width:100px; height:auto;'>
      </td>
    </td> 
    </tr>
    
    </table>
  </tr>
</table>

</body>
</html>
";

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


// <?php
// require 'dompdf/vendor/autoload.php';
// use Dompdf\Dompdf;

// require_once __DIR__ . '/../inc/db.php';

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

// $stmt = $conn->prepare("SELECT * FROM invoices WHERE id = ?");
// $stmt->bind_param('i', $id);
// $stmt->execute();
// $result = $stmt->get_result();
// $invoice = $result->fetch_assoc();
// if (!$invoice) {
//     die('Invoice not found.');
// }

// // HTML कैप्चर करें
// ob_start();
// include 'invoice-template.php'; // सिर्फ़ इनवॉइस का HTML
// $html = ob_get_clean();

// $dompdf = new Dompdf();
// $dompdf->loadHtml($html);
// $dompdf->setPaper('A4', 'portrait');
// $dompdf->render();

// // ✅ नया टैब में दिखाने के लिए Attachment false
// $dompdf->stream("Invoice-$id.pdf", ["Attachment" => false]);
