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

$formname = 'Container Expense';
$maindb   = 'containerexp';
$file     = 'containerexp.php';
$keyfld   = 'vouchno';
$source   = 'CEXP';

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

// ── Auto-migration ─────────────────────────────────────────────────────────
$t1 = mysqli_query($conn, "SHOW TABLES LIKE 'containerexp'");
if (mysqli_num_rows($t1) == 0) {
    mysqli_query($conn, "CREATE TABLE `containerexp` (
        `vouchno`     int(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `vouchdt`     date         NOT NULL DEFAULT '0000-00-00',
        `containerno` varchar(50)  NOT NULL DEFAULT '',
        `dspvouchno`  int(11)      NOT NULL DEFAULT 0,
        `customer`    int(11)      NOT NULL DEFAULT 0,
        `remarks`     varchar(200) NOT NULL DEFAULT '',
        `totexpamt`   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));
}
$t2 = mysqli_query($conn, "SHOW TABLES LIKE 'containerexplines'");
if (mysqli_num_rows($t2) == 0) {
    mysqli_query($conn, "CREATE TABLE `containerexplines` (
        `srl`       int(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `vouchno`   int(11)      NOT NULL DEFAULT 0,
        `expense`   int(11)      NOT NULL DEFAULT 0,
        `narr`      varchar(200) NOT NULL DEFAULT '',
        `expamt`    double       NOT NULL DEFAULT 0,
        INDEX (`vouchno`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));
}
// Add narr to actran if not exists
$anChk = mysqli_query($conn, "SHOW COLUMNS FROM `actran` LIKE 'narr'");
if ($anChk && mysqli_num_rows($anChk) == 0)
    mysqli_query($conn, "ALTER TABLE `actran` ADD COLUMN `narr` varchar(200) NOT NULL DEFAULT ''");

include("includes/vouchno_generate.php");
include("includes/prev_next.php");
$audituser = audituser();

function acc_list($conn, $grp) {
    $list = []; $r = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `grpcode`='$grp' AND `accode`>50 ORDER BY `name`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $list[] = $row; return $list;
}
function acc_name($conn, $ac) {
    $ac=(int)$ac; if(!$ac) return '';
    $r = mysqli_query($conn, "SELECT `name` FROM `accmast` WHERE `accode`='$ac'");
    $row = $r ? mysqli_fetch_assoc($r) : null; return $row ? $row['name'] : '';
}

$expenseList = acc_list($conn, '012');

// Arrived containers list (despatch with arrivaldate set, not already in containerexp)
$arrivedContainers = [];
$acRes = mysqli_query($conn, "SELECT d.vouchno, d.containerno, d.arrivaldate, d.customer, a.name AS custname
    FROM despatch d
    LEFT JOIN accmast a ON a.accode = d.customer
    WHERE d.containerno != '' AND d.arrivaldate IS NOT NULL AND d.arrivaldate != '0000-00-00'
    AND d.vouchno NOT IN (SELECT DISTINCT dspvouchno FROM containerexp WHERE dspvouchno > 0)
    ORDER BY d.arrivaldate DESC");
while ($r = mysqli_fetch_assoc($acRes)) $arrivedContainers[] = $r;

// ── POST ─────────────────────────────────────────────────────────────────
if (isset($_POST['submit'])) {
    $vouchdt     = trim($_POST['vouchdt']     ?? '');
    $containerno = mysqli_real_escape_string($conn, trim($_POST['containerno'] ?? ''));
    $dspVouch    = (int)($_POST['dspvouchno'] ?? 0);
    $customer    = (int)($_POST['customer']   ?? 0);
    $remarks     = mysqli_real_escape_string($conn, trim($_POST['remarks'] ?? ''));

    $expAccA  = $_POST['expense'] ?? [];
    $expNarrA = $_POST['expnarr'] ?? [];
    $expAmtA  = $_POST['expamt']  ?? [];

    $expLines = []; $totexpamt = 0;
    foreach ($expAccA as $i => $eacc) {
        $eacc = (int)$eacc;
        $eamt = (float)($expAmtA[$i] ?? 0);
        if (!$eacc || $eamt == 0) continue;
        $enarr = mysqli_real_escape_string($conn, trim($expNarrA[$i] ?? ''));
        $expLines[] = ['expense'=>$eacc, 'narr'=>$enarr, 'expamt'=>$eamt];
        $totexpamt += $eamt;
    }

    if ($addflag == 1) {
        mysqli_query($conn, "INSERT INTO `$maindb`
            (`vouchno`,`vouchdt`,`containerno`,`dspvouchno`,`customer`,`remarks`,`totexpamt`,`adduser`,`adddate`,`addtime`)
            VALUES ('$qvouch','$vouchdt','$containerno','$dspVouch','$customer','$remarks','$totexpamt','$audituser',CURDATE(),CURTIME())")
        or die(mysqli_error($conn));
    } else {
        mysqli_query($conn, "UPDATE `$maindb` SET
            `vouchdt`='$vouchdt', `containerno`='$containerno', `dspvouchno`='$dspVouch',
            `customer`='$customer', `remarks`='$remarks', `totexpamt`='$totexpamt',
            `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
            WHERE `$keyfld`='$qvouch'")
        or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `containerexplines` WHERE `vouchno`='$qvouch'");
    }

    foreach ($expLines as $ln) {
        mysqli_query($conn, "INSERT INTO `containerexplines` (`vouchno`,`expense`,`narr`,`expamt`)
            VALUES ('$qvouch','{$ln['expense']}','{$ln['narr']}','{$ln['expamt']}')")
        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 `containerexplines` WHERE `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 ─────────────────────────────────────────────────────────────────
$get = []; $expLines = [];
if ($addflag != 1 && $qvouch > 0) {
    $res = mysqli_query($conn, "SELECT ce.*, a.name AS custname FROM `$maindb` ce LEFT JOIN accmast a ON a.accode=ce.customer WHERE ce.`$keyfld`='$qvouch'");
    $get = mysqli_fetch_assoc($res) ?: [];
    $er  = mysqli_query($conn, "SELECT * FROM `containerexplines` WHERE `vouchno`='$qvouch' ORDER BY `srl`");
    while ($r = mysqli_fetch_assoc($er)) $expLines[] = $r;
}
if (!$expLines) $expLines[] = ['expense'=>0,'narr'=>'','expamt'=>''];

$vouchdt_val = (!empty($get['vouchdt']) && $get['vouchdt']!='0000-00-00') ? $get['vouchdt'] : '';
$selectedCN  = $get['containerno'] ?? '';
$selectedDsp = (int)($get['dspvouchno'] ?? 0);
$selectedCust= (int)($get['customer'] ?? 0);

// Include current voucher's container in the list if editing
if ($addflag != 1 && $selectedCN != '') {
    $alreadyIn = false;
    foreach ($arrivedContainers as $ac) if ($ac['containerno'] == $selectedCN) { $alreadyIn = true; break; }
    if (!$alreadyIn) {
        $curRes = mysqli_query($conn, "SELECT d.vouchno,d.containerno,d.arrivaldate,d.customer,a.name AS custname FROM despatch d LEFT JOIN accmast a ON a.accode=d.customer WHERE d.vouchno='$selectedDsp'");
        if ($curRes && ($curRow = mysqli_fetch_assoc($curRes))) array_unshift($arrivedContainers, $curRow);
    }
}

include("includes/linkshead.php");
?>
<style>
body { background:#f0f2f5; 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:200px; display:flex; flex-direction:column; margin-bottom:11px; }
.lbl { font-size:13px; font-weight:600; color:#374151; margin-bottom:4px; }
.finp { padding:8px 12px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:6px; font-size:13.5px; color:#1e293b; outline:none; 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; }
.finp[readonly] { background:#f1f5f9; color:#64748b; }
.fl .select2-container .select2-selection--single { height:36px; 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:13.5px; color:#1e293b; padding-left:12px; }
.fl .select2-container--default .select2-selection--single .select2-selection__arrow { height:34px; right:6px; }
.fl .select2-container--default.select2-container--focus .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; }

/* Container info strip */
.cnt-info { background:#f0fdf4; border:1px solid #bbf7d0; border-radius:8px; padding:12px 16px; margin:12px 0; display:flex; flex-wrap:wrap; gap:16px; align-items:center; }
.cnt-info-item { font-size:12.5px; color:#166534; }
.cnt-info-item b { font-weight:700; }
.cnt-info-item i { margin-right:5px; }

/* Expense grid */
.grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; margin-top:4px; }
table.dgrid { width:100%; border-collapse:collapse; font-size:13px; }
table.dgrid th { background:#1e293b; color:#e2e8f0; font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:.04em; padding:9px 10px; border-bottom:2px solid #334155; text-align:left; white-space:nowrap; }
table.dgrid th.num { text-align:right; }
table.dgrid td { padding:5px 5px; border-bottom:1px solid #f1f5f9; }
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:13px; padding:8px 8px; color:#1e293b; }
table.dgrid input, table.dgrid select { width:100%; padding:6px 8px; font-size:12.5px; border:1px solid #e2e8f0; border-radius:5px; background:#fff; font-family:inherit; box-sizing:border-box; color:#1e293b; }
table.dgrid input:focus, table.dgrid select:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
table.dgrid input.numfld { text-align:right; }

.row-del { background:#fee2e2; border:none; border-radius:4px; color:#dc2626; cursor:pointer; padding:4px 9px; 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; flex-wrap:wrap; }
.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; position:relative; }
.abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); }
.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; }
</style>
</head>
<body>
<form action="" method="POST">
<input type="hidden" name="submit" value="1">
<input type="hidden" name="dspvouchno" id="dspvouchno" value="<?php echo $selectedDsp; ?>">
<input type="hidden" name="customer"   id="customer_hidden" value="<?php echo $selectedCust; ?>">

<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-file-invoice-dollar" 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>
                <select name="containerno" id="containerno" class="finp form select2 required-star" style="width:100%;" onchange="onContainerChange(this)">
                    <option value="">-- Select Arrived Container --</option>
                    <?php foreach ($arrivedContainers as $ac): ?>
                    <option value="<?php echo htmlspecialchars($ac['containerno']); ?>"
                        data-dsp="<?php echo (int)$ac['vouchno']; ?>"
                        data-cust="<?php echo (int)$ac['customer']; ?>"
                        data-custname="<?php echo htmlspecialchars($ac['custname'] ?? ''); ?>"
                        data-arrival="<?php echo htmlspecialchars($ac['arrivaldate'] ?? ''); ?>"
                        <?php echo ($ac['containerno'] == $selectedCN) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($ac['containerno']); ?>
                        (DSP#<?php echo $ac['vouchno']; ?> · Arrived: <?php echo $ac['arrivaldate'] != '0000-00-00' ? date('d-m-Y', strtotime($ac['arrivaldate'])) : ''; ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Customer</span>
                <input type="text" id="customer_display" class="finp" readonly
                    value="<?php echo htmlspecialchars($get['custname'] ?? ''); ?>"
                    placeholder="Auto-filled from container">
            </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>

        <!-- Container info strip (shown after picking) -->
        <div class="cnt-info" id="cntInfoStrip" style="<?php echo $selectedCN ? '' : 'display:none;'; ?>">
            <div class="cnt-info-item"><i class="fa fa-box"></i>Container: <b id="infoContainer"><?php echo htmlspecialchars($selectedCN); ?></b></div>
            <div class="cnt-info-item"><i class="fa fa-truck"></i>DSP#: <b id="infoDsp"><?php echo $selectedDsp ?: '—'; ?></b></div>
            <div class="cnt-info-item"><i class="fa fa-user"></i>Customer: <b id="infoCust"><?php echo htmlspecialchars($get['custname'] ?? ''); ?></b></div>
            <div class="cnt-info-item"><i class="fa fa-anchor" style="color:#10b981;"></i>Arrived: <b id="infoArrival" style="color:#10b981;"><?php echo (!empty($get['vouchdt']) && $get['vouchdt']!='0000-00-00') ? date('d-m-Y', strtotime($get['vouchdt'])) : ''; ?></b></div>
        </div>

        <!-- Expense rows -->
        <div style="margin-top:16px;">
            <div style="font-size:13px;font-weight:700;color:#1e293b;margin-bottom:8px;"><i class="fa fa-receipt" style="color:#7c3aed;margin-right:7px;"></i>Expense Lines</div>
            <div class="grid-wrap">
            <table class="dgrid" id="dgrid">
                <thead>
                    <tr>
                        <th style="width:28px;">#</th>
                        <th style="width:26px;"></th>
                        <th>Expense Account <span style="color:#ef4444;">*</span></th>
                        <th>Narration / Remarks</th>
                        <th class="num" style="width:120px;">Amount <span style="color:#ef4444;">*</span></th>
                    </tr>
                </thead>
                <tbody id="expBody">
                    <?php foreach ($expLines as $i => $el): ?>
                    <tr>
                        <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;font-size:11px;"><?php echo $i+1; ?></td>
                        <td><button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button></td>
                        <td>
                            <select name="expense[]" class="form exp-acc" onchange="recalc()">
                                <option value="">-- Select Expense --</option>
                                <?php foreach ($expenseList as $erow): ?>
                                <option value="<?php echo (int)$erow['accode']; ?>" <?php echo ((int)($el['expense']??0)==$erow['accode'])?'selected':''; ?>>
                                    <?php echo htmlspecialchars($erow['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><input type="text" name="expnarr[]" class="form" value="<?php echo fv($el,'narr'); ?>" placeholder="Optional narration"></td>
                        <td><input type="number" step="any" name="expamt[]" class="numfld form" value="<?php echo fvn($el,'expamt'); ?>" oninput="recalc()"></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" style="text-align:right;font-size:12px;color:#64748b;">Total Expense</td>
                        <td id="t_totexp" class="num" style="font-size:14px;color:#1e293b;font-weight:800;"></td>
                    </tr>
                </tfoot>
            </table>
            </div>
        </div>

        <button type="button" class="add-row-btn form" onclick="addRow()"><i class="fa fa-plus"></i> Add Expense</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="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>

<!-- Row template -->
<table style="display:none;"><tbody id="rowTemplate">
<tr>
    <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;font-size:11px;"></td>
    <td><button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button></td>
    <td>
        <select name="expense[]" class="form exp-acc" onchange="recalc()">
            <option value="">-- Select Expense --</option>
            <?php foreach ($expenseList as $erow): ?>
            <option value="<?php echo (int)$erow['accode']; ?>"><?php echo htmlspecialchars($erow['name']); ?></option>
            <?php endforeach; ?>
        </select>
    </td>
    <td><input type="text" name="expnarr[]" class="form" placeholder="Optional narration"></td>
    <td><input type="number" step="any" name="expamt[]" class="numfld form" oninput="recalc()"></td>
</tr>
</tbody></table>

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

<script>
function onContainerChange(sel) {
    var opt = sel.options[sel.selectedIndex];
    var dsp     = opt.getAttribute('data-dsp')      || '';
    var cust    = opt.getAttribute('data-cust')     || '';
    var custname= opt.getAttribute('data-custname') || '';
    var arrival = opt.getAttribute('data-arrival')  || '';
    var cn      = sel.value;

    document.getElementById('dspvouchno').value       = dsp;
    document.getElementById('customer_hidden').value  = cust;
    document.getElementById('customer_display').value = custname;

    var strip = document.getElementById('cntInfoStrip');
    if (cn) {
        document.getElementById('infoContainer').textContent = cn;
        document.getElementById('infoDsp').textContent       = dsp ? 'DSP#'+dsp : '—';
        document.getElementById('infoCust').textContent      = custname || '—';
        if (arrival) {
            var d = new Date(arrival);
            document.getElementById('infoArrival').textContent = d.toLocaleDateString('en-GB');
        }
        strip.style.display = 'flex';
    } else {
        strip.style.display = 'none';
    }
}

function addRow() {
    var tpl = document.getElementById('rowTemplate').innerHTML;
    var tbody = document.getElementById('expBody');
    var tr = document.createElement('tr');
    tr.innerHTML = tpl;
    tbody.appendChild(tr);
    renumber();
}

function delRow(btn) {
    var tbody = document.getElementById('expBody');
    if (tbody.rows.length > 1) { btn.closest('tr').remove(); recalc(); }
}

function renumber() {
    document.querySelectorAll('#expBody tr').forEach(function(tr, i) {
        var c = tr.querySelector('.srno'); if (c) c.textContent = i + 1;
    });
}

function recalc() {
    var total = 0;
    document.querySelectorAll('#expBody tr').forEach(function(tr) {
        var inp = tr.querySelector('input[name="expamt[]"]');
        var v = inp && inp.value !== '' ? parseFloat(inp.value) : 0;
        if (!isNaN(v)) total += v;
    });
    document.getElementById('t_totexp').textContent = total ? total.toFixed(2) : '';
}

// Submit validation + re-enable
document.getElementById('ssubmit').addEventListener('click', function(e) {
    document.querySelectorAll('input.form[disabled], select.form[disabled]').forEach(function(i){ i.disabled=false; });
    var errors = [];
    if (!document.getElementById('vouchdt').value) errors.push('Date is required');
    if (!document.getElementById('containerno').value) errors.push('Container No. is required');
    var hasExp = false;
    document.querySelectorAll('#expBody tr').forEach(function(tr) {
        var acc = tr.querySelector('select[name="expense[]"]');
        var amt = tr.querySelector('input[name="expamt[]"]');
        if (acc && acc.value && amt && parseFloat(amt.value) > 0) hasExp = true;
    });
    if (!hasExp) errors.push('At least one expense line with account and amount 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' });
    }
});

renumber();
recalc();
</script>
</body>
</html>
