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

$formname  = 'Loading Plan';
$maindb    = 'loadingplan';
$printfile = 'loadingplan_print.php';
$file      = 'loadingplan.php';
$keyfld    = 'vouchno';

$zdb    = $_SESSION["zdbyear_" . $dbname];
$compcd = $_SESSION["comp_"    . $dbname];
mysqli_select_db($conn, $zdb);

// ── Auto-migration ─────────────────────────────────────────────────────────
$tabChk = mysqli_query($conn, "SHOW TABLES LIKE 'loadingplan'");
if (mysqli_num_rows($tabChk) == 0) {
    mysqli_query($conn, "CREATE TABLE `loadingplan` (
        `vouchno`     int(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `vouchdt`     date         NOT NULL DEFAULT '0000-00-00',
        `containerno` varchar(50)  NOT NULL DEFAULT '',
        `shipper`     int(11)      NOT NULL DEFAULT 0,
        `remarks`     varchar(200) NOT NULL DEFAULT '',
        `totctn`      double       NOT NULL DEFAULT 0,
        `tottqty`     double       NOT NULL DEFAULT 0,
        `totamt`      double       NOT NULL DEFAULT 0,
        `totcbm`      double       NOT NULL DEFAULT 0,
        `totweight`   double       NOT NULL DEFAULT 0,
        `adduser`     varchar(50)  NOT NULL DEFAULT '',
        `adddate`     date         NOT NULL DEFAULT '0000-00-00',
        `addtime`     time         NOT NULL DEFAULT '00:00:00',
        `edituser`    varchar(50)  NOT NULL DEFAULT '',
        `editdate`    date         NOT NULL DEFAULT '0000-00-00',
        `edittime`    time         NOT NULL DEFAULT '00:00:00'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));
} else {
    // Migrate shipper column from varchar to int if needed
    $scol = mysqli_query($conn, "SHOW COLUMNS FROM `loadingplan` LIKE 'shipper'");
    if ($scol) {
        $srow = mysqli_fetch_assoc($scol);
        if ($srow && strpos($srow['Type'], 'varchar') !== false) {
            mysqli_query($conn, "ALTER TABLE `loadingplan` MODIFY COLUMN `shipper` int(11) NOT NULL DEFAULT 0");
        }
    }
}

$tabTrChk = mysqli_query($conn, "SHOW TABLES LIKE 'loadingplantr'");
if (mysqli_num_rows($tabTrChk) == 0) {
    mysqli_query($conn, "CREATE TABLE `loadingplantr` (
        `srl`           int(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `vouchno`       int(11)      NOT NULL DEFAULT 0,
        `supplier`      int(11)      NOT NULL DEFAULT 0,
        `customer`      int(11)      NOT NULL DEFAULT 0,
        `bcvouchno`     int(11)      NOT NULL DEFAULT 0,
        `shipmark`      varchar(100) NOT NULL DEFAULT '',
        `description`   varchar(200) NOT NULL DEFAULT '',
        `ctn`           double       NOT NULL DEFAULT 0,
        `tqty`          double       NOT NULL DEFAULT 0,
        `amt`           double       NOT NULL DEFAULT 0,
        `advance`       double       NOT NULL DEFAULT 0,
        `our`           double       NOT NULL DEFAULT 0,
        `clientpaid`    double       NOT NULL DEFAULT 0,
        `shipperamount` double       NOT NULL DEFAULT 0,
        `credit`        double       NOT NULL DEFAULT 0,
        `balance`       double       NOT NULL DEFAULT 0,
        `cbm`           double       NOT NULL DEFAULT 0,
        `weight`        double       NOT NULL DEFAULT 0,
        `cry`           double       NOT NULL DEFAULT 0,
        INDEX (`vouchno`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));
} else {
    // Migrate old columns to new names/types
    $migrations = [
        'supplier'      => "int(11) NOT NULL DEFAULT 0",
        'customer'      => "int(11) NOT NULL DEFAULT 0",
        'bcvouchno'     => "int(11) NOT NULL DEFAULT 0",
        'advance'       => "double NOT NULL DEFAULT 0",
        'clientpaid'    => "double NOT NULL DEFAULT 0",
        'shipperamount' => "double NOT NULL DEFAULT 0",
        'cry'           => "double NOT NULL DEFAULT 0",
    ];
    foreach ($migrations as $col => $def) {
        $chk = mysqli_query($conn, "SHOW COLUMNS FROM `loadingplantr` LIKE '$col'");
        if ($chk && mysqli_num_rows($chk) == 0) {
            mysqli_query($conn, "ALTER TABLE `loadingplantr` ADD COLUMN `$col` $def");
        }
    }
}

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

$audituser = audituser();

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;
}

// ── Lookup lists ──────────────────────────────────────────────────────────
$agentList    = acc_list($conn, '040');
$supplierList = acc_list($conn, '009');
$customerList = acc_list($conn, '010');

// ── POST: Save / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vd = isset($_POST["vouchdt"]) ? trim($_POST["vouchdt"]) : '';
    if ($vd == '' || $vd == '0000-00-00') { browse("Date Cannot Be Empty"); header("refresh:1; url=$file?mode=last"); exit; }

    $containerno = mysqli_real_escape_string($conn, trim($_POST["containerno"] ?? ''));
    $shipper     = (int)($_POST["shipper"] ?? 0);
    $remarks     = mysqli_real_escape_string($conn, trim($_POST["remarks"]     ?? ''));

    $supplierA   = $_POST['supplier']      ?? [];
    $customerA   = $_POST['customer']      ?? [];
    $bcvouchnoA  = $_POST['bcvouchno']     ?? [];
    $markA       = $_POST['shipmark']      ?? [];
    $descA       = $_POST['description']   ?? [];
    $ctnA        = $_POST['ctn']           ?? [];
    $tqtyA       = $_POST['tqty']          ?? [];
    $amtA        = $_POST['amt']           ?? [];
    $advanceA    = $_POST['advance']       ?? [];
    $ourA        = $_POST['our']           ?? [];
    $shpamtA     = $_POST['shipperamount'] ?? [];
    $creditA     = $_POST['credit']        ?? [];
    $balanceA    = $_POST['balance']       ?? [];
    $cbmA        = $_POST['cbm']           ?? [];
    $weightA     = $_POST['weight']        ?? [];
    $cryA        = $_POST['cry']           ?? [];

    $lines = [];
    $totctn = $tottqty = $totamt = $totcbm = $totweight = 0;

    foreach ($descA as $i => $desc) {
        $desc = trim($desc);
        $ctn  = (float)($ctnA[$i]  ?? 0);
        $tqty = (float)($tqtyA[$i] ?? 0);
        if ($desc == '' && $ctn == 0 && $tqty == 0) continue;
        $lines[] = [
            'supplier'      => (int)($supplierA[$i]   ?? 0),
            'customer'      => (int)($customerA[$i]   ?? 0),
            'bcvouchno'     => (int)($bcvouchnoA[$i]  ?? 0),
            'shipmark'      => trim($markA[$i]         ?? ''),
            'description'   => $desc,
            'ctn'           => $ctn,
            'tqty'          => $tqty,
            'amt'           => (float)($amtA[$i]        ?? 0),
            'advance'       => (float)($advanceA[$i]    ?? 0),
            'our'           => (float)($ourA[$i]        ?? 0),
            'shipperamount' => (float)($shpamtA[$i]     ?? 0),
            'credit'        => (float)($creditA[$i]     ?? 0),
            'balance'       => (float)($balanceA[$i]    ?? 0),
            'cbm'           => (float)($cbmA[$i]        ?? 0),
            'weight'        => (float)($weightA[$i]     ?? 0),
            'cry'           => (float)($cryA[$i]        ?? 0),
        ];
        $totctn    += $ctn;
        $tottqty   += $tqty;
        $totamt    += (float)($amtA[$i] ?? 0);
        $totcbm    += (float)($cbmA[$i] ?? 0);
        $totweight += (float)($weightA[$i] ?? 0);
    }

    if ($addflag == 1) {
        mysqli_query($conn, "INSERT INTO `$maindb`
            (`vouchno`,`vouchdt`,`containerno`,`shipper`,`remarks`,
             `totctn`,`tottqty`,`totamt`,`totcbm`,`totweight`,
             `adduser`,`adddate`,`addtime`)
            VALUES
            ('$qvouch','$vd','$containerno','$shipper','$remarks',
             '$totctn','$tottqty','$totamt','$totcbm','$totweight',
             '$audituser',CURDATE(),CURTIME())")
        or die(mysqli_error($conn));
    } else {
        mysqli_query($conn, "UPDATE `$maindb` SET
            `vouchdt`='$vd', `containerno`='$containerno', `shipper`='$shipper', `remarks`='$remarks',
            `totctn`='$totctn', `tottqty`='$tottqty', `totamt`='$totamt',
            `totcbm`='$totcbm', `totweight`='$totweight',
            `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
            WHERE `$keyfld`='$qvouch'")
        or die(mysqli_error($conn));
    }

    mysqli_query($conn, "DELETE FROM `loadingplantr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    foreach ($lines as $ln) {
        $sm = mysqli_real_escape_string($conn, $ln['shipmark']);
        $d  = mysqli_real_escape_string($conn, $ln['description']);
        mysqli_query($conn, "INSERT INTO `loadingplantr`
            (`vouchno`,`supplier`,`customer`,`bcvouchno`,`shipmark`,`description`,
             `ctn`,`tqty`,`amt`,`advance`,`our`,`shipperamount`,`credit`,`balance`,`cbm`,`weight`,`cry`)
            VALUES ('$qvouch','{$ln['supplier']}','{$ln['customer']}','{$ln['bcvouchno']}','$sm','$d',
             '{$ln['ctn']}','{$ln['tqty']}','{$ln['amt']}','{$ln['advance']}','{$ln['our']}',
             '{$ln['shipperamount']}','{$ln['credit']}','{$ln['balance']}',
             '{$ln['cbm']}','{$ln['weight']}','{$ln['cry']}')")
        or die(mysqli_error($conn));
    }

    // ── Posting to actran ─────────────────────────────────────────────────
    $lpsource = 'LP';
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$lpsource' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));

    // Look up shipper name for narration
    $shipperName = '';
    if ($shipper > 0) {
        $snRes = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$shipper'");
        if ($snRes) { $snRow = mysqli_fetch_assoc($snRes); $shipperName = $snRow['name'] ?? ''; }
    }

    $trnno = 1;
    foreach ($lines as $ln) {
        $sup  = (int)$ln['supplier'];
        $cust = (int)$ln['customer'];
        $amt  = (float)$ln['amt'];
        $adv  = (float)$ln['advance'];
        $our  = (float)$ln['our'];
        $shpa = (float)$ln['shipperamount'];

        $supGrp  = '009';
        $custGrp = '010';

        // Look up names for narration
        $custName = '';
        $supName  = '';
        if ($cust > 0) {
            $cnRes = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$cust'");
            if ($cnRes) { $cnRow = mysqli_fetch_assoc($cnRes); $custName = mysqli_real_escape_string($conn, $cnRow['name'] ?? ''); }
        }
        if ($sup > 0) {
            $snRes2 = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$sup'");
            if ($snRes2) { $snRow2 = mysqli_fetch_assoc($snRes2); $supName = mysqli_real_escape_string($conn, $snRow2['name'] ?? ''); }
        }
        $shipperEsc = mysqli_real_escape_string($conn, $shipperName);
        $ourUser    = mysqli_real_escape_string($conn, $audituser);

        // ── AMT: credit supplier — narration says who it's from (customer) ──
        if ($amt != 0 && $sup > 0) {
            $cr   = $amt;
            $narr = mysqli_real_escape_string($conn, 'Paid by ' . ($custName ?: 'Customer'));
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$sup','$supGrp','$cr','1','$cr','','$cr','$narr')")
            or die(mysqli_error($conn));
        }

        // ── Client Adv: debit supplier (paid by customer), credit customer ──
        if ($adv != 0 && $sup > 0 && $cust > 0) {
            $dr      = $adv * -1;
            $narrSup = mysqli_real_escape_string($conn, 'Client Adv. paid by ' . ($custName ?: 'Customer'));
            $narrCus = mysqli_real_escape_string($conn, 'Client Adv. to ' . ($supName ?: 'Supplier'));
            // Debit supplier
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$sup','$supGrp','$dr','1','$dr','','$dr','$narrSup')")
            or die(mysqli_error($conn));
            // Credit customer
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$cust','$custGrp','$adv','1','$adv','','$adv','$narrCus')")
            or die(mysqli_error($conn));
        }

        // ── Shipper Amt: debit supplier, credit shipper ───────────────────
        if ($shpa != 0 && $sup > 0 && $shipper > 0) {
            $dr      = $shpa * -1;
            $narrSup = mysqli_real_escape_string($conn, 'Shipper Amt. paid to ' . $shipperName);
            $narrShp = mysqli_real_escape_string($conn, 'Received from ' . ($supName ?: 'Supplier'));
            // Debit supplier
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$sup','$supGrp','$dr','1','$dr','','$dr','$narrSup')")
            or die(mysqli_error($conn));
            // Credit shipper
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$shipper','040','$shpa','1','$shpa','','$shpa','$narrShp')")
            or die(mysqli_error($conn));
        }

        // ── OUR: debit supplier — paid by logged-in user's company ───────
        if ($our != 0 && $sup > 0) {
            $dr   = $our * -1;
            $narr = mysqli_real_escape_string($conn, 'Paid by ' . $audituser);
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                VALUES ('$vd','$vd','$qvouch','$lpsource','" . str_pad($trnno++, 3, '0', STR_PAD_LEFT) . "','$sup','$supGrp','$dr','1','$dr','','$dr','$narr')")
            or die(mysqli_error($conn));
        }
    }

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

// ── DELETE ─────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    mysqli_query($conn, "DELETE FROM `loadingplantr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='LP' 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($a,$k,$d='') { return isset($a[$k]) ? htmlspecialchars($a[$k]) : $d; }
function fvn($a,$k)      { $v=(float)($a[$k]??0); return $v?$v:''; }

// ── Fetch record ───────────────────────────────────────────────────────────
$get   = [];
$lines = [];
if ($qvouch > 0 && $addflag != 1) {
    $res = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    $get = mysqli_fetch_assoc($res) ?: [];
    $tr  = mysqli_query($conn, "SELECT * FROM `loadingplantr` WHERE `vouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_assoc($tr)) { $lines[] = $r; }
}
if (count($lines) == 0) {
    $lines[] = ['supplier'=>0,'customer'=>0,'bcvouchno'=>0,'shipmark'=>'','description'=>'',
                'ctn'=>'','tqty'=>'','amt'=>'','advance'=>'','our'=>'',
                'shipperamount'=>'','credit'=>'','balance'=>'','cbm'=>'','weight'=>'','cry'=>''];
}

$vouchdt_val = (!empty($get['vouchdt']) && $get['vouchdt'] != '0000-00-00') ? $get['vouchdt'] : '';

// Build supplier/customer/agent options as JSON for JS dynamic selects
$supplierOpts = [];
foreach ($supplierList as $r) { $supplierOpts[] = ['v'=>(int)$r['accode'], 'n'=>$r['name']]; }
$customerOpts = [];
foreach ($customerList as $r) { $customerOpts[] = ['v'=>(int)$r['accode'], 'n'=>$r['name']]; }

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; flex-wrap:wrap; gap:8px; }
    .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:16px 20px; }
    .fr-grid { display:flex; flex-wrap:wrap; gap:0 20px; }
    .fl { flex:1; min-width:220px; display:flex; flex-direction:column; margin-bottom:11px; }
    .lbl { font-size:11.5px; font-weight:600; color:#64748b; margin-bottom:4px; display:flex; align-items:center; justify-content:space-between; }
    .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; 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.required-star { border-left:3px solid #3b82f6; }
    .new-btn { font-size:10px; font-weight:700; background:#2563eb; color:#fff; border:none; border-radius:4px; padding:2px 7px; cursor:pointer; line-height:18px; }
    .new-btn.supplier-col { background:#7f5539; }
    .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); }

    .sum-strip { margin:14px 0 10px; padding:14px 16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; }
    .sum-strip-label { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; margin-bottom:10px; }
    .sum-grid { display:grid; grid-template-columns:repeat(5,1fr); gap:8px; }
    .sum-field label { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
    .sum-field input { width:100%; box-sizing:border-box; padding:6px 8px; font-size:12.5px; font-weight:700; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#1e293b; text-align:right; font-family:inherit; }

    .grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; margin-top:4px; }
    table.dgrid { width:100%; border-collapse:collapse; font-size:11.5px; table-layout:fixed; }
    table.dgrid th { background:#1e293b; color:#e2e8f0; font-weight:700; font-size:9.5px; text-transform:uppercase; letter-spacing:.04em; padding:7px 3px; border-bottom:2px solid #334155; text-align:center; white-space:nowrap; overflow:hidden; }
    table.dgrid th.num { text-align:right; }
    table.dgrid td { padding:3px 2px; border-bottom:1px solid #f1f5f9; overflow:hidden; }
    table.dgrid tbody tr:hover { background:#f8faff; }
    table.dgrid tfoot td { font-weight:700; background:#f1f5f9; border-top:2px solid #e2e8f0; text-align:right; font-size:11px; padding:5px 4px; color:#1e293b; overflow:hidden; }
    table.dgrid input { width:100%; padding:3px 4px; font-size:11px; border:1px solid #e2e8f0; border-radius:3px; background:#fff; font-family:inherit; box-sizing:border-box; color:#1e293b; }
    table.dgrid input:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
    table.dgrid input[readonly] { background:#f8fafc; color:#64748b; border-color:#f1f5f9; }
    table.dgrid input.numfld { text-align:right; }
    table.dgrid td.desc-td { max-width:90px; }
    table.dgrid td.desc-td input { overflow:hidden; text-overflow:ellipsis; }

    /* Select2 inside dgrid cells - compact */
    table.dgrid td .select2-container { width:100% !important; }
    table.dgrid td .select2-container .select2-selection--single {
        height:26px; border:1px solid #e2e8f0; border-radius:3px; background:#fff;
        display:flex; align-items:center;
    }
    table.dgrid td .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height:normal; font-size:10.5px; color:#1e293b; padding-left:5px; padding-right:16px;
        overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
    }
    table.dgrid td .select2-container--default .select2-selection--single .select2-selection__arrow {
        height:24px; right:1px; width:12px;
    }
    table.dgrid td .select2-container--default.select2-container--focus .select2-selection--single,
    table.dgrid td .select2-container--default.select2-container--open .select2-selection--single {
        border-color:#3b82f6;
    }
    .bc-pick-btn:disabled { opacity:.35; pointer-events:none; }
    .row-del { background:#fee2e2; border:none; border-radius:4px; color:#dc2626; cursor:pointer; padding:4px 8px; font-size:12px; }
    .row-del:hover { background:#fecaca; }
    .row-del:disabled { opacity:.35; pointer-events:none; }
    .add-row-btn { display:inline-flex; align-items:center; gap:6px; margin-top:10px; padding:8px 18px; background:#16a34a; color:#fff; border:none; border-radius:8px; font-size:12.5px; font-weight:600; cursor:pointer; }
    .add-row-btn:disabled { opacity:.35; pointer-events:none; }
    .audit-info { margin-top:10px; font-size:11px; color:#94a3b8; display:flex; gap:16px; flex-wrap:wrap; }

    .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[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; }

    @media(max-width:768px) {
        .sim-body { padding:12px 14px; }
        .fr-grid { flex-direction:column; gap:0; }
        .fl { min-width:100%; }
        .sum-grid { grid-template-columns:repeat(3,1fr); }
        .btn-bar { gap:5px; padding:10px 8px; flex-wrap:wrap; }
    }
</style>
</head>

<body>
<form action="" method="POST">
<input type="hidden" name="submit" value="1">
<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-ship" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <span class="sim-badge">Voucher No: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
    </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($vouchdt_val); ?>">
            </div>
            <div class="fl">
                <span class="lbl">Container No. <span style="color:#ef4444;">*</span></span>
                <input type="text" name="containerno" class="finp form required-star" maxlength="50"
                    value="<?php echo fv($get,'containerno'); ?>">
            </div>
            <div class="fl">
                <span class="lbl">
                    <span>Shipper (Agent)</span>
                    <button type="button" class="new-btn form" onclick="openQuickCreate('agent')">+ New</button>
                </span>
                <select name="shipper" id="shipper" class="finp form select2" style="width:100%;">
                    <option value="">-- Select Agent --</option>
                    <?php foreach ($agentList as $a): ?>
                    <option value="<?php echo (int)$a['accode']; ?>" <?php echo ((int)fv($get,'shipper',0) == $a['accode']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($a['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Remarks</span>
                <input type="text" name="remarks" class="finp form" maxlength="200" value="<?php echo fv($get,'remarks'); ?>">
            </div>
        </div>

        <!-- Summary strip -->
        <div class="sum-strip">
            <div class="sum-strip-label"><i class="fa fa-layer-group" style="margin-right:5px;color:#6366f1;"></i>Summary</div>
            <div class="sum-grid">
                <?php foreach ([['sum_ctn','CTN'],['sum_tqty','T.QTY'],['sum_amt','AMT'],['sum_cbm','CBM'],['sum_weight','Weight']] as $sf): ?>
                <div class="sum-field">
                    <label><?php echo $sf[1]; ?></label>
                    <input type="text" id="<?php echo $sf[0]; ?>" readonly tabindex="-1">
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Detail grid -->
        <div class="grid-wrap">
        <table class="dgrid" id="dgrid">
            <thead>
                <tr>
                    <th style="width:24px;">#</th>
                    <th style="width:22px;"></th>
                    <th style="width:90px;text-align:left;">Supplier</th>
                    <th style="width:90px;text-align:left;">Customer</th>
                    <th style="width:55px;text-align:left;">Ship Mk</th>
                    <th style="width:90px;text-align:left;">Description</th>
                    <th class="num" style="width:44px;">CTN</th>
                    <th class="num" style="width:52px;">T.QTY</th>
                    <th class="num" style="width:68px;">AMT</th>
                    <th class="num" style="width:68px;">Cli.Adv</th>
                    <th class="num" style="width:55px;">OUR</th>
                    <th class="num" style="width:68px;">Shp.Amt</th>
                    <th class="num" style="width:55px;">CREDIT</th>
                    <th class="num" style="width:62px;">BALANCE</th>
                    <th class="num" style="width:46px;">CBM</th>
                    <th class="num" style="width:58px;">WEIGHT</th>
                    <th class="num" style="width:40px;">CRY</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lines as $i => $ln): ?>
                <tr>
                    <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;"></td>
                    <td><button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button></td>
                    <td>
                        <select name="supplier[]" class="form supplier-sel" onchange="recalc()">
                            <option value="">--</option>
                            <?php foreach ($supplierList as $s): ?>
                            <option value="<?php echo (int)$s['accode']; ?>" <?php echo ((int)($ln['supplier'] ?? 0) == $s['accode']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td>
                        <select name="customer[]" class="form customer-sel" onchange="recalc()">
                            <option value="">--</option>
                            <?php foreach ($customerList as $c): ?>
                            <option value="<?php echo (int)$c['accode']; ?>" <?php echo ((int)($ln['customer'] ?? 0) == $c['accode']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input type="text"   name="shipmark[]"      class="form"   value="<?php echo fv($ln,'shipmark'); ?>"></td>
                    <td class="desc-td"><input type="text"   name="description[]"   class="form"   value="<?php echo fv($ln,'description'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="ctn[]"           class="numfld form" value="<?php echo fvn($ln,'ctn'); ?>"           oninput="recalc()"></td>
                    <td><input type="number" step="any" name="tqty[]"          class="numfld form" value="<?php echo fvn($ln,'tqty'); ?>"          oninput="recalc()"></td>
                    <td><input type="number" step="any" name="amt[]"           class="numfld form" value="<?php echo fvn($ln,'amt'); ?>"           oninput="recalcBalance(this)"></td>
                    <td><input type="number" step="any" name="advance[]"       class="numfld form" value="<?php echo fvn($ln,'advance'); ?>"       readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="our[]"           class="numfld form" value="<?php echo fvn($ln,'our'); ?>"           oninput="recalcBalance(this)"></td>
                    <td><input type="number" step="any" name="shipperamount[]" class="numfld form" value="<?php echo fvn($ln,'shipperamount'); ?>" oninput="recalcBalance(this)"></td>
                    <td><input type="number" step="any" name="credit[]"        class="numfld form" value="<?php echo fvn($ln,'credit'); ?>"        oninput="recalcBalance(this)"></td>
                    <td><input type="number" step="any" name="balance[]"       class="numfld form" value="<?php echo fvn($ln,'balance'); ?>"       readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="cbm[]"           class="numfld form" value="<?php echo fvn($ln,'cbm'); ?>"           oninput="recalc()"></td>
                    <td><input type="number" step="any" name="weight[]"        class="numfld form" value="<?php echo fvn($ln,'weight'); ?>"        oninput="recalc()"></td>
                    <td><input type="number" step="any" name="cry[]"           class="numfld form" value="<?php echo fvn($ln,'cry'); ?>"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="7" style="text-align:right;font-size:10px;color:#64748b;">Total</td>
                    <td id="t_ctn"></td><td id="t_tqty"></td><td id="t_amt"></td>
                    <td id="t_advance"></td><td id="t_our"></td>
                    <td id="t_shipperamount"></td><td id="t_credit"></td><td id="t_balance"></td>
                    <td id="t_cbm"></td><td id="t_weight"></td><td id="t_cry"></td>
                </tr>
            </tfoot>
        </table>
        </div>

        <button type="button" class="add-row-btn form" onclick="addRow()"><i class="fa fa-plus"></i> Add Row</button>

        <?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'); ?></span><?php endif; ?>
            <?php if (fv($get,'edituser') != ''): ?><span><i class="fa fa-pencil"></i> Edited by <b><?php echo fv($get,'edituser'); ?></b> on <?php echo fv($get,'editdate'); ?></span><?php endif; ?>
        </div>
        <?php endif; ?>

    </div>

    <div class="btn-bar">
        <button id="hprevious" type="button" class="abtn abtn-prev buttonform" data-tip="Previous" style="display:<?php echo $pdisabled; ?>;" <?php echo $pdisabled1; ?> onclick="window.location.href='<?php echo $file.'?mode=edit&'.$keyfld.'='.$prevvouch; ?>'"><i class="fa fa-chevron-left"></i></button>
        <button id="hnext"     type="button" class="abtn abtn-next buttonform" data-tip="Next"     style="display:<?php echo $ndisabled; ?>;" <?php echo $ndisabled1; ?> onclick="window.location.href='<?php echo $file.'?mode=edit&'.$keyfld.'='.$nextvouch; ?>'"><i class="fa fa-chevron-right"></i></button>
        <button id="hsearch"   type="button" class="abtn abtn-search buttonform" data-tip="Search" style="display:<?php echo $searchdisabled; ?>;" onclick="document.getElementById('searchModal').style.display='flex'"><i class="fa fa-search"></i></button>
        <button id="hprint"    type="button" class="abtn abtn-print buttonform" data-tip="Print"   style="display:<?php echo $printdisabled; ?>;" 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"   data-tip="Add New" style="display:<?php echo $adddisabled; ?>;"   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"  data-tip="Edit"    style="display:<?php echo $editdisabled; ?>;"><i class="fa fa-pencil"></i></button>
        <a      id="hdelete"   class="abtn abtn-del buttonform"  data-tip="Delete"                 style="display:<?php echo $deletedisabled; ?>;" 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"  data-tip="Exit"    style="display:<?php echo $exitdisabled; ?>;"   onclick="window.location.href='default.php'"><i class="fa fa-power-off"></i></button>
        <button id="ssubmit"   type="submit" class="abtn abtn-save buttonform"  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" 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>

<!-- Voucher search modal -->
<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:700px;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;" onclick="document.getElementById('searchModal').style.display='none'">&times;</button>
        </div>
        <div style="padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;gap:8px;background:#fafbfc;">
            <input type="text" id="srchInput" placeholder="Container No / Shipper..." style="flex:1;padding:7px 11px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;">
            <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 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;font-size:11.5px;">Voucher No</th>
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Date</th>
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Container No.</th>
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Shipper</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;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;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>

<!-- Quick create modal (agent/supplier) -->
<div id="quickCreateModal" style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:10000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;width:92%;max-width:380px;overflow:hidden;box-shadow:0 24px 64px rgba(0,0,0,.3);">
        <div style="padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f1f5f9;">
            <span id="qcTitle" style="font-size:14px;font-weight:700;color:#1e293b;"></span>
            <button type="button" onclick="closeQuickCreate()" style="background:#f1f5f9;border:none;color:#64748b;width:30px;height:30px;border-radius:6px;cursor:pointer;font-size:16px;">&times;</button>
        </div>
        <div style="padding:20px 18px;display:flex;flex-direction:column;gap:14px;">
            <div>
                <label style="display:block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;margin-bottom:5px;">Name <span style="color:#ef4444;">*</span></label>
                <input type="text" id="qcName" placeholder="Enter name" style="width:100%;box-sizing:border-box;padding:8px 12px;border:1px solid #e2e8f0;border-radius:7px;font-size:13px;outline:none;font-family:inherit;" onkeydown="if(event.key==='Enter')document.getElementById('qcMobile').focus()">
            </div>
            <div>
                <label style="display:block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;margin-bottom:5px;">Mobile</label>
                <input type="text" id="qcMobile" placeholder="Enter mobile" style="width:100%;box-sizing:border-box;padding:8px 12px;border:1px solid #e2e8f0;border-radius:7px;font-size:13px;outline:none;font-family:inherit;" onkeydown="if(event.key==='Enter')saveQuickCreate()">
            </div>
            <div id="qcError" style="display:none;color:#dc2626;font-size:12px;background:#fee2e2;padding:7px 10px;border-radius:6px;"></div>
        </div>
        <div style="padding:14px 18px;border-top:1px solid #f1f5f9;display:flex;gap:8px;justify-content:flex-end;">
            <button type="button" onclick="closeQuickCreate()" style="padding:8px 18px;border:1px solid #e2e8f0;border-radius:7px;background:#fff;color:#64748b;font-size:13px;font-weight:600;cursor:pointer;">Cancel</button>
            <button type="button" id="qcSaveBtn" onclick="saveQuickCreate()" style="padding:8px 20px;border:none;border-radius:7px;background:#2563eb;color:#fff;font-size:13px;font-weight:600;cursor:pointer;"><i class="fa fa-check"></i> Save</button>
        </div>
    </div>
</div>

<!-- Row template -->
<table style="display:none;"><tbody id="rowTemplate">
<tr>
    <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;"></td>
    <td><button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button></td>
    <td>
        <select name="supplier[]" class="form supplier-sel" onchange="recalc()">
            <option value="">--</option>
            <?php foreach ($supplierList as $s): ?>
            <option value="<?php echo (int)$s['accode']; ?>"><?php echo htmlspecialchars($s['name']); ?></option>
            <?php endforeach; ?>
        </select>
    </td>
    <td>
        <select name="customer[]" class="form customer-sel" onchange="recalc()">
            <option value="">--</option>
            <?php foreach ($customerList as $c): ?>
            <option value="<?php echo (int)$c['accode']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
            <?php endforeach; ?>
        </select>
    </td>
    <td><input type="text"   name="shipmark[]"      class="form"></td>
    <td class="desc-td"><input type="text"   name="description[]"   class="form" oninput="recalc()"></td>
    <td><input type="number" step="any" name="ctn[]"           class="numfld form" oninput="recalc()"></td>
    <td><input type="number" step="any" name="tqty[]"          class="numfld form" oninput="recalc()"></td>
    <td><input type="number" step="any" name="amt[]"           class="numfld form" oninput="recalcBalance(this)"></td>
    <td><input type="number" step="any" name="advance[]"       class="numfld form" readonly tabindex="-1"></td>
    <td><input type="number" step="any" name="our[]"           class="numfld form" oninput="recalcBalance(this)"></td>
    <td><input type="number" step="any" name="shipperamount[]" class="numfld form" oninput="recalcBalance(this)"></td>
    <td><input type="number" step="any" name="credit[]"        class="numfld form" oninput="recalcBalance(this)"></td>
    <td><input type="number" step="any" name="balance[]"       class="numfld form" readonly tabindex="-1"></td>
    <td><input type="number" step="any" name="cbm[]"           class="numfld form" oninput="recalc()"></td>
    <td><input type="number" step="any" name="weight[]"        class="numfld form" oninput="recalc()"></td>
    <td><input type="number" step="any" name="cry[]"           class="numfld form"></td>
</tr>
</tbody></table>

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

<script>
var SUPPLIER_OPTS = <?php echo json_encode($supplierOpts); ?>;
var CUSTOMER_OPTS = <?php echo json_encode($customerOpts); ?>;

function initRowSelects(tr) {
    $(tr).find('select.supplier-sel, select.customer-sel').each(function() {
        if (!$(this).data('select2')) {
            $(this).select2({
                dropdownAutoWidth: true,
                width: '100%',
                placeholder: '--',
                allowClear: false,
            });
        }
        // Match disabled state to current form state
        var isEditable = !document.getElementById('vouchdt').disabled;
        $(this).prop('disabled', !isEditable).trigger('change.select2');
    });
}

function addRow() {
    var tpl = document.getElementById('rowTemplate').innerHTML;
    var tbody = document.querySelector('#dgrid tbody');
    var tr = document.createElement('tr');
    tr.innerHTML = tpl;
    tbody.appendChild(tr);
    initRowSelects(tr);
    renumber();
}
function delRow(btn) {
    var tbody = document.querySelector('#dgrid tbody');
    if (tbody.rows.length > 1) { btn.closest('tr').remove(); recalc(); }
}
function renumber() {
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr, i) {
        var c = tr.querySelector('.srno'); if (c) c.textContent = i + 1;
    });
}

// Balance = amt - advance - our - clientpaid - shipperamount - credit
function recalcBalance(inp) {
    var tr = inp.closest('tr');
    function v(name) {
        var el = tr.querySelector('[name="' + name + '[]"]');
        return el && el.value !== '' ? parseFloat(el.value) : 0;
    }
    var bal = v('amt') - v('advance') - v('our') - v('shipperamount') - v('credit');
    var balInp = tr.querySelector('input[name="balance[]"]');
    if (balInp) balInp.value = bal ? bal.toFixed(2) : '';
    recalc();
}

function recalc() {
    var cols = ['ctn','tqty','amt','advance','our','shipperamount','credit','balance','cbm','weight','cry'];
    var totals = {};
    cols.forEach(function(c) { totals[c] = 0; });
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
        cols.forEach(function(c) {
            var inp = tr.querySelector('input[name="' + c + '[]"]');
            var v = inp && inp.value !== '' ? parseFloat(inp.value) : 0;
            if (!isNaN(v)) totals[c] += v;
        });
    });
    cols.forEach(function(c) {
        var el = document.getElementById('t_' + c);
        if (el) el.textContent = totals[c] ? totals[c].toFixed(2) : '';
    });
    var fmtS = function(v) { return v == 0 ? '' : Number(v.toFixed(3)).toString(); };
    document.getElementById('sum_ctn').value    = fmtS(totals.ctn);
    document.getElementById('sum_tqty').value   = fmtS(totals.tqty);
    document.getElementById('sum_amt').value    = fmtS(totals.amt);
    document.getElementById('sum_cbm').value    = fmtS(totals.cbm);
    document.getElementById('sum_weight').value = fmtS(totals.weight);
}

// ── Quick Create agent ────────────────────────────────────────────────────
var _qcType = '';
function openQuickCreate(type) {
    _qcType = type;
    var labels = { agent: 'New Shipper (Agent)' };
    document.getElementById('qcTitle').textContent = labels[type] || 'New Account';
    document.getElementById('qcSaveBtn').style.background = '#2563eb';
    document.getElementById('qcName').value = '';
    document.getElementById('qcMobile').value = '';
    document.getElementById('qcError').style.display = 'none';
    document.getElementById('quickCreateModal').style.display = 'flex';
    setTimeout(function() { document.getElementById('qcName').focus(); }, 60);
}
function closeQuickCreate() { document.getElementById('quickCreateModal').style.display = 'none'; }
function saveQuickCreate() {
    var name   = document.getElementById('qcName').value.trim();
    var mobile = document.getElementById('qcMobile').value.trim();
    var errEl  = document.getElementById('qcError');
    if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
    var btn = document.getElementById('qcSaveBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Saving...';
    errEl.style.display = 'none';
    // Map type to grpcode
    var grpMap = { agent: 'agent' };
    $.post('includes/quick_create_account.php', { type: _qcType, name: name, mobile: mobile }, function(data) {
        btn.disabled = false; btn.innerHTML = '<i class="fa fa-check"></i> Save';
        if (!data.ok) { errEl.textContent = data.error || 'Could not save.'; errEl.style.display = 'block'; return; }
        var newOpt = new Option(data.name, data.accode, true, true);
        $('#shipper').append(newOpt).trigger('change');
        closeQuickCreate();
        Swal.fire({ icon:'success', title: data.name + ' added!', timer:1200, showConfirmButton:false });
    }, 'json').fail(function() {
        btn.disabled = false; btn.innerHTML = '<i class="fa fa-check"></i> Save';
        errEl.textContent = 'Server error.'; errEl.style.display = 'block';
    });
}
document.getElementById('quickCreateModal').addEventListener('click', function(e) { if (e.target === this) closeQuickCreate(); });

// ── Validation on submit ──────────────────────────────────────────────────
document.getElementById('ssubmit').addEventListener('click', function(e) {
    // Re-enable all disabled .form inputs so readonly computed fields post correctly
    document.querySelectorAll('input.form[disabled], select.form[disabled]').forEach(function(inp) {
        inp.disabled = false;
    });

    var errors = [];
    if (!document.getElementById('vouchdt').value) errors.push('Date is required');
    var cn = document.querySelector('input[name="containerno"]');
    if (!cn || !cn.value.trim()) errors.push('Container No. is required');
    var hasRow = false;
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
        var d = tr.querySelector('input[name="description[]"]');
        if (d && d.value.trim()) hasRow = true;
    });
    if (!hasRow) errors.push('At least one detail row with Description is required');
    if (errors.length) {
        e.preventDefault(); e.stopImmediatePropagation();
        Swal.fire({ icon:'warning', title:'Required Fields',
            html:'<ul style="text-align:left;padding-left:20px;margin:0;">' +
                 errors.map(function(m){return '<li style="margin-bottom:4px;">'+m+'</li>';}).join('') + '</ul>',
            confirmButtonColor:'#2563eb' });
    }
});

// ── Voucher search modal ─────────────────────────────────────────────────
var srchPage = 1, srchPages = 1;
function srchLoad(page) {
    srchPage = page;
    $.post('includes/loadingplan_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);
});

renumber();
recalc();

// Init Select2 on all existing rows AFTER linkshead's document.ready has run
$(function() {
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) { initRowSelects(tr); });

    // When Edit is clicked, re-enable all detail selects for Select2
    $('#hedit').on('click', function() {
        setTimeout(function() {
            document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
                $(tr).find('select.supplier-sel, select.customer-sel').each(function() {
                    $(this).prop('disabled', false).trigger('change.select2');
                });
            });
        }, 0);
    });
});
</script>
</body>
</html>
