<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$zdb    = $_SESSION["zdbyear_" . $dbname];
$compcd = $_SESSION["comp_"    . $dbname];
$zdbroot = $_SESSION["zdbroot"] = $dbname;   // sim_root
mysqli_select_db($conn, $zdb);

$vouchno = isset($_GET['vouchno']) ? (int)$_GET['vouchno'] : 0;

$result = mysqli_query($conn,
    "SELECT s.*, c.name AS customername, c.statecode AS custstatecode
     FROM `salegst` s
     LEFT JOIN `accmast` c ON c.accode = s.customer
     WHERE s.vouchno='$vouchno'") or die(mysqli_error($conn));
$get = mysqli_fetch_array($result);
if (!$get) $get = [];

$tres = mysqli_query($conn, "SELECT * FROM `salegsttr` WHERE `vouchno`='$vouchno' ORDER BY `srl`") or die(mysqli_error($conn));
$lines = [];
while ($r = mysqli_fetch_array($tres)) { $lines[] = $r; }

$compres = mysqli_query($conn, "SELECT * FROM $zdbroot.`company` WHERE `code`='$compcd'");
$comprow = $compres ? mysqli_fetch_assoc($compres) : null;
if (!$comprow) $comprow = [];
$compname = trim($comprow['tradename'] ?? '') !== '' ? $comprow['tradename'] : ($comprow['name'] ?? '');

// ── GST-specific Bank Details / Address (Company Setup → GST Details tab) —
//    each field falls back to the General tab's value when left blank. ─────
function gstfp($get, $gstKey, $genKey) {
    $v = trim($get[$gstKey] ?? '');
    return $v !== '' ? $v : ($get[$genKey] ?? '');
}
$printAddress    = gstfp($comprow, 'gst_address',    'address');
$printCity       = gstfp($comprow, 'gst_city',       'city');
$printPincode    = gstfp($comprow, 'gst_pincode',    'pincode');
$printCountry    = gstfp($comprow, 'gst_country',    'country');
$printBankname   = gstfp($comprow, 'gst_bankname',   'bankname');
$printBranchname = gstfp($comprow, 'gst_branchname', 'branchname');
$printAccountno  = gstfp($comprow, 'gst_accountno',  'accountno');
$printIfsccode   = gstfp($comprow, 'gst_ifsccode',   'ifsccode');
$printTelephone  = gstfp($comprow, 'gst_telephone',  'telephone');

// Display-time fallback: invoices saved before the CGST/SGST/IGST columns
// existed have them at 0 even though gstamt is populated. If a line's split
// is all-zero but it does carry GST, derive the split here on the fly (same
// rule as the live entry save path — customer statecode blank, or company
// GSTIN unknown, both default to intrastate CGST+SGST, never IGST).
$companyStateCodePrint = trim($comprow['statecode'] ?? '');
if ($companyStateCodePrint === '') {
    $companyStateCodePrint = $comprow ? substr(trim($comprow['gstno'] ?? ''), 0, 2) : '';
}
$customerStateCodePrint = trim($get['custstatecode'] ?? '');
$isInterstatePrint = ($companyStateCodePrint !== '' && $customerStateCodePrint !== '' && $companyStateCodePrint !== $customerStateCodePrint);
foreach ($lines as $k => $ln) {
    $gstamt = (float)($ln['gstamt'] ?? 0);
    $hasSplit = ((float)($ln['cgstamt'] ?? 0)) > 0 || ((float)($ln['sgstamt'] ?? 0)) > 0 || ((float)($ln['igstamt'] ?? 0)) > 0;
    if ($gstamt > 0 && !$hasSplit) {
        if ($isInterstatePrint) {
            $lines[$k]['cgstamt'] = 0; $lines[$k]['sgstamt'] = 0; $lines[$k]['igstamt'] = $gstamt;
        } else {
            $c = round($gstamt / 2, 2);
            $lines[$k]['cgstamt'] = $c; $lines[$k]['sgstamt'] = round($gstamt - $c, 2); $lines[$k]['igstamt'] = 0;
        }
    }
}

// GST Rate-wise Breakup: when line items carry different GST% (e.g. 5% + 18%
// on the same invoice), group the taxable value and GST amount by rate so
// the printed invoice shows a proper slab-wise summary instead of one lumped
// "Total GST" figure.
$gstBreakup = [];
foreach ($lines as $ln) {
    $rate = (float)($ln['gstpercent'] ?? 0);
    $key  = number_format($rate, 2, '.', '');
    if (!isset($gstBreakup[$key])) $gstBreakup[$key] = ['rate' => $rate, 'taxable' => 0, 'gst' => 0, 'cgst' => 0, 'sgst' => 0, 'igst' => 0];
    $gstBreakup[$key]['taxable'] += (float)($ln['amt'] ?? 0) - (float)($ln['discamt'] ?? 0);
    $gstBreakup[$key]['gst']     += (float)($ln['gstamt'] ?? 0);
    $gstBreakup[$key]['cgst']    += (float)($ln['cgstamt'] ?? 0);
    $gstBreakup[$key]['sgst']    += (float)($ln['sgstamt'] ?? 0);
    $gstBreakup[$key]['igst']    += (float)($ln['igstamt'] ?? 0);
}
ksort($gstBreakup, SORT_NUMERIC);

// Header totals (bottom summary row) may also be stale 0s on old invoices —
// prefer the freshly-summed breakup totals whenever the stored header total
// disagrees with them (i.e. wasn't backfilled yet).
$sumCgst = array_sum(array_column($gstBreakup, 'cgst'));
$sumSgst = array_sum(array_column($gstBreakup, 'sgst'));
$sumIgst = array_sum(array_column($gstBreakup, 'igst'));
if (((float)($get['totcgst'] ?? 0)) == 0 && ((float)($get['totsgst'] ?? 0)) == 0 && ((float)($get['totigst'] ?? 0)) == 0 && ($sumCgst > 0 || $sumSgst > 0 || $sumIgst > 0)) {
    $get['totcgst'] = $sumCgst;
    $get['totsgst'] = $sumSgst;
    $get['totigst'] = $sumIgst;
}

$vouchdt_disp = (!empty($get['vouchdt']) && $get['vouchdt'] != '0000-00-00') ? date('d-m-Y', strtotime($get['vouchdt'])) : '';

function pf($v) {
    if ($v === null || $v === '') return '';
    $v = (float)$v;
    return $v == 0 ? '' : (($v == (int)$v) ? (string)(int)$v : number_format($v, 2));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sale GST Invoice - <?php echo $vouchno; ?></title>
<style>
    body { font-family: Arial, sans-serif; font-size:13px; color:#1e293b; margin:20px; }
    h2 { text-align:center; margin:0 0 4px; }
    .sub { text-align:center; color:#64748b; margin-bottom:16px; }
    table { width:100%; border-collapse:collapse; margin-top:10px; }
    th, td { border:1px solid #cbd5e1; padding:6px 8px; font-size:11.5px; }
    th { background:#f1f5f9; text-align:center; }
    td.num { text-align:right; }
    .hdr-table td { border:none; padding:3px 6px; font-size:12.5px; }
    .hdr-label { color:#64748b; font-weight:600; width:120px; }
    tfoot td { font-weight:700; background:#f8fafc; }
    .sum-table { width:320px; margin-left:auto; margin-top:10px; }
    .sum-table td { border:none; padding:3px 8px; font-size:12.5px; }
    .sum-table .lbl { color:#64748b; text-align:right; }
    .sum-table .val { text-align:right; font-weight:600; width:110px; }
    .sum-table .grand td { border-top:2px solid #1e293b; font-weight:700; font-size:13.5px; }
    .comp-hdr { text-align:center; margin-bottom:2px; }
    .comp-info { text-align:center; font-size:11px; color:#475569; margin-bottom:14px; line-height:1.5; }
    @media print { .no-print { display:none; } }
</style>
</head>
<body>
    <div class="comp-hdr">
        <h2 style="margin:0;"><?php echo htmlspecialchars($compname); ?></h2>
    </div>
    <div class="comp-info">
        <?php
        $addrBits = array_filter([$printAddress, $printCity, $printPincode, $printCountry]);
        if ($addrBits) echo htmlspecialchars(implode(', ', $addrBits)) . '<br>';
        $lineBits = [];
        if (!empty($comprow['gstno'])) $lineBits[] = 'GSTIN: ' . $comprow['gstno'];
        if (!empty($comprow['panno'])) $lineBits[] = 'PAN: ' . $comprow['panno'];
        if (!empty($comprow['cin'])) $lineBits[] = 'CIN: ' . $comprow['cin'];
        if ($lineBits) echo htmlspecialchars(implode('  |  ', $lineBits)) . '<br>';
        $lineBits2 = [];
        if (!empty($comprow['state']) || $companyStateCodePrint !== '') $lineBits2[] = 'State: ' . ($comprow['state'] ?? '') . ' (Code: ' . $companyStateCodePrint . ')';
        if ($printTelephone !== '') $lineBits2[] = 'Mobile: ' . $printTelephone;
        if (!empty($comprow['email'])) $lineBits2[] = 'Email: ' . $comprow['email'];
        if ($lineBits2) echo htmlspecialchars(implode('  |  ', $lineBits2));
        ?>
    </div>
    <div class="sub">Sale GST Invoice</div>

    <table class="hdr-table">
        <tr>
            <td class="hdr-label">Voucher No</td><td>GST#<?php echo $vouchno; ?></td>
            <td class="hdr-label">Date</td><td><?php echo htmlspecialchars($vouchdt_disp); ?></td>
        </tr>
        <tr>
            <td class="hdr-label">Customer</td><td colspan="3"><?php echo htmlspecialchars($get['customername'] ?? ''); ?></td>
        </tr>
        <tr>
            <td class="hdr-label">Remarks</td><td colspan="3"><?php echo htmlspecialchars($get['remarks'] ?? ''); ?></td>
        </tr>
    </table>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Description</th>
                <th>HSN Code</th>
                <th>Qty</th>
                <th>Rate</th>
                <th>Amount</th>
                <th>Disc %</th>
                <th>Disc Amt</th>
                <th>GST %</th>
                <th>GST Amt</th>
                <th>Net Amt</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($lines as $i => $ln): ?>
            <tr>
                <td style="text-align:center;"><?php echo $i + 1; ?></td>
                <td><?php echo htmlspecialchars($ln['description']); ?></td>
                <td style="text-align:center;"><?php echo htmlspecialchars($ln['hsncode'] ?? ''); ?></td>
                <td class="num"><?php echo pf($ln['tqty']); ?></td>
                <td class="num"><?php echo pf($ln['cost']); ?></td>
                <td class="num"><?php echo pf($ln['amt']); ?></td>
                <td class="num"><?php echo pf($ln['discpercent']); ?></td>
                <td class="num"><?php echo pf($ln['discamt']); ?></td>
                <td class="num"><?php echo pf($ln['gstpercent']); ?></td>
                <td class="num"><?php echo pf($ln['gstamt']); ?></td>
                <td class="num"><?php echo pf($ln['netamt']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" style="text-align:right;">Total</td>
                <td class="num"><?php echo pf($get['tottqty'] ?? 0); ?></td>
                <td></td>
                <td class="num"><?php echo pf($get['subtotal'] ?? 0); ?></td>
                <td></td>
                <td class="num"><?php echo pf($get['totdiscamt'] ?? 0); ?></td>
                <td></td>
                <td class="num"><?php echo pf($get['totgstamt'] ?? 0); ?></td>
                <td class="num"><?php echo pf(($get['taxableamt'] ?? 0) + ($get['totgstamt'] ?? 0)); ?></td>
            </tr>
        </tfoot>
    </table>

    <?php if (count($gstBreakup) > 0): ?>
    <div class="sec-title" style="margin-top:18px;font-weight:700;font-size:12.5px;color:#374151;">
        GST Rate-wise Breakup
        <span style="font-weight:600;color:#64748b;"> — <?php echo $isInterstatePrint ? 'Interstate (IGST)' : 'Intrastate (CGST + SGST)'; ?></span>
    </div>
    <table style="width:520px;margin-left:auto;">
        <thead>
            <tr>
                <th>GST %</th>
                <th>Taxable Amount</th>
                <th>CGST</th>
                <th>SGST</th>
                <th>IGST</th>
                <th>Total GST</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($gstBreakup as $bk): ?>
            <tr>
                <td style="text-align:center;"><?php echo rtrim(rtrim(number_format($bk['rate'], 2), '0'), '.'); ?>%</td>
                <td class="num"><?php echo pf($bk['taxable']); ?></td>
                <td class="num"><?php echo pf($bk['cgst']); ?></td>
                <td class="num"><?php echo pf($bk['sgst']); ?></td>
                <td class="num"><?php echo pf($bk['igst']); ?></td>
                <td class="num"><?php echo pf($bk['gst']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <td style="text-align:right;">Total</td>
                <td class="num"><?php echo pf($get['taxableamt'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totcgst'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totsgst'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totigst'] ?? 0); ?></td>
                <td class="num"><?php echo pf($get['totgstamt'] ?? 0); ?></td>
            </tr>
        </tfoot>
    </table>
    <?php endif; ?>

    <?php $bankBits = array_filter([$printBankname, $printBranchname, $printAccountno, $printIfsccode]); ?>
    <?php if ($bankBits): ?>
    <table class="hdr-table" style="width:320px;margin-top:10px;">
        <tr><td colspan="2" style="font-weight:700;padding-bottom:2px;">Payment Details</td></tr>
        <?php if ($printBankname   !== ''): ?><tr><td class="hdr-label">Bank Name</td><td><?php echo htmlspecialchars($printBankname); ?></td></tr><?php endif; ?>
        <?php if ($printBranchname !== ''): ?><tr><td class="hdr-label">Branch</td><td><?php echo htmlspecialchars($printBranchname); ?></td></tr><?php endif; ?>
        <?php if ($printAccountno  !== ''): ?><tr><td class="hdr-label">A/c No.</td><td><?php echo htmlspecialchars($printAccountno); ?></td></tr><?php endif; ?>
        <?php if ($printIfsccode   !== ''): ?><tr><td class="hdr-label">IFSC Code</td><td><?php echo htmlspecialchars($printIfsccode); ?></td></tr><?php endif; ?>
    </table>
    <?php endif; ?>

    <table class="sum-table">
        <tr><td class="lbl">Taxable Amount</td><td class="val"><?php echo pf($get['taxableamt'] ?? 0); ?></td></tr>
        <tr><td class="lbl">Total GST</td><td class="val"><?php echo pf($get['totgstamt'] ?? 0); ?></td></tr>
        <tr><td class="lbl">Packing Charges</td><td class="val"><?php echo pf($get['packingcharges'] ?? 0); ?></td></tr>
        <tr><td class="lbl">Transport Charges</td><td class="val"><?php echo pf($get['transport_charges'] ?? 0); ?></td></tr>
        <tr><td class="lbl">Other Charges</td><td class="val"><?php echo pf($get['other_charges'] ?? 0); ?></td></tr>
        <tr class="grand"><td class="lbl">Net Amount</td><td class="val"><?php echo pf($get['totamt'] ?? 0); ?></td></tr>
    </table>

    <div style="margin-top:26px;text-align:right;">
        <div style="font-size:12px;font-weight:600;color:#1e293b;">For <?php echo htmlspecialchars($compname); ?></div>
        <div style="height:50px;"></div>
        <div style="font-size:11px;color:#64748b;border-top:1px solid #cbd5e1;display:inline-block;padding-top:3px;">Authorised Signatory</div>
    </div>

    <div class="no-print" style="margin-top:16px;text-align:center;">
        <button onclick="window.print()" style="padding:8px 18px;border:none;border-radius:6px;background:#2563eb;color:#fff;cursor:pointer;">Print</button>
    </div>
</body>
</html>
