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

$maindb   = 'billconf';
$trandb   = 'billconftr';
$formname = 'Bill Confirming Register';

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

// ── Inputs from filter form ──────────────────────────────────────────────
$party    = isset($_POST['party'])    ? (int)$_POST['party']     : 0;
$supplier = isset($_POST['supplier']) ? (int)$_POST['supplier']  : 0;
$origin   = isset($_POST['origin'])   ? trim($_POST['origin'])   : '';
$status   = isset($_POST['status'])   ? trim($_POST['status'])   : '';
$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=billconfreg.php");
    exit;
}
if ($mtodate == '') {
    browse("To Date Cannot Be Empty");
    header("refresh:1; url=billconfreg.php");
    exit;
}

$partycond    = ($party > 0)    ? " AND b.`party`='$party' "       : '';
$suppliercond = ($supplier > 0) ? " AND b.`supplier`='$supplier' " : '';
$origincond   = ($origin != '') ? " AND b.`origin`='" . mysqli_real_escape_string($conn, $origin) . "' " : '';
$statuscond   = ($status != '') ? " AND b.`status`='" . mysqli_real_escape_string($conn, $status) . "' " : '';

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

$getbmain = mysqli_query($conn, "SELECT b.*, DATE_FORMAT(b.`vouchdt`, '%d-%m-%Y') AS mydt,
                                          p.`name` AS partyname, s.`name` AS suppliername
                                   FROM `$maindb` b
                                   LEFT JOIN `accmast` p ON p.accode = b.party
                                   LEFT JOIN `accmast` s ON s.accode = b.supplier
                                   WHERE b.`vouchdt` >= '$mfrmdate' AND b.`vouchdt` <= '$mtodate'
                                   $partycond $suppliercond $origincond $statuscond
                                   ORDER BY b.`vouchdt` ASC, b.`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; }
    .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; }

    .status-pill { font-size:10.5px; font-weight:700; border-radius:20px; padding:2px 10px; color:#fff; display:inline-block; }
    .status-pending   { background:#f59e0b; }
    .status-confirmed { background:#16a34a; }
    .status-declined  { background:#dc2626; }

    .dtype-sub th { background:#cccccc; }
    .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-file-invoice" style="color:#3b82f6;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>Party</th>
                <th>Supplier</th>
                <th>Ship Mark</th>
                <th>Origin</th>
                <th>Status</th>
                <th class="num">CTN</th>
                <th class="num">QTY</th>
                <th class="num">Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $ctr = 0;
            $ttotctn = 0;
            $ttotqty = 0;
            $ttotamt = 0;

            while ($bmain = mysqli_fetch_array($getbmain)) {
                $ctr++;
                $stcls = $bmain['status']=='Confirmed' ? 'status-confirmed' : ($bmain['status']=='Declined' ? 'status-declined' : 'status-pending');
                echo "<tr class='mainrow' onclick=\"window.open('billconf.php?mode=edit&vouchno={$bmain['vouchno']}','_blank')\">";
                echo "<td style='text-align:center;'>$ctr</td>";
                echo "<td style='color:#2563eb;'>{$bmain['vouchno']}</td>";
                echo "<td>{$bmain['mydt']}</td>";
                echo "<td>" . htmlspecialchars($bmain['partyname'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($bmain['suppliername'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($bmain['shipmark']) . "</td>";
                echo "<td style='text-align:center;'>" . htmlspecialchars($bmain['origin']) . "</td>";
                echo "<td style='text-align:center;'><span class='status-pill $stcls'>" . htmlspecialchars($bmain['status']) . "</span></td>";
                echo "<td class='num'>" . pf($bmain['totctn']) . "</td>";
                echo "<td class='num'>" . pf($bmain['totqty']) . "</td>";
                echo "<td class='num'>" . pf($bmain['totamt']) . "</td>";
                echo "</tr>";

                $ttotctn += (float)$bmain['totctn'];
                $ttotqty += (float)$bmain['totqty'];
                $ttotamt += (float)$bmain['totamt'];

                if ($dtype == '2') {
                    echo "<tr><td colspan='11' 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;'>Description</th>
                            <th style='padding:6px;text-align:right;'>CTN</th>
                            <th style='padding:6px;text-align:right;'>QTY</th>
                            <th style='padding:6px;text-align:right;'>T.QTY</th>
                            <th style='padding:6px;text-align:right;'>Amount</th>
                            <th style='padding:6px;text-align:right;'>CBM</th>
                            <th style='padding:6px;text-align:right;'>Weight</th>
                          </tr>";

                    $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$bmain['vouchno']}' ORDER BY `srl`") or die(mysqli_error($conn));
                    $ctr2 = 0;
                    $sctn = $sqty = $stqty = $samt = $scbm = $swt = 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 class='num' style='padding:5px;'>" . pf($tran['ctn']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['qty']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['tqty']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['amt']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['cbm']) . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($tran['weight']) . "</td>";
                        echo "</tr>";

                        $sctn += (float)$tran['ctn'];
                        $sqty += (float)$tran['qty'];
                        $stqty += (float)$tran['tqty'];
                        $samt += (float)$tran['amt'];
                        $scbm += (float)$tran['cbm'];
                        $swt  += (float)$tran['weight'];
                    }
                    echo "<tr style='font-weight:700;background:#f1f5f9;'>";
                    echo "<td colspan='2' style='text-align:right;padding:6px;'>Total</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($sctn) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($sqty) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($stqty) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($samt) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($scbm) . "</td>";
                    echo "<td class='num' style='padding:6px;'>" . pf($swt) . "</td>";
                    echo "</tr>";
                    echo "</table>";
                    echo "</td></tr>";
                }
            }
            ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="8" style="text-align:right;">Grand Total (<?php echo $ctr; ?> vouchers)</td>
                <td class="num"><?php echo pf($ttotctn); ?></td>
                <td class="num"><?php echo pf($ttotqty); ?></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,Party,Supplier,Ship Mark,Origin,Status,CTN,QTY,Amount\n";

    $ctr = 0;
    $ttotctn = 0;
    $ttotqty = 0;
    $ttotamt = 0;

    while ($bmain = mysqli_fetch_array($getbmain)) {
        $ctr++;
        $contents .= $ctr . ",";
        $contents .= $bmain['vouchno'] . ",";
        $contents .= $bmain['mydt'] . ",";
        $contents .= $bmain['partyname'] . ",";
        $contents .= $bmain['suppliername'] . ",";
        $contents .= $bmain['shipmark'] . ",";
        $contents .= $bmain['origin'] . ",";
        $contents .= $bmain['status'] . ",";
        $contents .= $bmain['totctn'] . ",";
        $contents .= $bmain['totqty'] . ",";
        $contents .= $bmain['totamt'] . "\n";

        $ttotctn += (float)$bmain['totctn'];
        $ttotqty += (float)$bmain['totqty'];
        $ttotamt += (float)$bmain['totamt'];

        if ($dtype == '2') {
            $contents .= "Sr.,Description,CTN,QTY,T.QTY,Amount,CBM,Weight\n";

            $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='{$bmain['vouchno']}' ORDER BY `srl`") or die(mysqli_error($conn));
            $ctr2 = 0;
            $sctn = $sqty = $stqty = $samt = $scbm = $swt = 0;
            while ($tran = mysqli_fetch_array($gettran)) {
                $ctr2++;
                $contents .= $ctr2 . ",";
                $contents .= $tran['description'] . ",";
                $contents .= $tran['ctn'] . ",";
                $contents .= $tran['qty'] . ",";
                $contents .= $tran['tqty'] . ",";
                $contents .= $tran['amt'] . ",";
                $contents .= $tran['cbm'] . ",";
                $contents .= $tran['weight'] . "\n";

                $sctn += (float)$tran['ctn'];
                $sqty += (float)$tran['qty'];
                $stqty += (float)$tran['tqty'];
                $samt += (float)$tran['amt'];
                $scbm += (float)$tran['cbm'];
                $swt  += (float)$tran['weight'];
            }
            $contents .= ",Total,";
            $contents .= $sctn . ",";
            $contents .= $sqty . ",";
            $contents .= $stqty . ",";
            $contents .= $samt . ",";
            $contents .= $scbm . ",";
            $contents .= $swt . "\n";
        }
        $contents .= "\n";
    }

    $contents .= ",,,,,,Grand Total,";
    $contents .= $ttotctn . ",";
    $contents .= $ttotqty . ",";
    $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;
}
