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

$formname  = 'Despatch';
$maindb    = 'despatch';
$printfile = 'despatch_print.php';
$file      = 'despatch.php';
$keyfld    = 'vouchno';
$keycond   = '';
$source    = 'DSP';

$zdb      = $_SESSION["zdbyear_" . $dbname];
$compcd   = $_SESSION["comp_"    . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

mysqli_select_db($conn, $zdb);

// ── Auto-migration ─────────────────────────────────────────────────────────
$chk = mysqli_query($conn, "SHOW COLUMNS FROM `despatch` LIKE 'containerno'");
if ($chk && mysqli_num_rows($chk) == 0) {
    mysqli_query($conn, "ALTER TABLE `despatch` ADD COLUMN `containerno` varchar(50) NOT NULL DEFAULT '' AFTER `remarks`");
}
$chk2 = mysqli_query($conn, "SHOW COLUMNS FROM `despatch` LIKE 'arrivaldate'");
if ($chk2 && mysqli_num_rows($chk2) == 0) {
    mysqli_query($conn, "ALTER TABLE `despatch` ADD COLUMN `arrivaldate` date NULL DEFAULT NULL AFTER `containerno`");
}
$chk3 = mysqli_query($conn, "SHOW COLUMNS FROM `despatch` LIKE 'arrivalgodown'");
if ($chk3 && mysqli_num_rows($chk3) == 0) {
    mysqli_query($conn, "ALTER TABLE `despatch` ADD COLUMN `arrivalgodown` int(11) NOT NULL DEFAULT 0 AFTER `arrivaldate`");
}
// `customer` and `totqty` are written on every Save (see INSERT/UPDATE below) and
// read back in the search/print/arrival screens, but were missing from the
// auto-migration list above — on a table created before these fields existed,
// saving would fail with "Unknown column" since the columns simply don't exist.
foreach (['customer' => "int(11) NOT NULL DEFAULT 0", 'totqty' => "double NOT NULL DEFAULT 0"] as $col => $def) {
    $chkCol = mysqli_query($conn, "SHOW COLUMNS FROM `despatch` LIKE '$col'");
    if ($chkCol && mysqli_num_rows($chkCol) == 0) {
        mysqli_query($conn, "ALTER TABLE `despatch` ADD COLUMN `$col` $def");
    }
}
$chk4 = mysqli_query($conn, "SHOW TABLES LIKE 'packlist'");
if (mysqli_num_rows($chk4) == 0) {
    mysqli_query($conn, "CREATE TABLE `packlist` (
        `srl`         int(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `dspvouchno`  int(11)      NOT NULL DEFAULT 0,
        `containerno` varchar(50)  NOT NULL DEFAULT '',
        `bcvouchno`   int(11)      NOT NULL DEFAULT 0,
        `shipmark`    varchar(100) NOT NULL DEFAULT '',
        `description` varchar(200) NOT NULL DEFAULT '',
        `picfile`     varchar(200) NOT NULL DEFAULT '',
        `ctn`         double       NOT NULL DEFAULT 0,
        `qty`         double       NOT NULL DEFAULT 0,
        `tqty`        double       NOT NULL DEFAULT 0,
        `cbm`         double       NOT NULL DEFAULT 0,
        `weight`      double       NOT NULL DEFAULT 0,
        INDEX (`dspvouchno`), INDEX (`containerno`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));
}

include("includes/vouchno_generate.php");
include("includes/prev_next.php");

// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vouchdt     = mysqli_real_escape_string($conn, trim($_POST["vouchdt"]));
    $godown      = isset($_POST["godown"])   ? (int)$_POST["godown"]   : 0;
    $remarks     = mysqli_real_escape_string($conn, trim($_POST["remarks"]));
    $containerno = mysqli_real_escape_string($conn, trim($_POST["containerno"] ?? ''));

    // Derive customer from loadingplan lines for this container
    $customer = 0;
    if ($containerno != '') {
        $lpCust = mysqli_query($conn, "SELECT lt.customer FROM loadingplantr lt
            INNER JOIN loadingplan lp ON lp.vouchno = lt.vouchno
            WHERE lp.containerno='$containerno' AND lt.customer > 0 LIMIT 1");
        if ($lpCust && ($lr = mysqli_fetch_assoc($lpCust))) $customer = (int)$lr['customer'];
    }

    $a = 1;
    $vd = preg_match('/^(\\d{2})-(\\d{2})-(\\d{4})$/',$vouchdt,$m) ? $m[3].'-'.$m[2].'-'.$m[1] : $vouchdt;
    if ($vouchdt == '' || $vd == '') { $a=0; browse("Date Cannot Be Empty"); header("refresh:1; url=$file?mode=last"); }
    if ($a==1 && $godown<=0) { $a=0; browse("Please Select Godown"); header("refresh:1; url=$file?mode=last"); }

    // ── Read packlist POST rows (stock deduction source) ─────────────────────
    $plBcA   = $_POST['pl_bcvouchno']   ?? [];
    $plSmA   = $_POST['pl_shipmark']    ?? [];
    $plDescA = $_POST['pl_description'] ?? [];
    $plPicA  = $_POST['pl_picfile']     ?? [];
    $plCtnA  = $_POST['pl_ctn']         ?? [];
    $plQtyA  = $_POST['pl_qty']         ?? [];
    $plTqtyA = $_POST['pl_tqty']        ?? [];
    $plCbmA  = $_POST['pl_cbm']         ?? [];
    $plWtA   = $_POST['pl_weight']      ?? [];

    $plLines = []; $totqty = 0;
    foreach ($plDescA as $pi => $pd) {
        $pd = trim($pd); if ($pd == '') continue;
        $plLines[] = [
            'bcvouchno'   => (int)($plBcA[$pi]  ?? 0),
            'shipmark'    => trim($plSmA[$pi]    ?? ''),
            'description' => $pd,
            'picfile'     => trim($plPicA[$pi]   ?? ''),
            'ctn'         => (float)($plCtnA[$pi]  ?? 0),
            'qty'         => (float)($plQtyA[$pi]  ?? 0),
            'tqty'        => (float)($plTqtyA[$pi] ?? 0),
            'cbm'         => (float)($plCbmA[$pi]  ?? 0),
            'weight'      => (float)($plWtA[$pi]   ?? 0),
        ];
        $totqty += (float)($plTqtyA[$pi] ?? 0);
    }

    if ($a == 1) {
        $audituser = mysqli_real_escape_string($conn, audituser());
        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`
                (`vouchno`,`vouchdt`,`customer`,`godown`,`remarks`,`containerno`,`totqty`,`adduser`,`adddate`,`addtime`)
                VALUES ('$qvouch','$vd','$customer','$godown','$remarks','$containerno','$totqty','$audituser',CURDATE(),CURTIME())")
            or die(mysqli_error($conn));
        } else {
            mysqli_query($conn, "UPDATE `$maindb` SET
                `vouchdt`='$vd', `customer`='$customer', `godown`='$godown', `remarks`='$remarks',
                `containerno`='$containerno', `totqty`='$totqty',
                `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
                WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
        }

        // ── Save packlist rows ────────────────────────────────────────────────
        mysqli_query($conn, "DELETE FROM `packlist` WHERE `dspvouchno`='$qvouch'") or die(mysqli_error($conn));
        foreach ($plLines as $pl) {
            $pbc = $pl['bcvouchno'];
            $psm = mysqli_real_escape_string($conn, $pl['shipmark']);
            $pd  = mysqli_real_escape_string($conn, $pl['description']);
            $ppf = mysqli_real_escape_string($conn, $pl['picfile']);
            mysqli_query($conn, "INSERT INTO `packlist`
                (`dspvouchno`,`containerno`,`bcvouchno`,`shipmark`,`description`,`picfile`,`ctn`,`qty`,`tqty`,`cbm`,`weight`)
                VALUES ('$qvouch','$containerno','$pbc','$psm','$pd','$ppf','{$pl['ctn']}','{$pl['qty']}','{$pl['tqty']}','{$pl['cbm']}','{$pl['weight']}')")
            or die(mysqli_error($conn));
        }

        // ── Stock deduction from packlist rows (CTN-based, negative = stock-out) ─
        mysqli_query($conn, "DELETE FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
        foreach ($plLines as $pl) {
            $ctn = (float)$pl['ctn']; if ($ctn <= 0) continue;
            $d   = mysqli_real_escape_string($conn, $pl['description']);
            $sm  = mysqli_real_escape_string($conn, $pl['shipmark']);
            $negCtn=$ctn*-1; $negTqty=(float)$pl['tqty']*-1; $negCbm=(float)$pl['cbm']*-1; $negWt=(float)$pl['weight']*-1;
            mysqli_query($conn, "INSERT INTO `stockledger`
                (`vouchdt`,`source`,`vouchno`,`godown`,`customer`,`supplier`,`description`,`modelno`,`marka`,`qty`,`ctn`,`tcbm`,`tweight`)
                VALUES ('$vd','$source','$qvouch','$godown','$customer','0','$d','','$sm','$negTqty','$negCtn','$negCbm','$negWt')")
            or die(mysqli_error($conn));
        }

        $rurl = "$file?$keyfld=$qvouch&mode=edit";
        if ($addflag == 1) insmess($rurl); else updmess($rurl);
    }
}

// ── Fetch record ─────────────────────────────────────────────────────────────
$get = [];
$plLines = [];
if ($addflag != 1 && $qvouch > 0) {
    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    $get    = mysqli_fetch_array($result);
    if (!$get) $get = [];
    // Fetch packlist rows
    $plRes = mysqli_query($conn, "SELECT * FROM `packlist` WHERE `dspvouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_assoc($plRes)) { $plLines[] = $r; }
}

// Container list: unpicked = not already referenced by any other despatch (except current)
$containerList = [];
$cnSql = "SELECT `vouchno`, `containerno`, `vouchdt` FROM `loadingplan`
          WHERE `containerno` != ''
          AND `vouchno` NOT IN (
              SELECT DISTINCT `containerno` FROM `despatch` WHERE `containerno` != ''
              " . ($qvouch > 0 ? "AND `vouchno` != '$qvouch'" : "") . "
          )
          ORDER BY `vouchno` DESC";
// Actually containerno is a string in loadingplan, despatch stores the string
// Fix: despatch.containerno stores the container NO string, not the LP vouchno
$cnSql = "SELECT `vouchno`, `containerno`, `vouchdt` FROM `loadingplan`
          WHERE `containerno` != ''
          AND `containerno` NOT IN (
              SELECT `containerno` FROM `despatch` WHERE `containerno` != ''
              " . ($qvouch > 0 ? "AND `vouchno` != '$qvouch'" : "") . "
          )
          ORDER BY `vouchno` DESC";
$cnRes = mysqli_query($conn, $cnSql) or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($cnRes)) { $containerList[] = $r; }
// If editing, also include current voucher's container
$currentContainer = $get['containerno'] ?? '';

// Fetch LP summary lines for display (from loadingplantr + related tables)
$lpSummaryLines = [];
if ($currentContainer != '') {
    $lpSum = mysqli_query($conn,
        "SELECT lt.*, s.name AS supname, c.name AS custname, lp.vouchno AS lpvouchno
         FROM loadingplantr lt
         INNER JOIN loadingplan lp ON lp.vouchno = lt.vouchno
         LEFT JOIN accmast s ON s.accode = lt.supplier
         LEFT JOIN accmast c ON c.accode = lt.customer
         WHERE lp.containerno='" . mysqli_real_escape_string($conn, $currentContainer) . "'
         ORDER BY lt.srl") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_assoc($lpSum)) $lpSummaryLines[] = $r;
}

function acc_name($conn, $accode) {
    $accode = (int)$accode;
    if ($accode <= 0) return '';
    $r = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$accode'");
    $row = $r ? mysqli_fetch_assoc($r) : null;
    return $row ? $row['name'] : '';
}
$customername = isset($get['customer']) ? acc_name($conn, $get['customer']) : '';

function acc_list($conn, $grpcode) {
    $list = [];
    $r = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `grpcode`='$grpcode' AND `accode`>50 ORDER BY `name` ASC");
    if ($r) { while ($row = mysqli_fetch_assoc($r)) { $list[] = $row; } }
    return $list;
}
$customerList = acc_list($conn, '010');

$godownList = [];
$gres = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` ORDER BY `name` ASC");
if ($gres) { while ($grow = mysqli_fetch_assoc($gres)) { $godownList[] = $grow; } }

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    mysqli_query($conn, "DELETE FROM `packlist`   WHERE `dspvouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    delmess("$file?mode=last");
    exit;
}

function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}
function fvn($get, $key, $default = '') {
    if (!isset($get[$key]) || $get[$key] === '' || $get[$key] === null) return $default;
    $v = (float)$get[$key];
    return ($v == (int)$v) ? (string)(int)$v : (string)$v;
}

if (isset($get['vouchdt']) && $get['vouchdt'] != '' && $get['vouchdt'] != '0000-00-00') {
    $vouchdt_disp = date('Y-m-d', strtotime($get['vouchdt']));
} else {
    $vouchdt_disp = date('Y-m-d');
}

include("includes/linkshead.php");
?>
<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-badge { font-size:11.5px; font-weight:600; color:#64748b; background:#f1f5f9; padding:4px 12px; border-radius:20px; }

    .sim-body { padding:18px 20px; }

    .fr { display:flex; align-items:center; margin-bottom:11px; gap:0; }
    .fr-grid { display:grid; grid-template-columns:1fr 1fr 1fr; gap:9px 14px; margin-bottom:11px; }
    .fl { display:flex; flex-direction:column; gap:4px; }
    .lbl { font-size:11px; font-weight:600; color:#64748b; margin-bottom:2px; }

    .finp {
        padding:7px 11px; background:#f8fafc; border:1px solid #e2e8f0;
        border-radius:6px; font-size:12.5px; color:#1e293b; outline:none;
        transition:border-color .15s, background .15s, box-shadow .15s;
        width:100%; box-sizing:border-box; font-family:inherit;
    }
    .finp:focus { background:#fff; border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
    .finp:disabled { background:#f1f5f9; color:#94a3b8; }
    .finp.required-star { border-left:3px solid #3b82f6; }

    .fl .select2-container { flex:1; }
    .fl .select2-container .select2-selection--single {
        height:34px; border:1px solid #e2e8f0; border-radius:6px; background:#f8fafc;
        display:flex; align-items:center;
    }
    .fl .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height:normal; font-size:12.5px; color:#1e293b; padding-left:11px;
    }
    .fl .select2-container--default .select2-selection--single .select2-selection__arrow { height:32px; right:6px; }
    .fl .select2-container--default.select2-container--focus .select2-selection--single,
    .fl .select2-container--default.select2-container--open .select2-selection--single {
        border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12);
    }
    .fl .select2-container.required-star .select2-selection--single { border-left:3px solid #3b82f6; }

    .grid-wrap { margin-top:16px; border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; }
    table.dgrid { width:100%; border-collapse:collapse; font-size:12px; }
    table.dgrid th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em;
        padding:8px 6px; border-bottom:2px solid #e2e8f0; text-align:center; white-space:nowrap;
    }
    table.dgrid td { padding:5px 6px; border-bottom:1px solid #f1f5f9; }
    table.dgrid td.num { text-align:right; }
    table.dgrid input, table.dgrid select {
        width:100%; box-sizing:border-box; padding:6px 8px; font-size:12px;
        border:1px solid #e2e8f0; border-radius:5px; background:#f8fafc; outline:none;
        text-align:right; font-family:inherit;
    }
    table.dgrid input.desc-inp, table.dgrid input.txt-inp { text-align:left; }
    table.dgrid input:focus, table.dgrid select:focus { background:#fff; border-color:#3b82f6; }
    table.dgrid tfoot td { background:#f8fafc; font-weight:700; color:#1e293b; padding:8px 6px; border-top:2px solid #e2e8f0; }
    .stock-hint { font-size:10.5px; color:#16a34a; margin-top:2px; }
    .stock-hint.low { color:#dc2626; }

    .row-del { background:#fee2e2; color:#dc2626; border:none; border-radius:5px; width:26px; height:26px; cursor:pointer; font-size:12px; }
    .row-del:hover { background:#fecaca; }
    .add-row-btn { margin-top:10px; padding:7px 14px; background:#16a34a; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:12.5px; font-weight:600; }
    .add-row-btn:hover { background:#15803d; }

    .audit-info { margin-top:18px; padding-top:14px; border-top:1px dashed #e2e8f0; display:flex; flex-wrap:wrap; gap:16px; font-size:11px; color:#94a3b8; }
    .audit-info i { margin-right:4px; }
    .audit-info b { color:#64748b; }

    .btn-bar { display:flex; justify-content:center; align-items:center; gap:8px; padding:16px 20px; border-top:1px solid #f1f5f9; background:#fafafa; }
    .abtn {
        width:46px; height:46px; border-radius:10px; border:none; cursor:pointer;
        font-size:15px; color:#fff; display:inline-flex; align-items:center; justify-content:center;
        text-decoration:none; transition:transform .12s, box-shadow .12s, filter .12s; position:relative;
    }
    .abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); filter:brightness(1.06); }
    .abtn:active { transform:translateY(0); box-shadow:none; filter:brightness(.95); }
    .abtn[disabled] { opacity:.4; pointer-events:none; }
    .abtn-prev   { background:#2563eb; }
    .abtn-next   { background:#38bdf8; }
    .abtn-search { background:#7f5539; }
    .abtn-print  { background:#4a5759; }
    .abtn-add    { background:#16a34a; }
    .abtn-edit   { background:#ffba08; }
    .abtn-del    { background:#e71d36; }
    .abtn-exit   { background:#e2e8f0; color:#64748b; }
    .abtn::after {
        content: attr(data-tip); position:absolute; bottom:calc(100% + 6px); left:50%;
        transform:translateX(-50%); background:#1e293b; color:#fff; font-size:10px; font-weight:600;
        padding:3px 8px; border-radius:4px; white-space:nowrap; opacity:0; pointer-events:none; transition:opacity .15s;
    }
    .abtn:hover::after { opacity:1; }
    .abtn-save   { width:auto; padding:0 18px; background:#16a34a; gap:6px; font-size:12.5px; font-weight:600; }
    .abtn-cancel { width:auto; padding:0 16px; background:#64748b; gap:6px; font-size:12.5px; font-weight:600; }

    /* ── Responsive: tablet / mobile ──────────────────────────────────── */
    @media (max-width: 768px) {
        body { padding:6px 8px; }
        .sim-card { border-radius:8px; }
        .sim-card-header { padding:10px 14px; flex-wrap:wrap; gap:8px; }
        .sim-card-header h2 { font-size:13.5px; }
        .sim-body { padding:14px; }

        .fr, .fr-grid { display:flex !important; flex-direction:column !important; gap:10px; align-items:stretch; }
        .fl { width:100%; }
        .lbl { width:100%; text-align:left; margin-bottom:2px; }
        .finp { font-size:13px; padding:8px 10px; }

        .grid-wrap { margin-top:12px; border-radius:6px; }
        table.dgrid { font-size:11px; min-width:560px; }
        table.dgrid th, table.dgrid td { padding:5px 5px; }
        table.dgrid input { font-size:11px; padding:5px 4px; }

        .add-row-btn { width:100%; justify-content:center; }
        .btn-bar { gap:6px; padding:12px 10px; flex-wrap:wrap; }
        .abtn { flex:1 1 auto; min-width:42px; height:42px; font-size:13px; }
    }
</style>

<body>
<form action="" method="POST">
<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-truck" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <div style="display:flex;gap:8px;align-items:center;">
            <span class="sim-badge">Voucher No: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
        </div>
    </div>

    <div class="sim-body">

        <div class="fr-grid">
            <div class="fl">
                <span class="lbl">Date <span style="color:#ef4444;">*</span></span>
                <input type="date" name="vouchdt" id="vouchdt" class="finp form focusfield required-star"
                    value="<?php echo htmlspecialchars($get['vouchdt'] ?? ''); ?>">
            </div>
            <div class="fl">
                <span class="lbl">Godown <span style="color:#ef4444;">*</span></span>
                <select name="godown" id="godown" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Godown --</option>
                    <?php foreach ($godownList as $row): ?>
                    <option value="<?php echo (int)$row['code']; ?>" <?php echo (fv($get,'godown') == $row['code']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($row['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Container No.</span>
                <select name="containerno" id="containerno" class="finp form select2" style="width:100%;" onchange="onContainerPick(this.value)">
                    <option value="">-- Select Container --</option>
                    <?php if ($currentContainer != ''): ?>
                    <option value="<?php echo htmlspecialchars($currentContainer); ?>" selected><?php echo htmlspecialchars($currentContainer); ?></option>
                    <?php endif; ?>
                    <?php foreach ($containerList as $cn): ?>
                    <?php if ($cn['containerno'] == $currentContainer) continue; ?>
                    <option value="<?php echo htmlspecialchars($cn['containerno']); ?>">
                        <?php echo htmlspecialchars($cn['containerno']); ?> (LP#<?php echo $cn['vouchno']; ?> · <?php echo $cn['vouchdt']; ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if (!empty($get['arrivaldate'])): ?>
            <div class="fl">
                <span class="lbl">Arrival Date</span>
                <input type="text" readonly value="<?php echo date('d-m-Y', strtotime($get['arrivaldate'])); ?>"
                    style="background:#d1fae5;border-color:#6ee7b7;color:#065f46;font-weight:700;" class="finp">
            </div>
            <?php endif; ?>
        </div>

        <div class="fr">
            <span class="lbl" style="min-width:90px;">Remarks</span>
            <input type="text" name="remarks" class="finp form" maxlength="100" value="<?php echo fv($get,'remarks'); ?>">
        </div>

        <!-- ── Grid 1: Loading Plan Summary (from container) ──────────────── -->
        <div style="margin-bottom:16px;">
            <div style="font-size:13px;font-weight:700;color:#1e293b;margin-bottom:8px;">
                <i class="fa fa-ship" style="color:#3b82f6;margin-right:7px;"></i>Loading Plan Summary
                <?php if ($currentContainer): ?><span style="font-size:11px;font-weight:500;color:#64748b;margin-left:8px;">Container: <b><?php echo htmlspecialchars($currentContainer); ?></b></span><?php endif; ?>
            </div>
            <div class="grid-wrap" id="lpSummaryWrap">
            <table style="width:100%;border-collapse:collapse;font-size:11.5px;table-layout:fixed;min-width:1150px;" id="lpSummaryGrid">
                <thead>
                    <tr>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:2%;text-align:center;font-size:10px;text-transform:uppercase;">#</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:9%;text-align:left;font-size:10px;text-transform:uppercase;">Supplier</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:9%;text-align:left;font-size:10px;text-transform:uppercase;">Customer</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:6%;text-align:left;font-size:10px;text-transform:uppercase;">Ship Mk</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:14%;text-align:left;font-size:10px;text-transform:uppercase;">Description</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:4%;text-align:right;font-size:10px;text-transform:uppercase;">CTN</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">T.QTY</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:6%;text-align:right;font-size:10px;text-transform:uppercase;">AMT</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:6%;text-align:right;font-size:10px;text-transform:uppercase;">Cli.Adv</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">OUR</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">Shp.Amt</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">Credit</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:6%;text-align:right;font-size:10px;text-transform:uppercase;">Balance</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">CBM</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:5%;text-align:right;font-size:10px;text-transform:uppercase;">Weight</th>
                        <th style="background:#0f172a;color:#e2e8f0;padding:8px 6px;width:4%;text-align:right;font-size:10px;text-transform:uppercase;">CRY</th>
                    </tr>
                </thead>
                <tbody id="lpSummaryBody">
                <?php if ($lpSummaryLines):
                    $stCtn=$stTqty=$stAmt=$stAdv=$stOur=$stShp=$stCr=$stBal=$stCbm=$stWt=$stCry=0;
                    foreach ($lpSummaryLines as $si => $sl):
                    $stCtn+=$sl['ctn']; $stTqty+=$sl['tqty']; $stAmt+=$sl['amt'];
                    $stAdv+=$sl['advance']; $stOur+=$sl['our']; $stShp+=$sl['shipperamount'];
                    $stCr+=$sl['credit']; $stBal+=$sl['balance']; $stCbm+=$sl['cbm'];
                    $stWt+=$sl['weight']; $stCry+=$sl['cry'];
                    if (!function_exists('pfs')) { function pfs($v){ $v=(float)$v; return $v?number_format($v,2):''; } }
                ?>
                <tr style="border-bottom:1px solid #f1f5f9;">
                    <td style="text-align:center;color:#94a3b8;font-size:11px;padding:6px 4px;"><?php echo $si+1; ?></td>
                    <td style="padding:6px 5px;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo htmlspecialchars($sl['supname']??''); ?>"><?php echo htmlspecialchars($sl['supname']??''); ?></td>
                    <td style="padding:6px 5px;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo htmlspecialchars($sl['custname']??''); ?>"><?php echo htmlspecialchars($sl['custname']??''); ?></td>
                    <td style="padding:6px 5px;font-size:11px;"><?php echo htmlspecialchars($sl['shipmark']); ?></td>
                    <td style="padding:6px 5px;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo htmlspecialchars($sl['description']); ?>"><?php echo htmlspecialchars($sl['description']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['ctn']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['tqty']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;font-weight:600;"><?php echo pfs($sl['amt']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['advance']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['our']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['shipperamount']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['credit']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;font-weight:600;color:#065f46;"><?php echo pfs($sl['balance']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['cbm']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['weight']); ?></td>
                    <td style="padding:6px 4px;text-align:right;font-size:11px;"><?php echo pfs($sl['cry']); ?></td>
                </tr>
                <?php endforeach; ?>
                <tr style="background:#f1f5f9;border-top:2px solid #e2e8f0;font-weight:700;">
                    <td colspan="5" style="padding:7px 8px;text-align:right;font-size:11px;color:#64748b;">Total</td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stCtn); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stTqty); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stAmt); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stAdv); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stOur); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stShp); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stCr); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;color:#065f46;"><?php echo pfs($stBal); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stCbm); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stWt); ?></td>
                    <td style="padding:7px 4px;text-align:right;font-size:11.5px;"><?php echo pfs($stCry); ?></td>
                </tr>
                <?php else: ?>
                <tr><td colspan="16" style="text-align:center;padding:16px;color:#94a3b8;font-size:12px;">Select a Container No. to see Loading Plan summary.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>

        <!-- ── Packing List Grid ───────────────────────────────────────────── -->
        <div style="margin-top:20px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;flex-wrap:wrap;gap:8px;">
                <div style="font-size:13px;font-weight:700;color:#1e293b;"><i class="fa fa-boxes-stacked" style="color:#7c3aed;margin-right:8px;"></i>Packing List</div>
                <?php if ($qvouch > 0): ?>
                <a href="despatch_packlist_print.php?vouchno=<?php echo $qvouch; ?>" target="_blank"
                   style="padding:6px 14px;background:#4a5759;color:#fff;border-radius:7px;font-size:12px;font-weight:600;text-decoration:none;">
                    <i class="fa fa-print"></i> Print Packing List
                </a>
                <?php endif; ?>
            </div>
            <div class="grid-wrap" id="plGridWrap">
            <table style="width:100%;border-collapse:collapse;font-size:11.5px;" id="plGrid">
                <thead>
                    <tr>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:26px;text-align:center;font-size:10px;text-transform:uppercase;">#</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:26px;"></th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:56px;text-align:left;font-size:10px;text-transform:uppercase;">Ship Mark</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;text-align:left;font-size:10px;text-transform:uppercase;">Description</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:56px;text-align:center;font-size:10px;text-transform:uppercase;">Image</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:50px;text-align:right;font-size:10px;text-transform:uppercase;">CTN</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:60px;text-align:right;font-size:10px;text-transform:uppercase;">QTY</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:65px;text-align:right;font-size:10px;text-transform:uppercase;">T.QTY</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:55px;text-align:right;font-size:10px;text-transform:uppercase;">CBM</th>
                        <th style="background:#3730a3;color:#e0e7ff;padding:8px 6px;width:65px;text-align:right;font-size:10px;text-transform:uppercase;">Weight</th>
                    </tr>
                </thead>
                <tbody id="plBody">
                    <?php if (count($plLines) > 0): ?>
                    <?php
                    require_once('includes/bc_image.php');
                    foreach ($plLines as $pi => $pl):
                        $imgSrc = getBcImageSrc($conn, $pl['picfile'] ?? '', (int)($pl['bcvouchno'] ?? 0), $pl['description'] ?? '');
                    ?>
                    <tr data-pi="<?php echo $pi; ?>">
                        <td style="text-align:center;color:#94a3b8;font-size:11px;padding:4px 3px;"><?php echo $pi+1; ?></td>
                        <td style="text-align:center;padding:3px;"><button type="button" class="row-del form" onclick="delPlRow(this)"><i class="fa fa-times"></i></button></td>
                        <td style="padding:3px;font-size:11px;"><?php echo htmlspecialchars($pl['shipmark']); ?></td>
                        <td style="padding:3px;font-size:11px;"><?php echo htmlspecialchars($pl['description']); ?></td>
                        <td style="padding:3px;text-align:center;">
                            <?php if ($imgSrc): ?><img src="<?php echo $imgSrc; ?>" style="width:40px;height:40px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;"><?php endif; ?>
                        </td>
                        <td style="padding:3px;text-align:right;font-size:11px;"><?php echo $pl['ctn'] ? $pl['ctn'] : ''; ?></td>
                        <td style="padding:3px;text-align:right;font-size:11px;"><?php echo $pl['qty'] ? $pl['qty'] : ''; ?></td>
                        <td style="padding:3px;text-align:right;font-size:11px;"><?php echo $pl['tqty'] ? $pl['tqty'] : ''; ?></td>
                        <td style="padding:3px;text-align:right;font-size:11px;"><?php echo $pl['cbm'] ? $pl['cbm'] : ''; ?></td>
                        <td style="padding:3px;text-align:right;font-size:11px;"><?php echo $pl['weight'] ? $pl['weight'] : ''; ?></td>
                        <!-- hidden inputs to POST -->
                        <input type="hidden" name="pl_bcvouchno[]"  value="<?php echo (int)$pl['bcvouchno']; ?>">
                        <input type="hidden" name="pl_shipmark[]"   value="<?php echo htmlspecialchars($pl['shipmark']); ?>">
                        <input type="hidden" name="pl_description[]"value="<?php echo htmlspecialchars($pl['description']); ?>">
                        <input type="hidden" name="pl_picfile[]"    value="<?php echo htmlspecialchars($pl['picfile']); ?>">
                        <input type="hidden" name="pl_ctn[]"        value="<?php echo $pl['ctn']; ?>">
                        <input type="hidden" name="pl_qty[]"        value="<?php echo $pl['qty']; ?>">
                        <input type="hidden" name="pl_tqty[]"       value="<?php echo $pl['tqty']; ?>">
                        <input type="hidden" name="pl_cbm[]"        value="<?php echo $pl['cbm']; ?>">
                        <input type="hidden" name="pl_weight[]"     value="<?php echo $pl['weight']; ?>">
                    </tr>
                    <?php endforeach; ?>
                    <?php else: ?>
                    <tr id="plEmpty"><td colspan="10" style="text-align:center;padding:16px;color:#94a3b8;font-size:12px;">Pick a Container No. to auto-fill the packing list.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>

        <?php if ($qvouch > 0 && (fv($get,'adduser') != '' || fv($get,'edituser') != '')): ?>
        <div class="audit-info">
            <?php if (fv($get,'adduser') != ''): ?>
            <span><i class="fa fa-plus-circle"></i> Added by <b><?php echo fv($get,'adduser'); ?></b> on <?php echo fv($get,'adddate'); ?> <?php echo fv($get,'addtime'); ?></span>
            <?php endif; ?>
            <?php if (fv($get,'edituser') != ''): ?>
            <span><i class="fa fa-pen"></i> Last edited by <b><?php echo fv($get,'edituser'); ?></b> on <?php echo fv($get,'editdate'); ?> <?php echo fv($get,'edittime'); ?></span>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    </div><!-- /sim-body -->

    <div class="btn-bar">

        <button id="hprevious" type="button" class="abtn abtn-prev buttonform"
            style="display:<?php echo $pdisabled; ?>;"
            data-tip="Previous"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $prevvouch; ?>'"
            <?php echo $pdisabled1; ?>>
            <i class="fa fa-chevron-left"></i>
        </button>

        <button id="hnext" type="button" class="abtn abtn-next buttonform"
            style="display:<?php echo $ndisabled; ?>;"
            data-tip="Next"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $nextvouch; ?>'"
            <?php echo $ndisabled1; ?>>
            <i class="fa fa-chevron-right"></i>
        </button>

        <button id="hsearch" type="button" class="abtn abtn-search buttonform"
            style="display:<?php echo $searchdisabled; ?>;"
            data-tip="Search"
            onclick="document.getElementById('searchModal').style.display='flex'">
            <i class="fa fa-search"></i>
        </button>

        <button id="hprint" type="button" class="abtn abtn-print buttonform"
            style="display:<?php echo $printdisabled; ?>;"
            data-tip="Print"
            onclick="window.open('<?php echo $printfile . '?' . $keyfld . '=' . $qvouch; ?>','_blank')">
            <i class="fa fa-print"></i>
        </button>

        <button id="hadd" type="button" class="abtn abtn-add buttonform"
            style="display:<?php echo $adddisabled; ?>;"
            data-tip="Add New"
            onclick="window.location.href='<?php echo $file . '?mode=true'; ?>'">
            <i class="fa fa-plus"></i>
        </button>

        <button id="hedit" type="button" class="abtn abtn-edit buttonform"
            style="display:<?php echo $editdisabled; ?>;"
            data-tip="Edit">
            <i class="fa fa-pencil"></i>
        </button>

        <a id="hdelete" class="abtn abtn-del buttonform"
            style="display:<?php echo $deletedisabled; ?>;"
            data-tip="Delete"
            href="javascript:void(0)"
            onclick="confirmDelete('?delete&<?php echo $keyfld . '=' . $qvouch; ?>')">
            <i class="fa fa-trash"></i>
        </a>

        <button id="hexit" type="button" class="abtn abtn-exit buttonform"
            style="display:<?php echo $exitdisabled; ?>;"
            data-tip="Exit"
            onclick="window.location.href='default.php'">
            <i class="fa fa-power-off"></i>
        </button>

        <button id="ssubmit" type="submit" name="submit"
            value="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            class="abtn abtn-save buttonform"
            data-tip="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            style="display:<?php echo $savedisabled; ?>;">
            <i class="fa fa-check"></i>
            <?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>
        </button>

        <button id="scancel" type="button"
            class="abtn abtn-cancel buttonform"
            data-tip="Cancel"
            style="display:<?php echo $canceldisabled; ?>;"
            onclick="window.location.href='<?php echo $file . '?mode=last'; ?>'">
            <i class="fa fa-times"></i> Cancel
        </button>

    </div>

</div>
</form>

<div id="searchModal"
    style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:9999;
           align-items:flex-start;justify-content:center;padding-top:60px;">
    <div style="background:#fff;border-radius:12px;width:94%;max-width:900px;overflow:hidden;
                box-shadow:0 24px 64px rgba(0,0,0,.3);max-height:85vh;display:flex;flex-direction:column;">

        <div style="padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f1f5f9;">
            <span style="font-size:14px;font-weight:700;color:#1e293b;">
                <i class="fa fa-search" style="color:#7f5539;margin-right:8px;"></i>Search <?php echo $formname; ?>
            </span>
            <button type="button"
                style="background:#f1f5f9;border:none;color:#64748b;width:30px;height:30px;border-radius:6px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;"
                onclick="document.getElementById('searchModal').style.display='none'">&times;</button>
        </div>

        <div style="padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;flex-wrap:wrap;gap:8px;align-items:end;background:#fafbfc;">
            <div style="flex:1;min-width:160px;">
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Customer / Godown / Remarks</label>
                <input type="text" id="srchInput" placeholder="Type to search..."
                    style="width:100%;padding:7px 11px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;box-sizing:border-box;">
            </div>
            <div>
                <button type="button" id="srchGoBtn"
                    style="padding:8px 18px;border-radius:6px;border:none;background:#2563eb;color:#fff;font-size:12.5px;font-weight:600;cursor:pointer;">
                    <i class="fa fa-search"></i> Search
                </button>
            </div>
        </div>

        <div style="overflow:auto;flex:1;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="position:sticky;top:0;background:#f8fafc;">
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Voucher No</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Date</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Customer</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Godown</th>
                        <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Qty</th>
                    </tr>
                </thead>
                <tbody id="srchBody"></tbody>
            </table>
        </div>

        <div style="display:flex;border-top:1px solid #f1f5f9;">
            <button type="button" id="srchPrevBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-right:1px solid #f1f5f9;">
                <i class="fa fa-chevron-left"></i> Previous
            </button>
            <span id="srchPageInfo" style="padding:10px 16px;font-size:12px;color:#64748b;white-space:nowrap;align-self:center;"></span>
            <button type="button" id="srchNextBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-left:1px solid #f1f5f9;">
                Next <i class="fa fa-chevron-right"></i>
            </button>
        </div>

    </div>
</div>

<?php include("includes/linksfoot.php"); ?>

<script>
var availableStock = [];   // [{description, modelno, marka, balance}]
var currentVouchNo = <?php echo (int)$qvouch; ?>;

function loadStock() {
    var godown = $('#godown').val();
    if (!godown) { availableStock = []; updateStockList(); return; }
    $.post('includes/available_stock.php', {
        godown: godown,
        exclvouch: currentVouchNo,
        exclsource: '<?php echo $source; ?>'
    }, function (data) {
        if (data.ok) {
            availableStock = data.stock;
            updateStockList();
            document.querySelectorAll('#dgrid tbody tr').forEach(function (tr) { checkQty(tr.querySelector('.qty-inp')); });
        }
    }, 'json');
}
// before doing it datalist function 
//function updateStockList() {
//    var dl = document.getElementById('stockList');
//    dl.innerHTML = '';
//    availableStock.forEach(function (s) {
//        var opt = document.createElement('option');
//        opt.value = s.description;
//        dl.appendChild(opt);
//    });
//}

function updateStockList() {
    var dl = document.getElementById('productList');

    availableStock.forEach(function (s) {
        if (!$('option[value="' + s.description.replace(/"/g,'\\"') + '"]', dl).length) {
            var opt = document.createElement('option');
            opt.value = s.description;
            dl.appendChild(opt);
        }
    });
}

function findStock(desc) {
    for (var i = 0; i < availableStock.length; i++) {
        if (availableStock[i].description.trim().toLowerCase() === desc.trim().toLowerCase()) return availableStock[i];
    }
    return null;
}


// ── Voucher search modal ─────────────────────────────────────────────────
var srchPage = 1;
var srchPages = 1;

function srchLoad(page) {
    srchPage = page;
    $.post('includes/despatch_search.php', {
        search: $('#srchInput').val(),
        page:   page
    }, function (data) {
        $('#srchBody').html(data.rows);
        srchPage  = data.page;
        srchPages = data.pages;
        $('#srchPageInfo').text('Page ' + srchPage + ' of ' + srchPages + ' (' + data.total + ' records)');
        $('#srchPrevBtn').prop('disabled', srchPage <= 1).css('opacity', srchPage <= 1 ? .5 : 1);
        $('#srchNextBtn').prop('disabled', srchPage >= srchPages).css('opacity', srchPage >= srchPages ? .5 : 1);
    }, 'json');
}

$('#srchGoBtn').on('click', function () { srchLoad(1); });
$('#srchInput').on('keyup', function (e) { if (e.key === 'Enter') srchLoad(1); });
$('#srchPrevBtn').on('click', function () { if (srchPage > 1) srchLoad(srchPage - 1); });
$('#srchNextBtn').on('click', function () { if (srchPage < srchPages) srchLoad(srchPage + 1); });

document.getElementById('searchModal').addEventListener('click', function (e) {
    if (e.target === this) this.style.display = 'none';
});
document.getElementById('hsearch') && document.getElementById('hsearch').addEventListener('click', function () {
    srchLoad(1);
    setTimeout(function () { document.getElementById('srchInput').focus(); }, 60);
});

// ── Container pick → auto-fill packing list + LP summary ─────────────────
function onContainerPick(containerno) {
    if (!containerno) return;
    // Load LP summary
    $.post('includes/lp_summary_pickup.php', { containerno: containerno }, function(data) {
        if (data.html) document.getElementById('lpSummaryBody').innerHTML = data.html;
    }, 'json');
    // Load packing list
    $.post('includes/container_pickup.php', { containerno: containerno }, function(data) {
        if (!data.ok) return;
        var tbody = document.getElementById('plBody');
        tbody.innerHTML = '';

        var emptyRow = document.getElementById('plEmpty');
        if (emptyRow) emptyRow.remove();

        data.rows.forEach(function(r, idx) {
            var tr = document.createElement('tr');
            var imgHtml = r.imgSrc ? '<img src="'+r.imgSrc+'" style="width:40px;height:40px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;">' : '';
            tr.innerHTML =
                '<td style="text-align:center;color:#94a3b8;font-size:11px;padding:4px 3px;">'+(idx+1)+'</td>' +
                '<td style="text-align:center;padding:3px;"><button type="button" class="row-del" onclick="delPlRow(this)"><i class="fa fa-times"></i></button></td>' +
                '<td style="padding:3px;font-size:11px;">'+escHtml(r.shipmark)+'</td>' +
                '<td style="padding:3px;font-size:11px;">'+escHtml(r.description)+'</td>' +
                '<td style="padding:3px;text-align:center;">'+imgHtml+'</td>' +
                '<td style="padding:3px;text-align:right;font-size:11px;">'+(r.ctn||'')+'</td>' +
                '<td style="padding:3px;text-align:right;font-size:11px;">'+(r.qty||'')+'</td>' +
                '<td style="padding:3px;text-align:right;font-size:11px;">'+(r.tqty||'')+'</td>' +
                '<td style="padding:3px;text-align:right;font-size:11px;">'+(r.cbm||'')+'</td>' +
                '<td style="padding:3px;text-align:right;font-size:11px;">'+(r.weight||'')+'</td>';

            // Hidden inputs for POST
            ['bcvouchno','shipmark','description','picfile','ctn','qty','tqty','cbm','weight'].forEach(function(f) {
                var inp = document.createElement('input');
                inp.type = 'hidden'; inp.name = 'pl_'+f+'[]';
                inp.value = r[f] !== undefined ? r[f] : '';
                tr.appendChild(inp);
            });
            tbody.appendChild(tr);
        });
    }, 'json');
}

function delPlRow(btn) {
    btn.closest('tr').remove();
}

function escHtml(s) {
    if (!s) return '';
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>
</body>
</html>
