<?php
$time = date('h:i A', strtotime($inv['created_at'] ?? $inv['invoice_date']));

// Collect all items first so we can show count
$itemRows = [];
while ($row = $items->fetch_assoc()) $itemRows[] = $row;

$gross       = 0;
$cgst_total  = 0;
$sgst_total  = 0;
foreach ($itemRows as $r) {
    $gross      += $r['total_amount'];
    $cgst_total += $r['gst_amount'] / 2;
    $sgst_total += $r['gst_amount'] / 2;
}
$allGstZero = floatval($inv['total_gst'] ?? 0) == 0;
?>

<div class="thermal-invoice">

    <?php if (!empty($company['logo'])): ?>
    <div class="th-center">
        <img src="../<?= $company['logo'] ?>" class="th-logo" alt="logo">
    </div>
    <?php endif; ?>

    <!-- Company Header -->
    <div class="th-center th-company"><?= htmlspecialchars($company['company_name']) ?></div>
    <div class="th-center th-addr">
        <?php if (!empty($company['address'])): ?><?= nl2br(htmlspecialchars($company['address'])) ?><br><?php endif; ?>
        <?php if (!empty($company['gst_no'])): ?>GSTIN: <?= htmlspecialchars($company['gst_no']) ?><br><?php endif; ?>
        <?php if (!empty($company['phone'])): ?>Ph: <?= htmlspecialchars($company['phone']) ?><?php endif; ?>
    </div>

    <div class="th-dashed"></div>

    <div class="th-center th-title">
        &#9733; <?= ($inv['status'] === 'final') ? ($allGstZero ? 'INVOICE' : 'TAX INVOICE') : 'QUOTATION' ?> &#9733;
    </div>

    <div class="th-dashed"></div>

    <!-- Bill Info -->
    <table class="th-info">
        <tr>
            <td>Bill No</td>
            <td><strong><?= htmlspecialchars($inv['invoice_no']) ?></strong></td>
        </tr>
        <tr>
            <td>Date</td>
            <td><?= date('d-m-Y', strtotime($inv['invoice_date'])) ?> <?= $time ?></td>
        </tr>
        <tr>
            <td>Customer</td>
            <td><strong><?= htmlspecialchars($client['name']) ?></strong></td>
        </tr>
        <?php if (!empty($client['phone'])): ?>
        <tr><td>Mobile</td><td><?= htmlspecialchars($client['phone']) ?></td></tr>
        <?php endif; ?>
        <?php if (!empty($client['gstin'])): ?>
        <tr><td>GSTIN</td><td><?= htmlspecialchars($client['gstin']) ?></td></tr>
        <?php endif; ?>
        <?php if (!empty($inv['payment_mode'])): ?>
        <tr><td>Pay Mode</td><td><?= htmlspecialchars($inv['payment_mode']) ?></td></tr>
        <?php endif; ?>
    </table>

    <div class="th-dashed"></div>

    <!-- Items -->
    <table class="th-items">
        <thead>
            <tr>
                <th class="c-item">ITEM</th>
                <th class="c-qty">QTY</th>
                <th class="c-rate">RATE</th>
                <th class="c-amt">AMT</th>
            </tr>
        </thead>
        <tbody>
        <?php $total_items = count($itemRows); foreach ($itemRows as $idx => $row):
            $line = $row['total_amount'];
        ?>
        <tr>
            <td class="c-item">
                <?= htmlspecialchars($row['product_name']) ?>
                <?php if (!empty($row['item_description'])): ?>
                <div class="th-desc"><?= nl2br(htmlspecialchars($row['item_description'])) ?></div>
                <?php endif; ?>
            </td>
            <td class="c-qty"><?= number_format($row['sold_qty'], 0) ?></td>
            <td class="c-rate"><?= number_format($row['selling_price_incl'], 2) ?></td>
            <td class="c-amt"><?= number_format($line, 2) ?></td>
        </tr>
        <?php if ($idx < $total_items - 1): ?>
        <tr class="th-item-sep"><td colspan="4"></td></tr>
        <?php endif; ?>
        <?php endforeach; ?>
        </tbody>
    </table>

    <div class="th-dashed"></div>

    <!-- Totals -->
    <table class="th-totals">
        <tr><td>Subtotal</td><td><?= number_format($gross, 2) ?></td></tr>
        <?php if (($inv['overall_discount_value'] ?? 0) > 0): ?>
        <tr><td>Discount</td><td>&minus; <?= number_format($inv['overall_discount_value'], 2) ?></td></tr>
        <?php endif; ?>
        <?php if (!$allGstZero): ?>
        <tr><td>Taxable</td><td><?= number_format($inv['total_taxable'], 2) ?></td></tr>
        <tr><td>CGST</td><td><?= number_format($cgst_total, 2) ?></td></tr>
        <tr><td>SGST</td><td><?= number_format($sgst_total, 2) ?></td></tr>
        <?php endif; ?>
        <tr class="th-grand">
            <td>GRAND TOTAL</td>
            <td>&#8377; <?= number_format($inv['net_total'], 2) ?></td>
        </tr>
        <?php if (($inv['received_amount'] ?? 0) > 0): ?>
        <tr class="th-paid">
            <td>&#10003; Received</td>
            <td>&#8377; <?= number_format($inv['received_amount'], 2) ?></td>
        </tr>
        <tr class="th-bal">
            <td><?= ($inv['balance_amount'] <= 0) ? '&#10003; Settled' : 'Balance Due' ?></td>
            <td>&#8377; <?= number_format(abs($inv['balance_amount']), 2) ?></td>
        </tr>
        <?php endif; ?>
    </table>

    <div class="th-dashed"></div>

    <!-- Barcode -->
    <div class="th-center">
        <svg id="barcode" data-invoice="<?= htmlspecialchars($inv['invoice_no']) ?>"></svg>
    </div>

    <?php
    // UPI: check company-level upi_id first, else primary bank account
    $upiId   = $company['upi_id'] ?? '';
    $upiName = $company['upi_name'] ?? $company['company_name'];
    if (empty($upiId)) {
        foreach (($company['bank_accounts'] ?? []) as $ba) {
            if (!empty($ba['upi_id'])) { $upiId = $ba['upi_id']; $upiName = $ba['upi_name'] ?: $upiName; break; }
        }
    }
    ?>
    <?php if (!empty($upiId)): ?>
    <div class="th-dashed"></div>
    <div class="th-center">
        <div id="upiQR"
             data-upi="<?= htmlspecialchars($upiId) ?>"
             data-name="<?= htmlspecialchars($upiName) ?>"
             data-amount="<?= number_format($inv['net_total'], 2, '.', '') ?>">
        </div>
        <div style="font-size:9px;margin-top:2px;font-weight:600;">
            &#8377; <?= number_format($inv['net_total'], 2) ?> &nbsp;&mdash;&nbsp; Scan &amp; Pay
        </div>
        <div class="th-small"><?= htmlspecialchars($upiName) ?></div>
    </div>
    <?php endif; ?>

    <div class="th-dashed"></div>

    <!-- Footer -->
    <div class="th-center th-footer-text">THANK YOU! VISIT AGAIN</div>
    <div class="th-center th-small" style="margin-top:3px;">
        This is a computer generated invoice.
    </div>
    <div style="height:1mm;"></div>

</div>
