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

$maindb   = 'salegst';
$trandb   = 'salegsttr';
$formname = 'Sale GST Register';

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

// ── Inputs from filter form ──────────────────────────────────────────────
$customer = isset($_POST['customer']) ? (int)$_POST['customer'] : 0;
$godown   = isset($_POST['godown'])   ? (int)$_POST['godown']   : 0;
$dtype    = isset($_POST['dtype'])    ? trim($_POST['dtype'])   : '1';   // 1=Summary, 2=Detail

function d2sql($d) {
    if ($d != '' && preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $d, $m)) {
        return $m[3] . '-' . $m[2] . '-' . $m[1];
    }
    return '';
}
$mfrmdate = d2sql(isset($_POST['fdate']) ? trim($_POST['fdate']) : '');
$mtodate  = d2sql(isset($_POST['tdate']) ? trim($_POST['tdate']) : '');

if ($mfrmdate == '') {
    browse("From Date Cannot Be Empty");
    header("refresh:1; url=salegstreg.php");
    exit;
}
if ($mtodate == '') {
    browse("To Date Cannot Be Empty");
    header("refresh:1; url=salegstreg.php");
    exit;
}

$cond = '';
if ($customer > 0) $cond .= " AND s.`customer`='$customer'";
if ($godown   > 0) $cond .= " AND s.`godown`='$godown'";

function pf($v) {
    $v = (float)$v;
    return $v == 0 ? '' : number_format($v, 2);
}

$getsmain = mysqli_query($conn, "SELECT s.*, DATE_FORMAT(s.`vouchdt`, '%d-%m-%Y') AS mydt,
                                          c.`name` AS customername, g.`name` AS godownname, sm.`name` AS salesmanname
                                   FROM `$maindb` s
                                   LEFT JOIN `accmast` c  ON c.accode  = s.customer
                                   LEFT JOIN `godown`  g  ON g.code    = s.godown
                                   LEFT JOIN `accmast` sm ON sm.accode = s.salesman
                                   WHERE s.`vouchdt` >= '$mfrmdate' AND s.`vouchdt` <= '$mtodate'
                                   $cond
                                   ORDER BY s.`vouchdt` ASC, s.`vouchno` ASC") or die(mysqli_error($conn));

if (isset($_POST["view"])) {

    include("includes/linkshead.php");
    $mfdt = date('d-m-Y', strtotime($mfrmdate));
    $mtdt = date('d-m-Y', strtotime($mtodate));
    ?>
<style>
    body { background:#f0f2f5; margin:0; padding:10px 14px; }

    .sim-card {
        background:#fff; border-radius:10px;
        box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06);
        overflow:hidden;
    }
    .sim-card-header {
        background:#fff; border-bottom:2px solid #f1f5f9; padding:12px 20px;
        display:flex; align-items:center; justify-content:space-between;
    }
    .sim-card-header h2 { font-size:15px; font-weight:700; color:#1e293b; margin:0; }
    .sim-card-header .sub { font-size:11.5px; color:#94a3b8; margin-top:2px; }

    .sim-body { padding:18px 20px; }

    .btn { padding:8px 16px; border:none; border-radius:6px; font-size:12.5px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:6px; text-decoration:none; }
    .btn-export { background:#16a34a; color:#fff; }
    .btn-export:hover { background:#15803d; }
    .btn-print { background:#4a5759; color:#fff; }
    .btn-print:hover { background:#374043; }

    table.reg { width:100%; border-collapse:collapse; font-size:12px; }
    table.reg th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em; padding:8px 10px;
        border-bottom:2px solid #e2e8f0; text-align:left; white-space:nowrap;
    }
    table.reg th.num { text-align:right; }
    table.reg td { padding:6px 10px; border-bottom:1px solid #f1f5f9; white-space:nowrap; }
    table.reg td.num { text-align:right; }
    table.reg tbody tr.mainrow { cursor:pointer; font-weight:600; }
    table.reg tbody tr.mainrow:hover { background:#eff6ff; }
    table.reg tfoot td { font-weight:700; background:#f8fafc; border-top:2px solid #e2e8f0; }

    .dtype-sub th { background:#fef3c7; }
    .reg-wrap { overflow:auto; }

    @media print {
        body { background:#fff; padding:0; }
        .no-print { display:none !important; }
        .sim-card { box-shadow:none; border-radius:0; }
        table.reg tbody tr.mainrow:hover { background:none; }
    }
</style>
</head>
<body>
<div class="sim-card">
    <div class="sim-card-header">
        <div>
            <h2><i class="fa fa-receipt" style="color:#f59e0b;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?> (<?php echo $dtype=='2' ? 'Detail' : 'Summary'; ?>)</h2>
            <div class="sub"><?php echo $mfdt; ?> to <?php echo $mtdt; ?></div>
        </div>
        <div class="no-print" style="display:flex;gap:8px;">
            <button type="button" class="btn btn-print" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
            <button onclick="if(window.parent&&window.parent!==window){window.parent.document.getElementById('rptframe').src='about:blank';}else{window.close();}" style="padding:8px 22px;background:#f1f5f9;color:#374151;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;margin-left:8px;"><i class="fa fa-arrow-left"></i> Go Back</button>
            <form method="POST" style="margin:0;">
                <?php foreach ($_POST as $k => $v) { if ($k != 'view') echo '<input type="hidden" name="' . htmlspecialchars($k) . '" value="' . htmlspecialchars($v) . '">'; } ?>
                <button type="submit" name="excel" value="1" class="btn btn-export"><i class="fa fa-file-csv"></i> Export CSV</button>
            </form>
        </div>
    </div>

    <div class="sim-body">
    <div class="reg-wrap">
    <table class="reg">
        <thead>
            <tr>
                <th>Sr</th>
                <th>Voucher No</th>
                <th>Date</th>
                <th>Customer</th>
                <th>Godown</th>
                <th>Salesman</th>
                <th class="num">Qty</th>
                <th class="num">Taxable Amt</th>
                <th class="num">GST Amt</th>
                <th class="num">Net Amt</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $ctr = 0;
            $ttotqty = 0;
            $ttaxable = 0;
            $ttotgst = 0;
            $ttotamt = 0;

            while ($smain = mysqli_fetch_array($getsmain)) {
                $ctr++;
                echo "<tr class='mainrow' onclick=\"window.open('salegst.php?mode=edit&vouchno={$smain['vouchno']}','_blank')\">";
                echo "<td style='text-align:center;'>$ctr</td>";
                echo "<td style='color:#2563eb;'>GST#{$smain['vouchno']}</td>";
                echo "<td>{$smain['mydt']}</td>";
                echo "<td>" . htmlspecialchars($smain['customername'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($smain['godownname'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($smain['salesmanname'] ?? '') . "</td>";
                echo "<td class='num'>" . pf($smain['tottqty']) . "</td>";
                echo "<td class='num'>" . pf($smain['taxableamt']) . "</td>";
                echo "<td class='num'>" . pf($smain['totgstamt']) . "</td>";
                echo "<td class='num'>" . pf($smain['totamt']) . "</td>";
                echo "</tr>";

                $ttotqty  += (float)$smain['tottqty'];
                $ttaxable += (float)$smain['taxableamt'];
                $ttotgst  += (float)$smain['totgstamt'];
                $ttotamt  += (float)$smain['totamt'];

                if ($dtype == '2') {
                    echo "<tr><td colspan='10' style='padding:4px 10px 10px;background:#fafbfc;'>";
                    echo "<table style='width:100%;border-collapse:collapse;font-size:11.5px;' class='dtype-sub'>";
                    echo "<tr>
                            <th style='width:5%;padding:6px;'>Sr</th>
                            <th style='padding:6px;'>Product</th>
                            <th style='padding:6px;'>HSN</th>
                            <th style='padding:6px;text-align:right;'>Qty</th>
                            <th style='padding:6px;text-align:right;'>Rate</th>
                            <th style='padding:6px;text-align:right;'>Disc%</th>
                            <th style='padding:6px;text-align:right;'>GST%</th>
                            <th style='padding:6px;text-align:right;'>GST Amt</th>
                            <th style='padding:6px;text-align:right;'>Net Amt</th>
                          </tr>";

                    $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$smain['vouchno']}' ORDER BY `srl`") or die(mysqli_error($conn));
                    $ctr2 = 0;
                    $sqty = $sgst = $snet = 0;
                    while ($tran = mysqli_fetch_array($gettran)) {
                        $ctr2++;
                        echo "<tr>";
                        echo "<td style='text-align:center;padding:5px;'>$ctr2</td>";
                        echo "<td style='padding:5px;'>" . htmlspecialchars($tran['description']) . "</td>";
                        echo "<td style='padding:5px;'>" . htmlspecialchars($tran['hsncode'] ?? '') . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['tqty']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['cost']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['discpercent']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['gstpercent']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['gstamt']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['netamt']) . "</td>";
                        echo "</tr>";

                        $sqty += (float)$tran['tqty'];
                        $sgst += (float)$tran['gstamt'];
                        $snet += (float)$tran['netamt'];
                    }
                    echo "<tr style='font-weight:700;background:#fef3c7;'>";
                    echo "<td colspan='3' style='text-align:right;padding:6px;'>Total</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($sqty) . "</td>";
                    echo "<td colspan='2'></td>";
                    echo "<td></td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($sgst) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($snet) . "</td>";
                    echo "</tr>";
                    echo "</table>";
                    echo "</td></tr>";
                }
            }
            ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="6" style="text-align:right;">Grand Total (<?php echo $ctr; ?> vouchers)</td>
                <td class="num"><?php echo pf($ttotqty); ?></td>
                <td class="num"><?php echo pf($ttaxable); ?></td>
                <td class="num"><?php echo pf($ttotgst); ?></td>
                <td class="num"><?php echo pf($ttotamt); ?></td>
            </tr>
        </tfoot>
    </table>
    </div>
    </div>
</div>

<?php include("includes/linksfoot.php"); ?>
</body>
</html>
<?php
}

if (isset($_POST["excel"])) {
    $contents = '';
    $contents .= "Sr.,Voucher No,Date,Customer,Godown,Salesman,Qty,Taxable Amt,GST Amt,Net Amt\n";

    $ctr = 0;
    $ttotqty = 0;
    $ttaxable = 0;
    $ttotgst = 0;
    $ttotamt = 0;

    while ($smain = mysqli_fetch_array($getsmain)) {
        $ctr++;
        $contents .= $ctr . ",";
        $contents .= "GST#" . $smain['vouchno'] . ",";
        $contents .= $smain['mydt'] . ",";
        $contents .= $smain['customername'] . ",";
        $contents .= $smain['godownname'] . ",";
        $contents .= $smain['salesmanname'] . ",";
        $contents .= $smain['tottqty'] . ",";
        $contents .= $smain['taxableamt'] . ",";
        $contents .= $smain['totgstamt'] . ",";
        $contents .= $smain['totamt'] . "\n";

        $ttotqty  += (float)$smain['tottqty'];
        $ttaxable += (float)$smain['taxableamt'];
        $ttotgst  += (float)$smain['totgstamt'];
        $ttotamt  += (float)$smain['totamt'];

        if ($dtype == '2') {
            $contents .= "Sr.,Product,HSN,Qty,Rate,Disc%,GST%,GST Amt,Net Amt\n";

            $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$smain['vouchno']}' ORDER BY `srl`") or die(mysqli_error($conn));
            $ctr2 = 0;
            $sqty = $sgst = $snet = 0;
            while ($tran = mysqli_fetch_array($gettran)) {
                $ctr2++;
                $contents .= $ctr2 . ",";
                $contents .= $tran['description'] . ",";
                $contents .= $tran['hsncode'] . ",";
                $contents .= $tran['tqty'] . ",";
                $contents .= $tran['cost'] . ",";
                $contents .= $tran['discpercent'] . ",";
                $contents .= $tran['gstpercent'] . ",";
                $contents .= $tran['gstamt'] . ",";
                $contents .= $tran['netamt'] . "\n";

                $sqty += (float)$tran['tqty'];
                $sgst += (float)$tran['gstamt'];
                $snet += (float)$tran['netamt'];
            }
            $contents .= ",,,Total,";
            $contents .= $sqty . ",,,";
            $contents .= $sgst . ",";
            $contents .= $snet . "\n";
        }
        $contents .= "\n";
    }

    $contents .= ",,,,,Grand Total,";
    $contents .= $ttotqty . ",";
    $contents .= $ttaxable . ",";
    $contents .= $ttotgst . ",";
    $contents .= $ttotamt . "\n";

    $contents = strip_tags($contents);

    header('Content-Type: text/csv; charset=utf-8');
    if ($dtype == '1') {
        header("Content-Disposition: attachment; filename=" . $formname . "_Summary_" . date('d-m-Y') . ".csv");
    } else {
        header("Content-Disposition: attachment; filename=" . $formname . "_Detail_" . date('d-m-Y') . ".csv");
    }
    print $contents;
}
