<?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);

$custFilter = isset($_GET['customer']) ? (int)$_GET['customer'] : 0;
$search     = isset($_GET['q']) ? trim($_GET['q']) : '';
$fromDt     = isset($_GET['fromdt']) ? trim($_GET['fromdt']) : '';
$toDt       = isset($_GET['todt']) ? trim($_GET['todt']) : '';

$where = ["(s.dispatchdate IS NOT NULL AND s.dispatchdate!='0000-00-00')", "(s.invoiceno=0 OR s.invoiceno IS NULL)"];
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%')";
}
if ($fromDt !== '') $where[] = "s.vouchdt >= '" . mysqli_real_escape_string($conn, $fromDt) . "'";
if ($toDt   !== '') $where[] = "s.vouchdt <= '" . mysqli_real_escape_string($conn, $toDt) . "'";
if ($_ut === 3 && $_ac > 0) $where[] = "s.salesman='$_ac'";
$whereSql = '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 (s.dispatchdate IS NOT NULL AND s.dispatchdate!='0000-00-00')
                                       AND (s.invoiceno=0 OR s.invoiceno IS NULL)$_salCond
                                     ORDER BY a.name");
$custList = [];
while ($r = mysqli_fetch_assoc($custListRes)) $custList[] = $r;

$_salCondNoAlias = ($_ut === 3 && $_ac > 0) ? " AND salesman='$_ac'" : '';
$totalPending = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE (dispatchdate IS NOT NULL AND dispatchdate!='0000-00-00') AND (invoiceno=0 OR invoiceno IS NULL)$_salCondNoAlias"))['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; }
.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; }

.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; ?> <span style="font-size:12px;color:#94a3b8;font-weight:500;">(<?php echo $totalPending; ?>)</span></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>

<div class="hint"><i class="fa fa-circle-info"></i> Select one or more 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">
    <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 !== '' || $toDt !== '' || $custFilter > 0): ?>
    <a class="clr" href="?">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 pending invoices. All dispatched orders are invoiced.</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>Dispatch Info</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($orders as $o): ?>
        <tr id="card_<?php echo (int)$o['vouchno']; ?>">
            <td>
                <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)">
            </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>
                <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>
            </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>
