<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.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");
}

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

$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%')";
}
$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;

$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)
                                     ORDER BY a.name");
$custList = [];
while ($r = mysqli_fetch_assoc($custListRes)) $custList[] = $r;

$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)"))['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:1100px; margin:0 auto 14px; display:flex; gap:8px; flex-wrap:wrap; }
.filterbar select, .filterbar input { 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 button { padding:9px 16px; border:none; border-radius:8px; background:#1e293b; color:#fff; font-weight:600; font-size:13px; cursor:pointer; }
.hint { max-width:1100px; margin:0 auto 12px; font-size:12px; color:#64748b; background:#eff6ff; border:1px solid #bfdbfe; padding:9px 12px; border-radius:8px; }

.cards { max-width:1100px; margin:0 auto; display:grid; grid-template-columns:repeat(auto-fill,minmax(290px,1fr)); gap:12px; }
.card { background:#fff; border-radius:12px; box-shadow:0 1px 3px rgba(0,0,0,.07); padding:14px 16px; border-left:4px solid #16a34a; position:relative; }
.card.checked { outline:2px solid #2563eb; }
.card-top { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:8px; gap:8px; }
.card-top label { display:flex; align-items:flex-start; gap:10px; cursor:pointer; flex:1; }
.card-top input[type=checkbox] { width:19px; height:19px; margin-top:1px; flex-shrink:0; accent-color:#2563eb; }
.so-no { font-size:13.5px; font-weight:700; color:#1e293b; }
.so-cust { font-size:12.5px; color:#475569; margin-top:2px; }
.card-row { display:flex; justify-content:space-between; font-size:12px; color:#64748b; margin-top:4px; }
.card-row b { color:#1e293b; font-weight:600; }
.lr-box { margin-top:8px; padding:8px 10px; background:#f8fafc; border-radius:8px; font-size:11.5px; color:#475569; line-height:1.5; }
.empty { text-align:center; padding:60px 20px; color:#94a3b8; max-width:1100px; 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:480px) {
    .pg-head h2 { font-size:15px; }
    .cards { grid-template-columns:1fr; }
    .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); ?>">
    <button type="submit"><i class="fa fa-search"></i></button>
</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="cards">
    <?php foreach ($orders as $o): ?>
    <div class="card" id="card_<?php echo (int)$o['vouchno']; ?>">
        <div class="card-top">
            <label>
                <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)">
                <span>
                    <div class="so-no">SO#<?php echo (int)$o['vouchno']; ?></div>
                    <div class="so-cust"><?php echo htmlspecialchars($o['custname'] ?? ''); ?></div>
                </span>
            </label>
        </div>
        <div class="card-row"><span>Order Date</span><b><?php echo df($o['vouchdt']); ?></b></div>
        <?php if (!empty($o['godownname'])): ?>
        <div class="card-row"><span>Godown</span><b><?php echo htmlspecialchars($o['godownname']); ?></b></div>
        <?php endif; ?>
        <div class="card-row"><span>Net Amount</span><b>&yen;<?php echo number_format((float)$o['netamount'],0); ?></b></div>
        <div class="lr-box">
            <div><b>Dispatched:</b> <?php echo df($o['dispatchdate']); ?> by <?php echo htmlspecialchars($o['dispatchby']); ?></div>
            <?php if ($o['lrno']): ?><div><b>LR No:</b> <?php echo htmlspecialchars($o['lrno']); ?> &nbsp; <b>LR Date:</b> <?php echo df($o['lrdate']); ?></div><?php endif; ?>
            <?php if ($o['transporter']): ?><div><b>Transporter:</b> <?php echo htmlspecialchars($o['transporter']); ?></div><?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
</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>
