<?php
require_once __DIR__ . '/../../../includes/number_to_words.php';
$hsnSummary = [];
$allRows = [];
$allGstZero = true;
while ($row = $items->fetch_assoc()) {
    $hsn = $row['hsn_code'] ?? '';
    if (!isset($hsnSummary[$hsn])) $hsnSummary[$hsn] = ['taxable'=>0,'gst'=>0,'rate'=>$row['gst_percent']];
    $hsnSummary[$hsn]['taxable'] += $row['taxable_amount'];
    $hsnSummary[$hsn]['gst']     += $row['gst_amount'];
    $allRows[] = $row;
    if ((float)($row['gst_percent'] ?? 0) > 0) $allGstZero = false;
}
$_siPrimaryBank = $company['bank_accounts'][0] ?? null;
?>
<div class="simple-invoice">

<div class="si-accent"></div>

<!-- HEADER -->
<?php if (!empty($isPdf)): ?>
<table style="width:100%;border-collapse:collapse;border-bottom:1.5px solid #2563eb;background:#fff;">
<tr>
  <td style="vertical-align:top;padding:14px 14px 10px;">
    <table style="border-collapse:collapse;"><tr>
      <?php if (!empty($company['logo'])): ?>
      <td style="vertical-align:top;padding-right:10px;">
        <img src="../<?= htmlspecialchars(ltrim($company['logo'],'/')) ?>" style="width:68px;height:68px;object-fit:contain;border-radius:4px;">
      </td>
      <?php endif; ?>
      <td style="vertical-align:top;">
        <div class="si-company-name"><?= htmlspecialchars($company['company_name']) ?></div>
        <div class="si-company-info">
            <?= nl2br(htmlspecialchars($company['address'])) ?><br>
            GSTIN: <?= htmlspecialchars($company['gst_no']) ?><br>
            Ph: <?= htmlspecialchars($company['phone']) ?>
            <?php if (!empty($company['email'])): ?> &nbsp;|&nbsp; Email: <?= htmlspecialchars($company['email']) ?><?php endif; ?>
        </div>
      </td>
    </tr></table>
  </td>
  <td style="vertical-align:top;padding:14px 14px 10px;text-align:right;width:38%;">
    <div class="si-title" style="display:inline-block;"><?= ($inv['status'] === 'final') ? (($inv['total_gst'] ?? 0) == 0 ? 'INVOICE' : 'TAX INVOICE') : ($inv['status'] === 'cancelled' ? 'CANCELLED' : 'QUOTATION') ?></div><br>
    <div style="font-size:10.5px;line-height:1.75;color:#333;margin-top:4px;">
      <div>No: <strong><?= htmlspecialchars($inv['invoice_no']) ?></strong></div>
      <div>Date: <?= date('d-m-Y', strtotime($inv['invoice_date'])) ?></div>
    </div>
    <barcode code="<?= htmlspecialchars($inv['invoice_no']) ?>" type="C128B" style="width:130px;height:32px;display:block;margin:5px 0 0 auto;"></barcode>
  </td>
</tr>
</table>
<?php else: ?>
<div class="si-header">
    <div style="display:flex;align-items:flex-start;gap:12px;">
        <?php if (!empty($company['logo'])): ?>
        <img src="../<?= htmlspecialchars(ltrim($company['logo'],'/')) ?>" style="width:68px;height:68px;object-fit:contain;flex-shrink:0;border-radius:4px;">
        <?php endif; ?>
        <div>
        <div class="si-company-name"><?= htmlspecialchars($company['company_name']) ?></div>
        <div class="si-company-info">
            <?= nl2br(htmlspecialchars($company['address'])) ?><br>
            GSTIN: <?= htmlspecialchars($company['gst_no']) ?><br>
            Ph: <?= htmlspecialchars($company['phone']) ?>
            <?php if (!empty($company['email'])): ?> &nbsp;|&nbsp; Email: <?= htmlspecialchars($company['email']) ?><?php endif; ?>
        </div>
        </div>
    </div>
    <div class="si-invoice-meta">
        <div class="si-title"><?= ($inv['status'] === 'final') ? (($inv['total_gst'] ?? 0) == 0 ? 'INVOICE' : 'TAX INVOICE') : ($inv['status'] === 'cancelled' ? 'CANCELLED' : 'QUOTATION') ?></div><br>
        <div>No: <strong><?= htmlspecialchars($inv['invoice_no']) ?></strong></div>
        <div>Date: <?= date('d-m-Y', strtotime($inv['invoice_date'])) ?></div>
        <svg id="barcode" data-invoice="<?= htmlspecialchars($inv['invoice_no']) ?>"></svg>
    </div>
</div>
<?php endif; ?>

<!-- PARTY -->
<?php
$_shipAddr  = !empty($client['ship_address']) ? $client['ship_address'] : ($client['address']  ?? '');
$_shipCity  = !empty($client['ship_city'])    ? $client['ship_city']    : ($client['city']     ?? '');
$_shipState = !empty($client['ship_state'])   ? $client['ship_state']  : ($client['state']    ?? '');
$_shipPin   = !empty($client['ship_pincode']) ? $client['ship_pincode'] : ($client['pincode']  ?? '');
$_billLine2 = implode(', ', array_filter([$client['city'] ?? '', $client['state'] ?? '']));
if (!empty($client['pincode'])) $_billLine2 .= ' - ' . $client['pincode'];
$_shipLine2 = implode(', ', array_filter([$_shipCity, $_shipState]));
if (!empty($_shipPin)) $_shipLine2 .= ' - ' . $_shipPin;
?>
<table style="width:100%;border-collapse:collapse;margin-bottom:6px;font-size:9px;">
<tr>
    <td style="width:50%;vertical-align:top;padding:5px 8px;border:1px solid #ccc;">
        <div style="font-size:7.5px;font-weight:700;letter-spacing:0.6px;color:#555;text-transform:uppercase;margin-bottom:3px;">Bill To / Buyer</div>
        <strong style="font-size:9.5px;"><?= htmlspecialchars($client['name']) ?></strong><br>
        <?php if (!empty($client['address'])): ?><?= nl2br(htmlspecialchars($client['address'])) ?><br><?php endif; ?>
        <?php if (!empty($_billLine2)): ?><?= htmlspecialchars($_billLine2) ?><br><?php endif; ?>
        <?php if (!empty($client['phone'])): ?>Ph: <?= htmlspecialchars($client['phone']) ?><br><?php endif; ?>
        <?php if (!empty($client['email'])): ?>Email: <?= htmlspecialchars($client['email']) ?><br><?php endif; ?>
        <?php if (!empty($client['gstin'])): ?>GSTIN: <?= htmlspecialchars($client['gstin']) ?><?php endif; ?>
    </td>
    <td style="width:50%;vertical-align:top;padding:5px 8px;border:1px solid #ccc;border-left:none;">
        <div style="font-size:7.5px;font-weight:700;letter-spacing:0.6px;color:#555;text-transform:uppercase;margin-bottom:3px;">Ship To</div>
        <strong style="font-size:9.5px;"><?= htmlspecialchars($client['name']) ?></strong><br>
        <?php if (!empty($_shipAddr)): ?><?= nl2br(htmlspecialchars($_shipAddr)) ?><br><?php endif; ?>
        <?php if (!empty($_shipLine2)): ?><?= htmlspecialchars($_shipLine2) ?><br><?php endif; ?>
        <?php if (!empty($client['phone'])): ?>Ph: <?= htmlspecialchars($client['phone']) ?><br><?php endif; ?>
        <?php if (!empty($client['email'])): ?>Email: <?= htmlspecialchars($client['email']) ?><?php endif; ?>
    </td>
</tr>
</table>

<!-- ITEMS — full-width, column widths set on <th> (dompdf ignores <col> styles) -->
<?php
// Dynamic column widths: Sr fixed 5%, Item fixed 30%, remaining 65% split by weight
$_siSrPct   = 5;
$_siItemPct = 30;
$_siRest    = 100 - $_siSrPct - $_siItemPct; // 65%
$_siWeights = ['hsn' => 10, 'mrp' => 9, 'qty' => 5, 'rate' => 10, 'disc' => 8, 'amt' => 12];
if (!$allGstZero) $_siWeights['gst'] = 6;
$_siWTotal  = array_sum($_siWeights);
$_siW       = [];
foreach ($_siWeights as $_k => $_v) $_siW[$_k] = round(($_v / $_siWTotal) * $_siRest, 1);
?>
<table class="si-items">
    <thead>
        <tr>
            <th style="text-align:center;width:<?= $_siSrPct ?>%;">Sr</th>
            <th style="text-align:left;width:<?= $_siItemPct ?>%;">Item Description</th>
            <th style="width:<?= $_siW['hsn'] ?>%;">HSN</th>
            <th style="width:<?= $_siW['mrp'] ?>%;">MRP</th>
            <th style="width:<?= $_siW['qty'] ?>%;">Qty</th>
            <th style="width:<?= $_siW['rate'] ?>%;">Rate</th>
            <th style="width:<?= $_siW['disc'] ?>%;">Disc</th>
            <?php if (!$allGstZero): ?><th style="width:<?= $_siW['gst'] ?>%;">GST%</th><?php endif; ?>
            <th style="text-align:right;width:<?= $_siW['amt'] ?>%;">Amount</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($allRows as $i => $row):
        $discText = '-';
        if ($row['discount_type'] === 'percent') $discText = $row['discount_value'].'%';
        elseif ($row['discount_type'] === 'amount') $discText = '&#8377;'.number_format($row['discount_value'],2);
    ?>
    <tr>
        <td class="c"><?= $i+1 ?></td>
        <td>
            <?= htmlspecialchars($row['product_name']) ?>
            <?php if (!empty($row['description'])): ?>
            <div class="si-desc"><?= nl2br(htmlspecialchars($row['description'])) ?></div>
            <?php endif; ?>
        </td>
        <td class="c"><?= htmlspecialchars($row['hsn_code'] ?? '') ?></td>
        <td class="r"><?= ($row['mrp'] ?? 0) > 0 ? number_format($row['mrp'],2) : '-' ?></td>
        <td class="r"><?= number_format($row['sold_qty'],0) ?></td>
        <td class="r"><?= number_format($row['selling_price_incl'],2) ?></td>
        <td class="c"><?= $discText ?></td>
        <?php if (!$allGstZero): ?><td class="c"><?= $row['gst_percent'] ?>%</td><?php endif; ?>
        <td class="r"><strong><?= number_format($row['total_amount'],2) ?></strong></td>
    </tr>
    <?php endforeach; ?>
    <?php
    $fillerCount = empty($isPdf) ? max(0, 11 - count($allRows)) : 0;
    for ($f = 0; $f < $fillerCount; $f++):
    ?>
    <tr class="si-filler-row">
        <td></td><td></td><td></td><td></td><td></td><td></td><td></td><?= $allGstZero ? '' : '<td></td>' ?><td></td>
    </tr>
    <?php endfor; ?>
    </tbody>
</table>

<!-- ====================================================
     BOTTOM SECTION — kept together on print
     ==================================================== -->
<div class="si-bottom">

<!-- TOTALS -->
<div class="si-totals-wrap"<?= !empty($isPdf) ? ' style="display:block;overflow:hidden;"' : '' ?>>
    <table class="si-totals"<?= !empty($isPdf) ? ' style="float:right;"' : '' ?>>
        <?php if (!$allGstZero): ?>
        <tr><td>Taxable Amount</td><td>&#8377; <?= number_format($inv['total_taxable'],2) ?></td></tr>
        <tr><td>CGST</td><td>&#8377; <?= number_format($inv['total_gst']/2,2) ?></td></tr>
        <tr><td>SGST</td><td>&#8377; <?= number_format($inv['total_gst']/2,2) ?></td></tr>
        <?php endif; ?>
        <?php if (!empty($inv['overall_discount_value'])): ?>
        <tr><td>Discount</td><td>&minus; &#8377; <?= number_format($inv['overall_discount_value'],2) ?></td></tr>
        <?php endif; ?>
        <tr class="si-grand"><td>Grand Total</td><td>&#8377; <?= number_format($inv['net_total'],2) ?></td></tr>
        <?php if (($inv['received_amount'] ?? 0) > 0): ?>
        <tr><td style="color:#15803d;">Received</td><td style="color:#15803d;">&#8377; <?= number_format($inv['received_amount'],2) ?></td></tr>
        <tr><td style="color:<?= $inv['balance_amount']>0?'#b91c1c':'#15803d' ?>;">Balance</td>
            <td style="color:<?= $inv['balance_amount']>0?'#b91c1c':'#15803d' ?>;">&#8377; <?= number_format($inv['balance_amount'],2) ?></td></tr>
        <?php endif; ?>
    </table>
    <?php if (!empty($isPdf)): ?><div style="clear:both;"></div><?php endif; ?>
</div>

<!-- AMOUNT IN WORDS -->
<div class="si-words">
    Amount in words: <strong><?= numberToWords(round($inv['net_total'])) ?></strong>
</div>

<!-- HSN SUMMARY -->
<?php if (!$allGstZero): ?>
<table class="si-hsn">
    <thead>
        <tr>
            <th>HSN Code</th>
            <th style="text-align:right;">Taxable Amt</th>
            <th>GST %</th>
            <th style="text-align:right;">CGST</th>
            <th style="text-align:right;">SGST</th>
            <th style="text-align:right;">Total GST</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($hsnSummary as $hsn => $d): ?>
    <tr>
        <td class="c"><?= htmlspecialchars($hsn) ?></td>
        <td class="r">&#8377; <?= number_format($d['taxable'],2) ?></td>
        <td class="c"><?= $d['rate'] ?>%</td>
        <td class="r">&#8377; <?= number_format($d['gst']/2,2) ?></td>
        <td class="r">&#8377; <?= number_format($d['gst']/2,2) ?></td>
        <td class="r">&#8377; <?= number_format($d['gst'],2) ?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<!-- BANK + QR -->
<?php if (!empty($isPdf)): ?>
<?php
$_siPrimaryBank = $company['bank_accounts'][0] ?? null;
$_siHasUpi = $_siPrimaryBank && !empty($_siPrimaryBank['upi_id']);
if ($_siHasUpi) {
    $_siUpiName = !empty($_siPrimaryBank['upi_name']) ? $_siPrimaryBank['upi_name'] : $company['company_name'];
    if (!empty($hasPHPQR)) {
        $_siUpiStr = 'upi://pay?pa=' . urlencode($_siPrimaryBank['upi_id']) . '&pn=' . urlencode($_siUpiName) . '&am=' . number_format($inv['net_total'], 2, '.', '');
        ob_start(); QRcode::png($_siUpiStr, false, QR_ECLEVEL_M, 3, 2); $_siQrPng = ob_get_clean();
        $_siQrSrc = 'data:image/png;base64,' . base64_encode($_siQrPng);
    }
}
?>
<table style="width:100%;border-collapse:collapse;border-bottom:1px solid #dde3ea;background:#fff;">
<tr>
  <td style="vertical-align:top;padding:8px 14px;font-size:10px;line-height:1.6;<?= $_siHasUpi ? 'border-right:1px solid #dde3ea;' : '' ?>">
    <strong style="color:#1e3a5f;font-size:10.5px;">Bank Details:</strong>
    <?php foreach ($company['bank_accounts'] as $b): ?>
    <table style="border:none;border-collapse:collapse;font-size:8px;line-height:1.5;margin-top:4px;">
        <tr><td style="padding:0 0 1px;white-space:nowrap;color:#555;width:75px;">Bank</td><td style="padding:0 3px;">:</td><td style="padding:0 0 1px;"><b><?= htmlspecialchars($b['bank_name']) ?></b><?= $b['is_primary'] ? ' <span style="color:#2563eb;">(Primary)</span>' : '' ?></td></tr>
        <?php if ($b['account_holder']): ?><tr><td style="padding:0 0 1px;color:#555;">A/c Holder</td><td style="padding:0 3px;">:</td><td style="padding:0 0 1px;"><?= htmlspecialchars($b['account_holder']) ?></td></tr><?php endif; ?>
        <tr><td style="padding:0 0 1px;color:#555;">Account No</td><td style="padding:0 3px;">:</td><td style="padding:0 0 1px;"><?= htmlspecialchars($b['account_no']) ?></td></tr>
        <tr><td style="padding:0 0 1px;color:#555;">IFSC Code</td><td style="padding:0 3px;">:</td><td style="padding:0 0 1px;"><?= htmlspecialchars($b['ifsc']) ?></td></tr>
        <?php if ($b['branch']): ?><tr><td style="padding:0;color:#555;">Branch</td><td style="padding:0 3px;">:</td><td style="padding:0;"><?= htmlspecialchars($b['branch']) ?></td></tr><?php endif; ?>
    </table>
    <?php endforeach; ?>
  </td>
  <?php if ($_siHasUpi): ?>
  <td style="vertical-align:middle;padding:8px 10px;text-align:center;width:130px;">
    <?php if (!empty($hasPHPQR)): ?>
    <div style="font-size:9px;font-weight:700;color:#1e3a5f;margin-bottom:3px;">Scan &amp; Pay</div>
    <img src="<?= $_siQrSrc ?>" style="width:90px;height:90px;display:block;margin:0 auto 3px;">
    <div style="font-size:9.5px;font-weight:800;color:#1e3a5f;"><?= htmlspecialchars($_siUpiName) ?></div>
    <div style="font-size:11px;font-weight:900;color:#15803d;margin-top:2px;">&#8377; <?= number_format($inv['net_total'],2) ?></div>
    <?php else: ?>
    <div style="border:1px solid #c5d0e8;border-radius:4px;padding:6px 10px;display:inline-block;">
        <div style="font-size:9px;font-weight:700;color:#1e3a5f;margin-bottom:2px;">Pay via UPI</div>
        <div style="font-size:9.5px;font-weight:800;color:#1e3a5f;"><?= htmlspecialchars($_siUpiName) ?></div>
        <div style="font-size:8px;color:#666;margin-top:1px;"><?= htmlspecialchars($_siPrimaryBank['upi_id']) ?></div>
        <div style="font-size:11px;font-weight:900;color:#15803d;margin-top:3px;">&#8377; <?= number_format($inv['net_total'],2) ?></div>
    </div>
    <?php endif; ?>
  </td>
  <?php endif; ?>
</tr>
</table>
<?php else: ?>
<div class="si-bank">
    <div>
        <strong style="color:#1e3a5f;">Bank Details:</strong>
        <div class="si-bank-list" style="margin-top:4px;">
        <?php foreach ($company['bank_accounts'] as $b): ?>
        <div class="si-bank-item">
            <table style="border:none;border-collapse:collapse;font-size:7.5px;line-height:1.5;">
                <tr><td style="padding:0;white-space:nowrap;">Bank</td><td style="padding:0 4px;">:</td><td style="padding:0;"><b><?= htmlspecialchars($b['bank_name']) ?></b><?= $b['is_primary'] ? ' <span style="color:#2563eb;font-size:9px;">(Primary)</span>' : '' ?></td></tr>
                <?php if ($b['account_holder']): ?><tr><td style="padding:0;white-space:nowrap;">Account Holder</td><td style="padding:0 4px;">:</td><td style="padding:0;"><?= htmlspecialchars($b['account_holder']) ?></td></tr><?php endif; ?>
                <tr><td style="padding:0;white-space:nowrap;">Account No</td><td style="padding:0 4px;">:</td><td style="padding:0;"><?= htmlspecialchars($b['account_no']) ?></td></tr>
                <tr><td style="padding:0;white-space:nowrap;">IFSC Code</td><td style="padding:0 4px;">:</td><td style="padding:0;"><?= htmlspecialchars($b['ifsc']) ?></td></tr>
                <?php if ($b['branch']): ?><tr><td style="padding:0;white-space:nowrap;">Branch</td><td style="padding:0 4px;">:</td><td style="padding:0;"><?= htmlspecialchars($b['branch']) ?></td></tr><?php endif; ?>
            </table>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php if ($_siPrimaryBank && !empty($_siPrimaryBank['upi_id'])): ?>
    <div class="si-qr">
        <div id="upiQR"
             data-upi="<?= htmlspecialchars($_siPrimaryBank['upi_id']) ?>"
             data-name="<?= htmlspecialchars($_siPrimaryBank['upi_name'] ?? '') ?>"
             data-amount="<?= number_format($inv['net_total'],2,'.','') ?>"></div>
        <div>&#8377; <?= number_format($inv['net_total'],2) ?></div>
        <div>Scan &amp; Pay</div>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- FOOTER -->
<?php if (!empty($isPdf)): ?>
<table style="width:100%;border-collapse:collapse;border-top:2px solid #2563eb;">
<tr>
  <td style="vertical-align:top;padding:8px 14px;font-size:10px;line-height:1.6;">
    <strong>Declaration:</strong><br>
    - Goods once sold will not be taken back.<br>
    - Warranty as per manufacturer's terms only.<br>
    - If the bill is not paid within 7 days, interest will be charged 5% per Month.<br>
    - Subject to Dhanbad Jurisdiction only.
  </td>
  <td style="vertical-align:top;padding:8px 14px;text-align:right;font-size:10px;line-height:1.6;width:200px;">
    For <strong><?= htmlspecialchars($company['company_name']) ?></strong><br>
    <?php if (!empty($company['signature'])): ?>
    <img src="../<?= htmlspecialchars(ltrim($company['signature'],'/')) ?>"
         style="height:70px;max-width:180px;object-fit:contain;display:block;margin:8px 0 4px auto;transform:rotate(-30deg);transform-origin:center;">
    <?php else: ?>
    <div style="height:70px;"></div>
    <?php endif; ?>
    Authorised Signatory
  </td>
</tr>
</table>
<?php else: ?>
<div class="si-footer">
    <div>
        <strong>Declaration:</strong><br>
        - Goods once sold will not be taken back.<br>
        - Warranty as per manufacturer's terms only.<br>
        - If the bill is not paid within 7 days, interest will be charged 5% per Month.<br>
        - Subject to Dhanbad Jurisdiction only.
    </div>
    <div class="si-sign">
        For <strong><?= htmlspecialchars($company['company_name']) ?></strong><br>
        <?php if (!empty($company['signature'])): ?>
        <img src="../<?= htmlspecialchars(ltrim($company['signature'],'/')) ?>"
             style="height:70px;max-width:180px;object-fit:contain;display:block;margin:8px 0 4px;transform:rotate(-30deg);transform-origin:center;">
        <?php else: ?>
        <div style="height:70px;"></div>
        <?php endif; ?>
        Authorised Signatory
    </div>
</div>
<?php endif; ?>

</div><!-- /.si-bottom -->

<div style="text-align:center;font-size:10.5px;color:#555;padding:5px 12px;background:#f5f5f5;margin-top:4px;">
    This is a computer-generated invoice. No signature required. Thank you for your valued business!
</div>

</div><!-- /.simple-invoice -->
