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

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

// ── Defensive auto-migrate (in case saleorder.php hasn't run yet) ─────────
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");
}

$audituser = audituser();

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
if (!in_array($filter, ['all','pending','dispatched'])) $filter = 'pending';
$search = isset($_GET['q']) ? trim($_GET['q']) : '';

$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 ($search !== '') {
    $sq = mysqli_real_escape_string($conn, $search);
    $where[] = "(a.name LIKE '%$sq%' OR s.vouchno LIKE '%$sq%' OR s.lrno LIKE '%$sq%' OR s.remarks LIKE '%$sq%')";
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

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

$cntAll = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder"))['c'] ?? 0);
$cntPending = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM saleorder WHERE dispatchdate IS NULL OR dispatchdate='0000-00-00'"))['c'] ?? 0);
$cntDispatched = $cntAll - $cntPending;

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 90px; }
.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:1100px; 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; }
.searchbar { max-width:1100px; margin:0 auto 14px; display:flex; gap:8px; }
.searchbar input { flex:1; padding:10px 14px; border:1px solid #e2e8f0; border-radius:8px; font-size:13.5px; outline:none; background:#fff; }
.searchbar button { padding:10px 18px; border:none; border-radius:8px; background:#1e293b; color:#fff; font-weight:600; font-size:13px; cursor:pointer; }

.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 #f59e0b; }
.card.dispatched { border-left-color:#16a34a; }
.card-top { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:8px; }
.so-no { font-size:13.5px; font-weight:700; color:#1e293b; }
.so-cust { font-size:12.5px; color:#475569; margin-top:2px; }
.badge { font-size:10.5px; font-weight:700; padding:3px 10px; border-radius:14px; white-space:nowrap; }
.badge.pending { background:#fef3c7; color:#92400e; }
.badge.dispatched { background:#dcfce7; color:#166534; }
.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; }
.card-actions { margin-top:10px; display:flex; gap:8px; }
.btn-disp { flex:1; padding:9px; border:none; border-radius:8px; background:#2563eb; color:#fff; font-size:12.5px; font-weight:600; cursor:pointer; }
.btn-disp.edit { background:#f59e0b; }
.empty { text-align:center; padding:60px 20px; color:#94a3b8; max-width:1100px; margin:0 auto; }

/* Modal */
#dispModal { display:none; position:fixed; inset:0; background:rgba(15,23,42,.55); z-index:9999; align-items:center; justify-content:center; padding:14px; }
.modal-box { background:#fff; border-radius:14px; width:100%; max-width:440px; max-height:92vh; overflow:auto; }
.modal-head { padding:16px 18px; border-bottom:1px solid #f1f5f9; display:flex; justify-content:space-between; align-items:center; }
.modal-head h3 { margin:0; font-size:15px; font-weight:700; color:#1e293b; }
.modal-head button { background:#f1f5f9; border:none; width:30px; height:30px; border-radius:7px; font-size:16px; color:#64748b; cursor:pointer; }
.modal-body { padding:16px 18px; }
.mfl { margin-bottom:13px; }
.mfl label { display:block; font-size:12.5px; font-weight:600; color:#374151; margin-bottom:5px; }
.mfl input, .mfl select { width:100%; box-sizing:border-box; padding:10px 12px; border:1px solid #e2e8f0; border-radius:8px; font-size:13.5px; outline:none; font-family:inherit; }
.mfl input:focus, .mfl select:focus { border-color:#3b82f6; }
.modal-foot { padding:14px 18px; border-top:1px solid #f1f5f9; display:flex; gap:8px; }
.modal-foot button { flex:1; padding:11px; border:none; border-radius:8px; font-size:13.5px; font-weight:700; cursor:pointer; }
.mbtn-save { background:#16a34a; color:#fff; }
.mbtn-cancel { background:#f1f5f9; color:#374151; }

@media (max-width:480px) {
    .pg-head h2 { font-size:15px; }
    .cards { grid-template-columns:1fr; }
}
</style>
</head>
<body>

<div class="pg-head">
    <h2><i class="fa fa-truck-fast" style="color:#f59e0b;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>

<div class="tabs">
    <a class="tab <?php echo $filter=='pending'?'active':''; ?>"    href="?filter=pending">Pending Dispatch <span class="cnt">(<?php echo $cntPending; ?>)</span></a>
    <a class="tab <?php echo $filter=='dispatched'?'active':''; ?>" href="?filter=dispatched">Dispatched <span class="cnt">(<?php echo $cntDispatched; ?>)</span></a>
    <a class="tab <?php echo $filter=='all'?'active':''; ?>"        href="?filter=all">All <span class="cnt">(<?php echo $cntAll; ?>)</span></a>
</div>

<form class="searchbar" method="GET">
    <input type="hidden" name="filter" value="<?php echo htmlspecialchars($filter); ?>">
    <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-inbox" style="font-size:34px;display:block;margin-bottom:10px;"></i>No sale orders found.</div>
<?php else: ?>
<div class="cards">
    <?php foreach ($orders as $o):
        $isDispatched = !empty($o['dispatchdate']) && $o['dispatchdate'] != '0000-00-00';
    ?>
    <div class="card <?php echo $isDispatched?'dispatched':''; ?>">
        <div class="card-top">
            <div>
                <div class="so-no">SO#<?php echo (int)$o['vouchno']; ?></div>
                <div class="so-cust"><?php echo htmlspecialchars($o['custname'] ?? ''); ?></div>
            </div>
            <span class="badge <?php echo $isDispatched?'dispatched':'pending'; ?>"><?php echo $isDispatched?'Dispatched':'Pending'; ?></span>
        </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>Order Qty.</span><b><?php echo (float)$o['totqty']; ?></b></div>
        <div class="card-row"><span>Net Amount</span><b><?php echo number_format((float)$o['netamount'],0); ?></b></div>
        <?php if ((int)($o['invoiceno'] ?? 0) > 0): ?>
        <div class="card-row"><span>Invoice</span><b>SAL#<?php echo (int)$o['invoiceno']; ?></b></div>
        <?php endif; ?>

        <?php if ($isDispatched): ?>
        <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; ?>
            <?php if ($o['transportmode']): ?><div><b>Mode:</b> <?php echo htmlspecialchars($o['transportmode']); ?></div><?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="card-actions">
            <button type="button" class="btn-disp <?php echo $isDispatched?'edit':''; ?>"
                onclick='openDispModal(<?php echo json_encode($o); ?>)'>
                <i class="fa fa-truck"></i> <?php echo $isDispatched?'Update Dispatch':'Mark Dispatched'; ?>
            </button>
            <a href="saleorder.php?mode=edit&vouchno=<?php echo (int)$o['vouchno']; ?>" style="padding:9px 14px;border-radius:8px;background:#f1f5f9;color:#475569;text-decoration:none;font-size:12.5px;"><i class="fa fa-eye"></i></a>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Dispatch Update Modal -->
<div id="dispModal">
    <div class="modal-box">
        <div class="modal-head">
            <h3 id="dmTitle">Update Dispatch</h3>
            <button type="button" onclick="closeDispModal()">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="dm_vouchno">
            <div class="mfl"><label>Dispatch Date</label><input type="date" id="dm_dispatchdate"></div>
            <div class="mfl"><label>Dispatched By</label><input type="text" id="dm_dispatchby" placeholder="Staff name"></div>
            <div class="mfl"><label>Mode of Transport</label>
                <select id="dm_transportmode" onchange="document.getElementById('dm_modeother').style.display=(this.value=='Other')?'block':'none';">
                    <option value="">-- Select --</option>
                    <option>By Road</option><option>By Rail</option><option>By Air</option><option>By Sea</option><option>Courier</option><option>Self Pickup</option><option value="Other">Other</option>
                </select>
                <input type="text" id="dm_modeother" placeholder="Specify mode" style="display:none;margin-top:7px;">
            </div>
            <div class="mfl"><label>LR No.</label><input type="text" id="dm_lrno" placeholder="LR / Bilty No."></div>
            <div class="mfl"><label>LR Date</label><input type="date" id="dm_lrdate"></div>
            <div class="mfl"><label>Transporter</label><input type="text" id="dm_transporter" placeholder="Transporter name"></div>
        </div>
        <div class="modal-foot">
            <button type="button" class="mbtn-cancel" onclick="closeDispModal()">Cancel</button>
            <button type="button" class="mbtn-save" onclick="saveDispatch()">Save</button>
        </div>
    </div>
</div>

<?php include("includes/linksfoot.php"); ?>
<script>
var CURRENT_USER = <?php echo json_encode($audituser); ?>;

function openDispModal(o) {
    document.getElementById('dm_vouchno').value = o.vouchno;
    document.getElementById('dmTitle').textContent = 'Dispatch — SO#' + o.vouchno;
    document.getElementById('dm_dispatchdate').value = (o.dispatchdate && o.dispatchdate!='0000-00-00') ? o.dispatchdate : new Date().toISOString().slice(0,10);
    document.getElementById('dm_dispatchby').value = o.dispatchby || CURRENT_USER || '';
    document.getElementById('dm_lrno').value = o.lrno || '';
    document.getElementById('dm_lrdate').value = (o.lrdate && o.lrdate!='0000-00-00') ? o.lrdate : '';
    document.getElementById('dm_transporter').value = o.transporter || '';
    var modeSel = document.getElementById('dm_transportmode');
    var modeOther = document.getElementById('dm_modeother');
    var stdModes = ['By Road','By Rail','By Air','By Sea','Courier','Self Pickup'];
    if (o.transportmode && stdModes.indexOf(o.transportmode) === -1) {
        modeSel.value = 'Other'; modeOther.style.display='block'; modeOther.value = o.transportmode;
    } else {
        modeSel.value = o.transportmode || ''; modeOther.style.display='none'; modeOther.value='';
    }
    document.getElementById('dispModal').style.display = 'flex';
}
function closeDispModal() { document.getElementById('dispModal').style.display = 'none'; }
document.getElementById('dispModal').addEventListener('click', function(e){ if (e.target === this) closeDispModal(); });

function saveDispatch() {
    var modeVal = document.getElementById('dm_transportmode').value;
    if (modeVal === 'Other') modeVal = document.getElementById('dm_modeother').value.trim();
    var payload = {
        vouchno: document.getElementById('dm_vouchno').value,
        dispatchdate: document.getElementById('dm_dispatchdate').value,
        dispatchby: document.getElementById('dm_dispatchby').value,
        transportmode: modeVal,
        lrno: document.getElementById('dm_lrno').value,
        lrdate: document.getElementById('dm_lrdate').value,
        transporter: document.getElementById('dm_transporter').value
    };
    if (!payload.dispatchdate) {
        Swal.fire({icon:'warning',title:'Dispatch date is required',confirmButtonColor:'#2563eb'});
        return;
    }
    $.post('includes/dispatchalert_update.php', payload, function(resp) {
        if (resp && resp.success) {
            closeDispModal();
            Swal.fire({icon:'success',title:'Saved!',text:'Dispatch details updated.',timer:1400,showConfirmButton:false}).then(function(){
                window.location.reload();
            });
        } else {
            Swal.fire({icon:'error',title:'Error',text:(resp && resp.message) ? resp.message : 'Could not save.',confirmButtonColor:'#2563eb'});
        }
    }, 'json').fail(function(){
        Swal.fire({icon:'error',title:'Error',text:'Request failed.',confirmButtonColor:'#2563eb'});
    });
}
</script>
</body>
</html>
