<?php
$taxableTotal = 0;
$gstTotal     = 0;
$rows = [];
while ($row = $items->fetch_assoc()) {
    $pp  = (float)$row['purchase_price'];
    $dt  = $row['disc_type'] ?? '';
    $dv  = (float)($row['disc_value'] ?? 0);
    $eff = $pp;
    if ($dt === 'percent') $eff = $pp * (1 - $dv / 100);
    elseif ($dt === 'amount') $eff = $pp - $dv;
    $eff = max(0, $eff);
    $taxable  = $eff * (float)$row['quantity'];
    $gstAmt   = $taxable * (float)$row['gst_percent'] / 100;
    $row['_eff']     = $eff;
    $row['_taxable'] = $taxable;
    $row['_gst']     = $gstAmt;
    $row['_total']   = $taxable + $gstAmt;
    $taxableTotal += $taxable;
    $gstTotal     += $gstAmt;
    $rows[] = $row;
}
$subTotal = $taxableTotal + $gstTotal;
$discType  = $po['discount_type']  ?? '';
$discValue = (float)($po['discount_value'] ?? 0);
$afterDisc = $subTotal;
if ($discType === 'percent') $afterDisc = $subTotal * (1 - $discValue / 100);
elseif ($discType === 'amount') $afterDisc = $subTotal - $discValue;
$afterDisc = max(0, $afterDisc);
$roundOff = (float)($po['round_off'] ?? 0);
$netTotal = round($afterDisc + $roundOff, 2);
?>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { margin: 0; padding: 0; background: #fff; font-family: Arial, sans-serif; font-size: 11px; color: #111; }
.po-wrap {
    width: 100%;
    min-height: 277mm;
    display: flex;
    flex-direction: column;
    font-family: Arial, sans-serif;
    font-size: 11px;
    color: #111;
    border: 1px solid #999;
}
/* HEADER */
.po-head {
    background: #1e3a5f;
    color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 16px;
}
.po-company-name { font-size: 20px; font-weight: 700; letter-spacing: 0.5px; }
.po-company-sub  { font-size: 10px; opacity: 0.85; margin-top: 3px; line-height: 1.5; }
.po-head-right   { text-align: right; }
.po-title        { font-size: 16px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; }
.po-title-sub    { font-size: 10px; opacity: 0.85; margin-top: 4px; line-height: 1.6; }
/* META ROW */
.po-meta {
    display: flex;
    border-bottom: 1px solid #ccc;
}
.po-meta-box {
    flex: 1;
    padding: 8px 12px;
    border-right: 1px solid #ccc;
    font-size: 11px;
    line-height: 1.5;
}
.po-meta-box:last-child { border-right: none; }
.po-meta-label { font-size: 9px; text-transform: uppercase; font-weight: 700; color: #1e3a5f; letter-spacing: 0.5px; margin-bottom: 2px; }
.po-meta-val   { font-size: 12px; font-weight: 600; }
.po-meta-sub   { font-size: 10px; color: #444; line-height: 1.5; margin-top: 2px; }
/* ITEMS */
.po-items { width: 100%; border-collapse: collapse; font-size: 10.5px; }
.po-items th {
    background: #1e3a5f; color: #fff;
    padding: 7px 5px; text-align: center;
    font-size: 10px; font-weight: 600; letter-spacing: 0.3px;
    border-right: 1px solid #2d5080;
}
.po-items th:last-child { border-right: none; }
.po-items td {
    padding: 6px 5px;
    border-bottom: 1px solid #e8ecf0;
    border-right: 1px solid #e8ecf0;
    vertical-align: top;
}
.po-items td:last-child { border-right: none; }
.po-items tbody tr:nth-child(even) td { background: #f8fafc; }
/* SPACER */
.po-spacer { flex: 1; }
/* BOTTOM */
.po-bottom {
    display: flex;
    border-top: 1px solid #ccc;
}
.po-bottom-left  { flex: 1; padding: 10px 12px; border-right: 1px solid #ccc; font-size: 10px; line-height: 1.6; }
.po-bottom-right { width: 52mm; padding: 10px 12px; }
.po-totals { width: 100%; border-collapse: collapse; font-size: 11px; }
.po-totals td { padding: 4px 6px; }
.po-totals .label { color: #444; }
.po-totals .val   { text-align: right; font-weight: 600; }
.po-totals .grand td { border-top: 2px solid #1e3a5f; font-weight: 700; font-size: 13px; color: #1e3a5f; padding-top: 6px; }
/* SIGN */
.po-sign {
    display: flex;
    justify-content: space-between;
    border-top: 1px solid #ccc;
    padding: 10px 14px;
    font-size: 10px;
}
.po-sign-right { text-align: right; }
.r { text-align: right; }
.c { text-align: center; }
@media print {
    @page { size: A4; margin: 10mm; }
    body { margin: 0; padding: 0; background: #fff; }
    .po-wrap { border: none; min-height: 0; width: 100%; }
}
</style>

<div class="po-wrap">

    <!-- HEADER -->
    <div class="po-head">
        <div>
            <div class="po-company-name"><?= strtoupper(htmlspecialchars($company['company_name'])) ?></div>
            <div class="po-company-sub">
                <?= nl2br(htmlspecialchars($company['address'])) ?><br>
                GSTIN: <?= htmlspecialchars($company['gst_no']) ?> &nbsp;|&nbsp; Ph: <?= htmlspecialchars($company['phone']) ?>
            </div>
        </div>
        <div class="po-head-right">
            <div class="po-title">Purchase Order</div>
            <div class="po-title-sub">
                <?= $po['status'] === 'final' ? 'FINALIZED' : 'DRAFT' ?>
            </div>
        </div>
    </div>

    <!-- META -->
    <div class="po-meta">
        <div class="po-meta-box">
            <div class="po-meta-label">PO Number</div>
            <div class="po-meta-val"><?= htmlspecialchars($po['po_no']) ?></div>
        </div>
        <div class="po-meta-box">
            <div class="po-meta-label">Date</div>
            <div class="po-meta-val"><?= date('d-m-Y', strtotime($po['purchase_date'])) ?></div>
        </div>
        <?php if (!empty($po['supplier_invoice_no'])): ?>
        <div class="po-meta-box">
            <div class="po-meta-label">Supplier Invoice</div>
            <div class="po-meta-val"><?= htmlspecialchars($po['supplier_invoice_no']) ?></div>
        </div>
        <?php endif; ?>
        <div class="po-meta-box" style="flex:2;">
            <div class="po-meta-label">Vendor</div>
            <div class="po-meta-val"><?= htmlspecialchars($po['vendor_name']) ?></div>
            <div class="po-meta-sub">
                <?php if (!empty($po['vendor_address'])): ?>
                    <?= htmlspecialchars($po['vendor_address']) ?>
                    <?php if (!empty($po['vendor_city']) || !empty($po['vendor_state'])): ?>
                        , <?= htmlspecialchars(trim($po['vendor_city'] . ' ' . $po['vendor_state'])) ?>
                    <?php endif; ?><br>
                <?php endif; ?>
                <?php $ph = trim(($po['vendor_phone'] ?? '') . ($po['vendor_phone'] && $po['vendor_mobile'] ? ' / ' : '') . ($po['vendor_mobile'] ?? '')); ?>
                <?php if ($ph): ?>Ph: <?= htmlspecialchars($ph) ?><br><?php endif; ?>
                <?php if (!empty($po['vendor_gstin'])): ?>GSTIN: <?= htmlspecialchars($po['vendor_gstin']) ?><?php endif; ?>
            </div>
        </div>
    </div>

    <!-- ITEMS -->
    <table class="po-items">
        <thead>
            <tr>
                <th style="width:4%">#</th>
                <th style="width:26%;text-align:left;">Product</th>
                <th style="width:10%">Batch</th>
                <th style="width:8%">MRP</th>
                <th style="width:8%">Price</th>
                <th style="width:7%">Disc</th>
                <th style="width:5%">Qty</th>
                <th style="width:5%">GST%</th>
                <th style="width:9%">Taxable</th>
                <th style="width:8%">GST</th>
                <th style="width:10%">Total</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $i => $row): ?>
        <tr>
            <td class="c"><?= $i + 1 ?></td>
            <td><strong><?= htmlspecialchars($row['product_name']) ?></strong></td>
            <td class="c" style="font-size:10px;color:#555;"><?= htmlspecialchars($row['batch_no']) ?></td>
            <td class="r">&#8377; <?= number_format($row['mrp'], 2) ?></td>
            <td class="r">&#8377; <?= number_format($row['purchase_price'], 2) ?></td>
            <td class="c" style="font-size:10px;">
                <?php if ($row['disc_type'] === 'percent'): ?>
                    <?= $row['disc_value'] ?>%
                <?php elseif ($row['disc_type'] === 'amount'): ?>
                    &#8377;<?= number_format($row['disc_value'], 2) ?>
                <?php else: ?>—<?php endif; ?>
            </td>
            <td class="c"><?= $row['quantity'] ?></td>
            <td class="c"><?= $row['gst_percent'] ?>%</td>
            <td class="r">&#8377; <?= number_format($row['_taxable'], 2) ?></td>
            <td class="r">&#8377; <?= number_format($row['_gst'], 2) ?></td>
            <td class="r"><strong>&#8377; <?= number_format($row['_total'], 2) ?></strong></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <!-- SPACER pushes bottom to page end -->
    <div class="po-spacer"></div>

    <!-- BOTTOM -->
    <div class="po-bottom">
        <div class="po-bottom-left">
            <strong style="color:#1e3a5f;">Note</strong><br>
            This is a computer generated Purchase Order.<br>
            Please quote PO No. on all correspondence.
        </div>
        <div class="po-bottom-right">
            <table class="po-totals">
                <tr>
                    <td class="label">Taxable Amount</td>
                    <td class="val">&#8377; <?= number_format($taxableTotal, 2) ?></td>
                </tr>
                <tr>
                    <td class="label">GST Amount</td>
                    <td class="val">&#8377; <?= number_format($gstTotal, 2) ?></td>
                </tr>
                <?php if ($discType !== '' && $discValue > 0): ?>
                <tr>
                    <td class="label">Discount<?= $discType === 'percent' ? ' (' . $discValue . '%)' : '' ?></td>
                    <td class="val" style="color:#c0392b;">- &#8377; <?= $discType === 'percent' ? number_format($subTotal * $discValue / 100, 2) : number_format($discValue, 2) ?></td>
                </tr>
                <?php endif; ?>
                <?php if ($roundOff != 0): ?>
                <tr>
                    <td class="label">Round Off</td>
                    <td class="val">&#8377; <?= number_format($roundOff, 2) ?></td>
                </tr>
                <?php endif; ?>
                <tr class="grand">
                    <td class="label">Net Total</td>
                    <td class="val">&#8377; <?= number_format($netTotal, 2) ?></td>
                </tr>
            </table>
        </div>
    </div>

    <!-- SIGN -->
    <div class="po-sign">
        <div>
            <strong>Terms</strong><br>
            Payment as agreed. Subject to local jurisdiction.
        </div>
        <div class="po-sign-right">
            For <strong><?= htmlspecialchars($company['company_name']) ?></strong><br><br><br>
            Authorised Signatory
        </div>
    </div>

</div>
