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

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

// ── Defensive auto-migrate ──────────────────────────────────────────────────
foreach ([
    'dispatchdate'   => "DATE NULL",
    'dispatchby'     => "VARCHAR(50) NOT NULL DEFAULT ''",
    'lrno'           => "VARCHAR(50) NOT NULL DEFAULT ''",
    'transporter'    => "VARCHAR(100) NOT NULL DEFAULT ''",
    'lrdate'         => "DATE NULL",
    'transportmode'  => "VARCHAR(30) NOT NULL DEFAULT ''",
    'invoiceno'      => "INT(11) NOT NULL DEFAULT 0",
    'invoicedate'    => "DATE NULL",
    'godown'         => "INT(11) NOT NULL DEFAULT 0",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `saleorder` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `saleorder` ADD COLUMN `$col` $def");
}

$_ut = (int)$_SESSION["usertype_".$dbname];
$_ac = (int)($_SESSION["agentcode_".$dbname] ?? 0);

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
if (!in_array($filter, ['all','pending','dispatched','invoiced'])) $filter = 'pending';
$custFilter = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;
$search     = isset($_GET['q']) ? trim($_GET['q']) : '';
// From/To default to today's date whenever not explicitly supplied (first
// load, or a "Clear" click) — same behaviour as Dispatch Alert.
$fromDt     = (isset($_GET['fromdt']) && trim($_GET['fromdt']) !== '') ? trim($_GET['fromdt']) : date('Y-m-d');
$toDt       = (isset($_GET['todt'])   && trim($_GET['todt'])   !== '') ? trim($_GET['todt'])   : date('Y-m-d');

$where = [];
if ($filter == 'pending')    $where[] = "(s.dispatchdate IS NULL OR s.dispatchdate='0000-00-00')";
if ($filter == 'dispatched') $where[] = "(s.dispatchdate IS NOT NULL AND s.dispatchdate!='0000-00-00')";
if ($filter == 'invoiced')   $where[] = "(s.invoiceno IS NOT NULL AND s.invoiceno>0)";
if ($custFilter > 0) $where[] = "s.customer='$custFilter'";
if ($search !== '') {
    $sq = mysqli_real_escape_string($conn, $search);
    $where[] = "(a.name LIKE '%$sq%' OR s.vouchno LIKE '%$sq%' OR s.lrno LIKE '%$sq%')";
}
// Date range is always active — defaults to today/today — and built as a
// plain (unaliased) condition too, so the tab badge counts below stay in
// sync with the same date range instead of always showing the all-time total.
$dateCondPlain = '';
if ($fromDt !== '') {
    $where[] = "s.vouchdt >= '" . mysqli_real_escape_string($conn, $fromDt) . "'";
    $dateCondPlain .= " AND vouchdt >= '" . mysqli_real_escape_string($conn, $fromDt) . "'";
}
if ($toDt !== '') {
    $where[] = "s.vouchdt <= '" . mysqli_real_escape_string($conn, $toDt) . "'";
    $dateCondPlain .= " AND vouchdt <= '" . mysqli_real_escape_string($conn, $toDt) . "'";
}
if ($_ut === 3 && $_ac > 0) $where[] = "s.salesman='$_ac'";
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$res = mysqli_query($conn, "SELECT s.*, a.name AS custname, g.name AS godownname
                             FROM `saleorder` s
                             LEFT JOIN `accmast` a ON a.accode = s.customer
                             LEFT JOIN `godown` g ON g.code = s.godown
                             $whereSql
                             ORDER BY s.customer, s.vouchno") or die(mysqli_error($conn));
$orders = [];
while ($r = mysqli_fetch_assoc($res)) $orders[] = $r;

$_salCond = ($_ut === 3 && $_ac > 0) ? " AND s.salesman='$_ac'" : '';
$custListRes = mysqli_query($conn, "SELECT DISTINCT a.accode, a.name
                                     FROM saleorder s
                                     LEFT JOIN accmast a ON a.accode = s.customer
                                     WHERE 1=1$_salCond
                                     ORDER BY a.name");
$custList = [];
while ($r = mysqli_fetch_assoc($custListRes)) $custList[] = $r;

// Badge counts respect the same active date range as the list itself, so a
// tab never shows e.g. "(1)" while its filtered list is actually empty.
$_cntSalCond = ($_ut === 3 && $_ac > 0) ? " AND salesman='$_ac'" : '';
$cntAll        = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE 1=1$_cntSalCond$dateCondPlain"))['c'] ?? 0);
$cntPending    = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE (dispatchdate IS NULL OR dispatchdate='0000-00-00')$_cntSalCond$dateCondPlain"))['c'] ?? 0);
$cntDispatched = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE (dispatchdate IS NOT NULL AND dispatchdate!='0000-00-00')$_cntSalCond$dateCondPlain"))['c'] ?? 0);
$cntInvoiced   = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE (invoiceno IS NOT NULL AND invoiceno>0)$_cntSalCond$dateCondPlain"))['c'] ?? 0);

function df($v) { return ($v && $v!='0000-00-00') ? date('d-m-Y', strtotime($v)) : ''; }

include("includes/linkshead.php");
?>
<style>
body { background:#f0f2f5; padding:10px 12px 110px; }
.pg-head { max-width:1100px; margin:0 auto 12px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px; }
.pg-head h2 { font-size:17px; font-weight:700; color:#1e293b; margin:0; }
.tabs { display:flex; gap:6px; max-width:1300px; margin:0 auto 12px; flex-wrap:wrap; }
.tab { padding:8px 16px; border-radius:20px; font-size:12.5px; font-weight:600; text-decoration:none; color:#475569; background:#fff; border:1px solid #e2e8f0; }
.tab.active { background:#2563eb; color:#fff; border-color:#2563eb; }
.tab .cnt { opacity:.8; margin-left:4px; }
.filterbar { max-width:1300px; margin:0 auto 14px; display:flex; gap:8px; flex-wrap:wrap; align-items:center; }
.filterbar select, .filterbar input[type=text] { padding:9px 12px; border:1px solid #e2e8f0; border-radius:8px; font-size:13px; outline:none; background:#fff; }
.filterbar input[type=text] { flex:1; min-width:160px; }
.filterbar .dt-grp { display:flex; align-items:center; gap:6px; background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:0 10px; }
.filterbar .dt-grp span { font-size:11.5px; color:#94a3b8; font-weight:600; }
.filterbar input[type=date] { border:none; padding:9px 4px; font-size:13px; outline:none; background:transparent; color:#1e293b; }
.filterbar button { padding:9px 16px; border:none; border-radius:8px; background:#1e293b; color:#fff; font-weight:600; font-size:13px; cursor:pointer; }
.filterbar .clr { background:#f1f5f9; color:#475569; text-decoration:none; padding:9px 14px; border-radius:8px; font-size:12.5px; font-weight:600; display:inline-flex; align-items:center; }
.hint { max-width:1300px; margin:0 auto 12px; font-size:12px; color:#64748b; background:#eff6ff; border:1px solid #bfdbfe; padding:9px 12px; border-radius:8px; }
.badge { font-size:10.5px; font-weight:700; padding:4px 11px; border-radius:14px; white-space:nowrap; display:inline-block; }
.badge.pending { background:#fef3c7; color:#92400e; }
.badge.dispatched { background:#dcfce7; color:#166534; }
.saleinvbadge { font-size:10.5px; font-weight:700; padding:4px 11px; border-radius:14px; white-space:nowrap; display:inline-block; background:#dbeafe; color:#1d4ed8; }
.saleinvbadge a { color:inherit; text-decoration:none; }

.listwrap { max-width:1300px; margin:0 auto; background:#fff; border-radius:14px; box-shadow:0 1px 3px rgba(0,0,0,.07); overflow:hidden; }
.list-tbl { width:100%; border-collapse:collapse; font-size:12.8px; }
.list-tbl thead th { text-align:left; padding:11px 14px; background:#f8fafc; color:#64748b; font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:.03em; border-bottom:1px solid #eef1f5; white-space:nowrap; }
.list-tbl tbody td { padding:12px 14px; border-bottom:1px solid #f1f5f9; color:#334155; vertical-align:middle; }
.list-tbl tbody tr { transition:background .12s; }
.list-tbl tbody tr:hover { background:#f8fafc; }
.list-tbl tbody tr.checked { background:#eff6ff; }
.list-tbl tbody tr:last-child td { border-bottom:none; }
.list-tbl input[type=checkbox] { width:18px; height:18px; accent-color:#2563eb; cursor:pointer; }
.so-no { font-size:13px; font-weight:700; color:#1e293b; }
.so-cust { font-size:12px; color:#475569; }
.muted { color:#94a3b8; }
.lr-box { font-size:11px; color:#64748b; line-height:1.5; max-width:230px; }
.empty { text-align:center; padding:60px 20px; color:#94a3b8; max-width:1300px; margin:0 auto; }

.gen-bar { position:fixed; left:0; right:0; bottom:0; background:#fff; box-shadow:0 -4px 16px rgba(0,0,0,.1); padding:12px 16px; display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; z-index:500; }
.gen-bar .sel-info { font-size:12.5px; color:#475569; font-weight:600; }
.gen-bar button { padding:11px 22px; border:none; border-radius:9px; background:#16a34a; color:#fff; font-weight:700; font-size:13.5px; cursor:pointer; }
.gen-bar button:disabled { background:#cbd5e1; cursor:not-allowed; }

@media (max-width:900px) {
    .listwrap { overflow-x:auto; }
    .list-tbl { min-width:880px; }
}
@media (max-width:480px) {
    .pg-head h2 { font-size:15px; }
    .gen-bar { flex-direction:column; align-items:stretch; }
    .gen-bar button { width:100%; }
}
</style>
</head>
<body>

<div class="pg-head">
    <h2><i class="fa fa-file-invoice-dollar" style="color:#16a34a;margin-right:8px;"></i><?php echo $formname; ?></h2>
    <a href="default.php" style="font-size:12.5px;color:#64748b;text-decoration:none;"><i class="fa fa-arrow-left"></i> Back</a>
</div>

<?php
// Tab links carry the currently active search/date/customer filter forward
// as a querystring so switching tabs narrows the status without dropping
// the rest of the filter.
$_tabQs = http_build_query(array_filter([
    'q'        => $search,
    'fromdt'   => $fromDt,
    'todt'     => $toDt,
    'customer' => $custFilter > 0 ? $custFilter : '',
]));
$_tabQs = $_tabQs !== '' ? '&' . $_tabQs : '';
?>
<div class="tabs">
    <a class="tab <?php echo $filter=='pending'?'active':''; ?>"    href="?filter=pending<?php echo $_tabQs; ?>">Pending Dispatch <span class="cnt">(<?php echo $cntPending; ?>)</span></a>
    <a class="tab <?php echo $filter=='dispatched'?'active':''; ?>" href="?filter=dispatched<?php echo $_tabQs; ?>">Dispatched <span class="cnt">(<?php echo $cntDispatched; ?>)</span></a>
    <a class="tab <?php echo $filter=='invoiced'?'active':''; ?>"   href="?filter=invoiced<?php echo $_tabQs; ?>">Invoiced <span class="cnt">(<?php echo $cntInvoiced; ?>)</span></a>
    <a class="tab <?php echo $filter=='all'?'active':''; ?>"        href="?filter=all<?php echo $_tabQs; ?>">All <span class="cnt">(<?php echo $cntAll; ?>)</span></a>
</div>

<div class="hint"><i class="fa fa-circle-info"></i> Select one or more <b>dispatched, not-yet-invoiced</b> orders from the <b>same customer</b> below, then tap <b>Generate Invoice</b> to create a single Sale invoice from them.</div>

<form class="filterbar" method="GET">
    <input type="hidden" name="filter" value="<?php echo htmlspecialchars($filter); ?>">
    <select name="customer" onchange="this.form.submit()">
        <option value="0">-- All Customers --</option>
        <?php foreach ($custList as $c): ?>
        <option value="<?php echo (int)$c['accode']; ?>" <?php echo $custFilter==$c['accode']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
        <?php endforeach; ?>
    </select>
    <input type="text" name="q" placeholder="Search customer, SO#, LR no..." value="<?php echo htmlspecialchars($search); ?>">
    <div class="dt-grp"><span>From</span><input type="date" name="fromdt" value="<?php echo htmlspecialchars($fromDt); ?>"></div>
    <div class="dt-grp"><span>To</span><input type="date" name="todt" value="<?php echo htmlspecialchars($toDt); ?>"></div>
    <button type="submit"><i class="fa fa-search"></i></button>
    <?php if ($search !== '' || $fromDt !== date('Y-m-d') || $toDt !== date('Y-m-d') || $custFilter > 0): ?>
    <a class="clr" href="?filter=<?php echo htmlspecialchars($filter); ?>">Clear</a>
    <?php endif; ?>
</form>

<?php if (!$orders): ?>
    <div class="empty"><i class="fa fa-circle-check" style="font-size:34px;display:block;margin-bottom:10px;color:#16a34a;"></i>No sale orders found.</div>
<?php else: ?>
<div class="listwrap">
<table class="list-tbl">
    <thead>
        <tr>
            <th></th>
            <th>SO#</th>
            <th>Customer</th>
            <th>Order Date</th>
            <th>Godown</th>
            <th>Net Amount</th>
            <th>Status</th>
            <th>Dispatch Info</th>
            <th>Invoice</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($orders as $o):
        $isDispatched = !empty($o['dispatchdate']) && $o['dispatchdate'] != '0000-00-00';
        $isInvoiced   = (int)($o['invoiceno'] ?? 0) > 0;
        $isEligible   = $isDispatched && !$isInvoiced; // selectable for invoice generation
    ?>
        <tr id="card_<?php echo (int)$o['vouchno']; ?>">
            <td>
                <?php if ($isEligible): ?>
                <input type="checkbox" class="so-chk" value="<?php echo (int)$o['vouchno']; ?>"
                       data-customer="<?php echo (int)$o['customer']; ?>"
                       data-custname="<?php echo htmlspecialchars($o['custname'] ?? ''); ?>"
                       onchange="onCheckChange(this)">
                <?php endif; ?>
            </td>
            <td><span class="so-no">SO#<?php echo (int)$o['vouchno']; ?></span></td>
            <td><span class="so-cust"><?php echo htmlspecialchars($o['custname'] ?? ''); ?></span></td>
            <td><?php echo df($o['vouchdt']); ?></td>
            <td><?php echo !empty($o['godownname']) ? htmlspecialchars($o['godownname']) : '<span class="muted">—</span>'; ?></td>
            <td>&yen;<?php echo number_format((float)$o['netamount'],0); ?></td>
            <td><span class="badge <?php echo $isDispatched?'dispatched':'pending'; ?>"><?php echo $isDispatched?'Dispatched':'Pending Dispatch'; ?></span></td>
            <td>
                <?php if ($isDispatched): ?>
                <div class="lr-box">
                    <div><?php echo df($o['dispatchdate']); ?> by <?php echo htmlspecialchars($o['dispatchby']); ?></div>
                    <?php if ($o['lrno']): ?><div>LR: <?php echo htmlspecialchars($o['lrno']); ?> (<?php echo df($o['lrdate']); ?>)</div><?php endif; ?>
                    <?php if ($o['transporter']): ?><div><?php echo htmlspecialchars($o['transporter']); ?></div><?php endif; ?>
                </div>
                <?php else: ?><span class="muted">—</span><?php endif; ?>
            </td>
            <td>
                <?php if ($isInvoiced): ?>
                <span class="saleinvbadge"><a href="sale.php?mode=edit&vouchno=<?php echo (int)$o['invoiceno']; ?>">SAL#<?php echo (int)$o['invoiceno']; ?></a></span>
                <?php else: ?><span class="muted">—</span><?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>

<div class="gen-bar">
    <span class="sel-info" id="selInfo">No orders selected</span>
    <button type="button" id="genBtn" disabled onclick="generateInvoice()"><i class="fa fa-bolt"></i> Generate Invoice</button>
</div>

<?php include("includes/linksfoot.php"); ?>
<script>
function getChecked() { return Array.from(document.querySelectorAll('.so-chk:checked')); }

function onCheckChange(cb) {
    var checked = getChecked();
    var card = document.getElementById('card_'+cb.value);
    card.classList.toggle('checked', cb.checked);

    if (checked.length > 0) {
        var firstCust = checked[0].dataset.customer;
        var mismatched = checked.filter(function(c){ return c.dataset.customer !== firstCust; });
        if (mismatched.length) {
            Swal.fire({icon:'warning',title:'Same customer only',text:'All selected orders must belong to the same customer to combine into one invoice.',confirmButtonColor:'#2563eb'});
            cb.checked = false;
            card.classList.remove('checked');
            checked = getChecked();
        }
    }
    var info = document.getElementById('selInfo');
    var btn = document.getElementById('genBtn');
    if (checked.length === 0) {
        info.textContent = 'No orders selected';
        btn.disabled = true;
    } else {
        info.textContent = checked.length + ' order(s) selected — ' + checked[0].dataset.custname;
        btn.disabled = false;
    }
}

function generateInvoice() {
    var checked = getChecked();
    if (!checked.length) return;
    var vouchnos = checked.map(function(c){ return c.value; });
    Swal.fire({
        title: 'Generate Invoice?',
        text: 'This will create one Sale invoice for ' + vouchnos.length + ' order(s).',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Generate',
        confirmButtonColor: '#16a34a',
        cancelButtonColor: '#64748b'
    }).then(function(result) {
        if (!result.isConfirmed) return;
        $.post('includes/pendinginvoice_geninvoice.php', { vouchnos: vouchnos }, function(resp) {
            if (resp && resp.success) {
                Swal.fire({icon:'success',title:'Invoice Generated!',text:'Sale invoice SAL#'+resp.invoiceno+' created.',confirmButtonColor:'#16a34a'}).then(function(){
                    window.location.href = 'sale.php?mode=edit&vouchno=' + resp.invoiceno;
                });
            } else {
                Swal.fire({icon:'error',title:'Error',text:(resp && resp.message) ? resp.message : 'Could not generate invoice.',confirmButtonColor:'#2563eb'});
            }
        }, 'json').fail(function(){
            Swal.fire({icon:'error',title:'Error',text:'Request failed.',confirmButtonColor:'#2563eb'});
        });
    });
}
</script>
</body>
</html>
