<?php
require_once __DIR__ . '/../../../includes/number_to_words.php';

$hsnSummary = [];
$allRows    = [];

$items->data_seek(0);
while ($row = $items->fetch_assoc()) {
    $hsn = $row['hsn_code'] ?? '';
    if (!isset($hsnSummary[$hsn])) {
        $hsnSummary[$hsn] = ['taxable'=>0,'cgst'=>0,'sgst'=>0,'rate'=>$row['gst_percent']];
    }
    $hsnSummary[$hsn]['taxable'] += $row['taxable_amount'];
    $hsnSummary[$hsn]['cgst']    += $row['gst_amount'] / 2;
    $hsnSummary[$hsn]['sgst']    += $row['gst_amount'] / 2;
    $allRows[] = $row;
}

$exactTotal   = $inv['total_taxable'] + $inv['total_gst'];
$roundedTotal = round($exactTotal);
$roundOff     = $roundedTotal - $exactTotal;
$totalQty     = array_sum(array_column($allRows, 'sold_qty'));
$primaryBank  = $company['bank_accounts'][0] ?? null;
?>

<div class="tally-invoice">

<!-- ══ TOP BAR ══ -->
<?php if (!empty($isPdf)): ?>
<table style="width:100%;border-collapse:collapse;border-bottom:1px solid #000;background:#f0f0f0;">
<tr>
  <td style="padding:3px 10px;font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;"><?= ($inv['status'] === 'final') ? (floatval($inv['total_gst'] ?? 0) == 0 ? 'Invoice' : 'Tax Invoice') : ($inv['status'] === 'cancelled' ? 'Cancelled' : 'Quotation / Estimate') ?></td>
  <td style="padding:3px 10px;text-align:right;font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;">Original For Recipient</td>
</tr>
</table>
<?php else: ?>
<div class="ti-topbar">
    <span><?= ($inv['status'] === 'final') ? (floatval($inv['total_gst'] ?? 0) == 0 ? 'Invoice' : 'Tax Invoice') : ($inv['status'] === 'cancelled' ? 'Cancelled' : 'Quotation / Estimate') ?></span>
    <span>Original For Recipient</span>
</div>
<?php endif; ?>

<!-- ══ HEADER ══ -->
<table class="ti-head-table">
<tr>
    <td class="ti-head-left">
        <?php if (!empty($isPdf)): ?>
        <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:70px;height:70px;object-fit:contain;">
          </td>
          <?php endif; ?>
          <td style="vertical-align:top;">
            <div class="ti-company-name"><?= htmlspecialchars($company['company_name']) ?></div>
            <div class="ti-company-sub">
                GSTIN: <strong><?= htmlspecialchars($company['gst_no']) ?></strong><br>
                <?= nl2br(htmlspecialchars($company['address'])) ?><br>
                Ph: <?= htmlspecialchars($company['phone']) ?>
                <?php if (!empty($company['email'])): ?><br>Email: <?= htmlspecialchars($company['email']) ?><?php endif; ?>
            </div>
          </td>
        </tr></table>
        <?php else: ?>
        <div class="ti-head-company">
            <?php if (!empty($company['logo'])): ?>
            <img src="../<?= htmlspecialchars(ltrim($company['logo'],'/')) ?>" class="ti-logo">
            <?php endif; ?>
            <div>
                <div class="ti-company-name"><?= htmlspecialchars($company['company_name']) ?></div>
                <div class="ti-company-sub">
                    GSTIN: <strong><?= htmlspecialchars($company['gst_no']) ?></strong><br>
                    <?= nl2br(htmlspecialchars($company['address'])) ?><br>
                    Ph: <?= htmlspecialchars($company['phone']) ?>
                    <?php if (!empty($company['email'])): ?><br>Email: <?= htmlspecialchars($company['email']) ?><?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </td>
    <td class="ti-head-right">
        <table class="ti-meta-table">
            <tr>
                <td>
                    <div class="ti-meta-k">Invoice No.</div>
                    <div class="ti-meta-v"><?= htmlspecialchars($inv['invoice_no']) ?></div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="ti-meta-k">Invoice Date</div>
                    <div class="ti-meta-v"><?= date('d-M-Y', strtotime($inv['invoice_date'])) ?></div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="ti-meta-k">Place of Supply</div>
                    <div class="ti-meta-v"><?= htmlspecialchars($client['state'] ?? '—') ?></div>
                </td>
            </tr>
            <tr>
                <td style="border-bottom:none;">
                    <?php if (!empty($isPdf)): ?>
                    <barcode code="<?= htmlspecialchars($inv['invoice_no']) ?>" type="C128B" style="width:130px;height:28px;display:block;margin-top:2px;"></barcode>
                    <?php else: ?>
                    <svg id="barcode" data-invoice="<?= htmlspecialchars($inv['invoice_no']) ?>"
                         style="display:block;max-width:140px;height:34px;margin-top:4px;"></svg>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
    </td>
</tr>
</table>

<!-- ══ 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 class="ti-party-table">
<tr>
    <td class="ti-party-left">
        <div class="ti-party-section-label">Bill To / Buyer</div>
        <strong><?= 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: <strong><?= htmlspecialchars($client['gstin']) ?></strong><?php endif; ?>
    </td>
    <td class="ti-party-right">
        <div class="ti-party-section-label">Ship To</div>
        <strong><?= 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 TABLE ══ -->
<table class="ti-items">
    <thead>
        <tr>
            <th style="width:4%">Sr</th>
            <th style="width:30%;text-align:left;">Particulars</th>
            <th style="width:9%">HSN/SAC</th>
            <th style="width:5%">Unit</th>
            <th style="width:6%">Qty</th>
            <th style="width:7%">MRP</th>
            <th style="width:9%">Rate</th>
            <th style="width:7%">Disc</th>
            <th style="width:5%">GST%</th>
            <th style="width:9%">Taxable</th>
            <th style="width:9%;text-align:right;">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']) ?></td>
        <td class="c"><?= htmlspecialchars($row['hsn_code']) ?></td>
        <td class="c"><?= htmlspecialchars($row['unit'] ?? '') ?></td>
        <td class="r"><?= number_format($row['sold_qty'],0) ?></td>
        <td class="r"><?= $row['mrp'] > 0 ? number_format($row['mrp'],2) : '-' ?></td>
        <td class="r"><?= number_format($row['selling_price_incl'],2) ?></td>
        <td class="c"><?= $discText ?></td>
        <td class="c"><?= number_format($row['gst_percent'],0) ?>%</td>
        <td class="r"><?= number_format($row['taxable_amount'],2) ?></td>
        <td class="r"><?= number_format($row['total_amount'],2) ?></td>
    </tr>
    <?php endforeach; ?>
    <?php $fillerCount = max(0, 20 - count($allRows)); for ($f = 0; $f < $fillerCount; $f++): ?>
    <tr class="ti-filler-row"><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
    <?php endfor; ?>
    </tbody>
</table>

<!-- ══ TOTALS TABLE ══ -->
<table class="ti-totals-table">
    <colgroup>
        <col style="width:82%">
        <col style="width:9%">
        <col style="width:9%">
    </colgroup>
    <tbody>
        <tr class="ti-subtotal-row">
            <td style="text-align:right;">Taxable Amount</td>
            <td class="r"><?= number_format($inv['total_taxable'],2) ?></td>
            <td class="r"><?= number_format($inv['total_taxable'],2) ?></td>
        </tr>
        <tr class="ti-subtotal-row">
            <td style="text-align:right;">CGST</td>
            <td class="r"><?= number_format($inv['total_gst']/2,2) ?></td>
            <td class="r"><?= number_format($inv['total_gst']/2,2) ?></td>
        </tr>
        <tr class="ti-subtotal-row">
            <td style="text-align:right;">SGST</td>
            <td class="r"><?= number_format($inv['total_gst']/2,2) ?></td>
            <td class="r"><?= number_format($inv['total_gst']/2,2) ?></td>
        </tr>
        <?php if (abs($roundOff) > 0.001): ?>
        <tr class="ti-subtotal-row">
            <td style="text-align:right;">Round Off</td>
            <td class="r"><?= number_format($roundOff,2) ?></td>
            <td class="r"><?= number_format($roundOff,2) ?></td>
        </tr>
        <?php endif; ?>
        <tr class="ti-grand-row">
            <td style="text-align:right;">Total &nbsp; <span style="font-size:9px;font-weight:400;color:#ddd;"><?= number_format($totalQty,0) ?> item(s)</span></td>
            <td></td>
            <td class="r">&#8377; <?= number_format($roundedTotal,2) ?></td>
        </tr>
    </tbody>
</table>

<!-- ══ BOTTOM GROUP (pushed to page end when items are few) ══ -->
<div class="ti-bottom">

<!-- ══ AMOUNT IN WORDS ══ -->
<div class="ti-words">
    <strong>Amount Chargeable (in words):</strong> INR <?= numberToWords($roundedTotal) ?> Only. &nbsp; <em>E &amp; O.E</em>
</div>

<!-- ══ HSN SUMMARY ══ -->
<div class="ti-hsn-section">
    <div class="ti-hsn-title">HSN / SAC Wise Tax Summary</div>
    <table class="ti-hsn">
        <thead>
            <tr>
                <th rowspan="2">HSN/SAC</th>
                <th rowspan="2">Taxable Value</th>
                <th colspan="2">Central Tax</th>
                <th colspan="2">State / UT Tax</th>
                <th rowspan="2">Total Tax Amount</th>
            </tr>
            <tr>
                <th>Rate</th><th>Amount</th>
                <th>Rate</th><th>Amount</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($hsnSummary as $hsn => $d): ?>
        <tr>
            <td class="c"><?= htmlspecialchars($hsn) ?></td>
            <td class="r"><?= number_format($d['taxable'],2) ?></td>
            <td class="c"><?= $d['rate']/2 ?>%</td>
            <td class="r"><?= number_format($d['cgst'],2) ?></td>
            <td class="c"><?= $d['rate']/2 ?>%</td>
            <td class="r"><?= number_format($d['sgst'],2) ?></td>
            <td class="r"><?= number_format($d['cgst']+$d['sgst'],2) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td><strong>TOTAL</strong></td>
                <td class="r"><strong><?= number_format($inv['total_taxable'],2) ?></strong></td>
                <td></td>
                <td class="r"><strong><?= number_format($inv['total_gst']/2,2) ?></strong></td>
                <td></td>
                <td class="r"><strong><?= number_format($inv['total_gst']/2,2) ?></strong></td>
                <td class="r"><strong><?= number_format($inv['total_gst'],2) ?></strong></td>
            </tr>
        </tfoot>
    </table>
</div>

<!-- ══ BANK | QR | SIGN ══ -->
<?php if (!empty($isPdf)): ?>
<?php $_tiUpiName = !empty($primaryBank['upi_name']) ? $primaryBank['upi_name'] : $company['company_name']; ?>
<table style="width:100%;border-collapse:collapse;border-bottom:1px solid #000;">
<tr>
  <td style="vertical-align:top;padding:7px 10px;border-right:1px solid #000;font-size:9.5px;line-height:1.65;">
    <strong>Bank Details:</strong>
    <?php foreach ($company['bank_accounts'] as $b): ?>
    <div class="ti-bank-entry">
        <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;"><strong><?= htmlspecialchars($b['bank_name']) ?></strong></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; ?>
  </td>
  <?php if ($primaryBank && !empty($primaryBank['upi_id'])): ?>
  <td style="vertical-align:middle;padding:7px 6px;border-right:1px solid #000;text-align:center;width:130px;">
    <?php if (!empty($hasPHPQR)):
        $_tiUpiStr = 'upi://pay?pa=' . urlencode($primaryBank['upi_id']) . '&pn=' . urlencode($_tiUpiName) . '&am=' . number_format($roundedTotal, 2, '.', '');
        ob_start(); QRcode::png($_tiUpiStr, false, QR_ECLEVEL_M, 3, 2); $_tiQrPng = ob_get_clean();
        $_tiQrSrc = 'data:image/png;base64,' . base64_encode($_tiQrPng);
    ?>
    <div style="font-size:9px;font-weight:700;color:#000;margin-bottom:2px;">Scan &amp; Pay</div>
    <img src="<?= $_tiQrSrc ?>" style="width:90px;height:90px;display:block;margin:0 auto 2px;">
    <div style="font-size:10px;font-weight:800;color:#000;"><?= htmlspecialchars($_tiUpiName) ?></div>
    <div style="font-size:11px;font-weight:900;color:#000;margin-top:2px;">&#8377; <?= number_format($roundedTotal,2) ?></div>
    <?php else: ?>
    <div style="font-size:9px;font-weight:700;color:#000;margin-bottom:2px;">Pay via UPI</div>
    <div style="font-size:10px;font-weight:800;color:#000;"><?= htmlspecialchars($_tiUpiName) ?></div>
    <div style="font-size:8px;color:#555;margin-top:1px;"><?= htmlspecialchars($primaryBank['upi_id']) ?></div>
    <div style="font-size:11px;font-weight:900;color:#000;margin-top:3px;">&#8377; <?= number_format($roundedTotal,2) ?></div>
    <?php endif; ?>
  </td>
  <?php endif; ?>
  <td style="vertical-align:top;padding:7px 10px;text-align:right;font-size:10px;width:185px;">
    <div>For <strong><?= htmlspecialchars($company['company_name']) ?></strong></div>
    <?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:50px;"></div>
    <?php endif; ?>
    <div>Authorised Signatory</div>
  </td>
</tr>
</table>
<?php else: ?>
<div class="ti-footer-row">
    <div class="ti-bank-col">
        <strong>Bank Details:</strong>
        <?php foreach ($company['bank_accounts'] as $b): ?>
        <div class="ti-bank-entry">
            <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;"><strong><?= htmlspecialchars($b['bank_name']) ?></strong></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>

    <?php if ($primaryBank && !empty($primaryBank['upi_id'])): ?>
    <div class="ti-qr-col">
        <div id="upiQR"
             data-upi="<?= htmlspecialchars($primaryBank['upi_id']) ?>"
             data-name="<?= htmlspecialchars($primaryBank['upi_name'] ?? $company['company_name']) ?>"
             data-amount="<?= number_format($roundedTotal,2,'.','') ?>"></div>
        <div class="ti-qr-lbl">Pay using UPI</div>
        <div class="ti-qr-amt">&#8377; <?= number_format($roundedTotal,2) ?></div>
    </div>
    <?php endif; ?>

    <div class="ti-sign-col">
        <div>For <strong><?= htmlspecialchars($company['company_name']) ?></strong></div>
        <?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 class="ti-sign-space"></div>
        <?php endif; ?>
        <div>Authorised Signatory</div>
    </div>
</div>
<?php endif; ?>

<!-- ══ DECLARATION / TERMS ══ -->
<div class="ti-decl">
    <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><!-- /.ti-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>
