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

$formname  = 'Sale';
$maindb    = 'sale';
$printfile = 'sale_print.php';
$file      = 'sale.php';
$keyfld    = 'vouchno';
$keycond   = '';
$source    = 'SAL';      // actran source code

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

mysqli_select_db($conn, $zdb);

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

$_upSale = upload_path('sale');
$uploaddir = $_upSale['dir'];
$uploadurl = $_upSale['url'];

const SALE_IMAGE_MAXSIZE = 512000; // 500 KB

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

    $descA   = isset($_POST['description']) ? $_POST['description'] : [];
    $modelA  = isset($_POST['modelno'])      ? $_POST['modelno']      : [];
    $markaA  = isset($_POST['marka'])        ? $_POST['marka']        : [];
    $ctnA    = isset($_POST['ctn'])          ? $_POST['ctn']          : [];
    $qtyA    = isset($_POST['qty'])          ? $_POST['qty']          : [];
    $tqtyA   = isset($_POST['tqty'])         ? $_POST['tqty']         : [];
    $rateA   = isset($_POST['rate'])         ? $_POST['rate']         : [];
    $amtA    = isset($_POST['amt'])          ? $_POST['amt']          : [];
    $cbmA    = isset($_POST['cbm'])          ? $_POST['cbm']          : [];
    $tcbmA   = isset($_POST['tcbm'])         ? $_POST['tcbm']         : [];
    $wtA     = isset($_POST['weight'])       ? $_POST['weight']       : [];
    $twtA    = isset($_POST['tweight'])      ? $_POST['tweight']      : [];
    $picfileA = isset($_POST['picfile'])     ? $_POST['picfile']      : [];

    $expaccA = isset($_POST['expacc']) ? $_POST['expacc'] : [];
    $expamtA = isset($_POST['expamt']) ? $_POST['expamt'] : [];

    $a = 1;

    // Convert date dd-mm-yyyy -> yyyy-mm-dd
    $vd = '';
    if (preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $vouchdt, $m)) {
        $vd = $m[3] . '-' . $m[2] . '-' . $m[1];
    } else {
        $vd = $vouchdt;
    }

    if ($vouchdt == '' || $vd == '') {
        $a = 0;
        browse("Date Cannot Be Empty");
        header("refresh:1; url=$file?mode=last");
    }

    if ($a == 1 && $customer <= 0) {
        $a = 0;
        browse("Please Select Customer");
        header("refresh:1; url=$file?mode=last");
    }

    // ── Build clean line rows (skip fully empty rows), handle image uploads ──
    $lines = [];
    $totctn = $totqty = $tottqty = $totamt = $totcbm = $tottcbm = $totweight = $tottweight = 0;

    if ($a == 1) {
        $cnt = count($descA);
        for ($i = 0; $i < $cnt; $i++) {
            $desc  = trim($descA[$i]);
            $model = isset($modelA[$i]) ? trim($modelA[$i]) : '';
            $marka = isset($markaA[$i]) ? trim($markaA[$i]) : '';
            $ctn   = isset($ctnA[$i])  && $ctnA[$i]  !== '' ? (float)$ctnA[$i]  : 0;
            $qty   = isset($qtyA[$i])  && $qtyA[$i]  !== '' ? (float)$qtyA[$i]  : 0;
            $tqty  = isset($tqtyA[$i]) && $tqtyA[$i] !== '' ? (float)$tqtyA[$i] : 0;
            $rate  = isset($rateA[$i]) && $rateA[$i] !== '' ? (float)$rateA[$i] : 0;
            $amt   = isset($amtA[$i])  && $amtA[$i]  !== '' ? (float)$amtA[$i]  : 0;
            $cbm   = isset($cbmA[$i])  && $cbmA[$i]  !== '' ? (float)$cbmA[$i]  : 0;
            $tcbm  = isset($tcbmA[$i]) && $tcbmA[$i] !== '' ? (float)$tcbmA[$i] : 0;
            $wt    = isset($wtA[$i])   && $wtA[$i]   !== '' ? (float)$wtA[$i]   : 0;
            $twt   = isset($twtA[$i])  && $twtA[$i]  !== '' ? (float)$twtA[$i]  : 0;
            $oldpic = isset($picfileA[$i]) ? trim($picfileA[$i]) : '';

            // Image upload for this row (optional)
            $picname = $oldpic;
            $hasUpload = isset($_FILES['pic']['name'][$i]) && $_FILES['pic']['error'][$i] != UPLOAD_ERR_NO_FILE;

            if ($hasUpload) {
                $err  = $_FILES['pic']['error'][$i];
                $size = $_FILES['pic']['size'][$i];
                $tmp  = $_FILES['pic']['tmp_name'][$i];
                $nm   = $_FILES['pic']['name'][$i];

                if ($err != UPLOAD_ERR_OK) {
                    $a = 0;
                    browse("Image Upload Failed For Row " . ($i + 1));
                    header("refresh:1; url=$file?mode=last");
                } elseif ($size > SALE_IMAGE_MAXSIZE) {
                    $a = 0;
                    browse("Image Size Must Be Up To 500 KB (Row " . ($i + 1) . ")");
                    header("refresh:1; url=$file?mode=last");
                } else {
                    $allowedExt = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp'];
                    $ext  = strtolower(pathinfo($nm, PATHINFO_EXTENSION));
                    $mime = mime_content_type($tmp);

                    if (!isset($allowedExt[$ext]) || $mime != $allowedExt[$ext]) {
                        $a = 0;
                        browse("Only JPG, PNG, GIF or WEBP Images Are Allowed (Row " . ($i + 1) . ")");
                        header("refresh:1; url=$file?mode=last");
                    } else {
                        $newname = 'purch_' . $qvouch . '_' . ($i + 1) . '_' . time() . '.' . $ext;
                        if (!move_uploaded_file($tmp, $uploaddir . $newname)) {
                            $a = 0;
                            browse("Could Not Save Uploaded Image (Row " . ($i + 1) . ")");
                            header("refresh:1; url=$file?mode=last");
                        } else {
                            if ($oldpic != '' && $oldpic != $newname && file_exists($uploaddir . $oldpic)) {
                                @unlink($uploaddir . $oldpic);
                            }
                            $picname = $newname;
                        }
                    }
                }
            }

            if ($desc == '' && $model == '' && $marka == '' && $picname == ''
                && $ctn == 0 && $qty == 0 && $tqty == 0 && $rate == 0 && $amt == 0
                && $cbm == 0 && $tcbm == 0 && $wt == 0 && $twt == 0) {
                continue;
            }

            $lines[] = [
                'picfile'     => $picname,
                'description' => $desc,
                'modelno'     => $model,
                'marka'       => $marka,
                'ctn'         => $ctn,
                'qty'         => $qty,
                'tqty'        => $tqty,
                'rate'        => $rate,
                'amt'         => $amt,
                'cbm'         => $cbm,
                'tcbm'        => $tcbm,
                'weight'      => $wt,
                'tweight'     => $twt,
            ];

            $totctn     += $ctn;
            $totqty     += $qty;
            $tottqty    += $tqty;
            $totamt     += $amt;
            $totcbm     += $cbm;
            $tottcbm    += $tcbm;
            $totweight  += $wt;
            $tottweight += $twt;
        }

        if ($a == 1 && count($lines) == 0) {
            $a = 0;
            browse("Please Add At Least One Item Row");
            header("refresh:1; url=$file?mode=last");
        }
    }

    // ── Build clean expense-allocation rows (skip fully empty rows) ──────────
    $expLines = [];
    $totexpamt = 0;
    if ($a == 1) {
        $ecnt = count($expaccA);
        for ($j = 0; $j < $ecnt; $j++) {
            $eacc = isset($expaccA[$j]) ? (int)$expaccA[$j] : 0;
            $eamt = isset($expamtA[$j]) && $expamtA[$j] !== '' ? (float)$expamtA[$j] : 0;
            if ($eacc <= 0 || $eamt == 0) continue;
            $expLines[] = ['expense' => $eacc, 'expamt' => $eamt];
            $totexpamt += $eamt;
        }
    }

    if ($a == 1) {
        $audituser = mysqli_real_escape_string($conn, audituser());

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

            mysqli_query($conn, "DELETE FROM `saletr` WHERE `vouchno`='$qvouch'")
            or die(mysqli_error($conn));

            mysqli_query($conn, "DELETE FROM `saleexp` WHERE `vouchno`='$qvouch'")
            or die(mysqli_error($conn));
        }
        
        foreach ($lines as $ln) {
            $desc = trim($ln['description']);
            if ($desc == '') {
                continue;
            }
            $desc_esc = mysqli_real_escape_string($conn, $desc);
            $chk = mysqli_query($conn, "SELECT id FROM product WHERE LOWER(name)=LOWER('$desc_esc') LIMIT 1");

            if (mysqli_num_rows($chk) == 0) {
                $res = mysqli_query($conn, "SELECT IFNULL(MAX(id),0)+1 AS nextid FROM product");
                $row = mysqli_fetch_assoc($res);
                $productid = $row['nextid'];

                mysqli_query($conn, "INSERT INTO product(id, name, adduser, adddate, addtime)
                VALUES('$productid', '$desc_esc', '$audituser', CURDATE(), CURTIME())
        ") or die(mysqli_error($conn));
            }
        }

        foreach ($lines as $ln) {
            $pic = mysqli_real_escape_string($conn, $ln['picfile']);
            $d   = mysqli_real_escape_string($conn, $ln['description']);
            $mo  = mysqli_real_escape_string($conn, $ln['modelno']);
            $mk  = mysqli_real_escape_string($conn, $ln['marka']);
            mysqli_query($conn, "INSERT INTO `saletr`
                (`vouchno`,`picfile`,`description`,`modelno`,`marka`,
                 `ctn`,`qty`,`tqty`,`rate`,`amt`,`cbm`,`tcbm`,`weight`,`tweight`)
                VALUES
                ('$qvouch','$pic','$d','$mo','$mk',
                 '{$ln['ctn']}','{$ln['qty']}','{$ln['tqty']}','{$ln['rate']}','{$ln['amt']}',
                 '{$ln['cbm']}','{$ln['tcbm']}','{$ln['weight']}','{$ln['tweight']}')")
            or die(mysqli_error($conn));
        }

        foreach ($expLines as $eln) {
            mysqli_query($conn, "INSERT INTO `saleexp` (`vouchno`,`vouchdt`,`expense`,`expamt`)
                VALUES ('$qvouch','$vd','{$eln['expense']}','{$eln['expamt']}')")
            or die(mysqli_error($conn));
        }

        // ── Posting to actran (ledger pattern) ───────────────────────────────
        // Sale part: minus goes to Credit Sale (accode 15, grpcode 005)
        // Customer part: ONE single debit (minus) for the full receivable (sale amount + total expenses combined)
        // Credit Sale part: credit (plus) for the sale amount
        // Expense lines: each expense account credited (plus) individually for its own amount
        mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));

        $trnno = 1;
        $prodtype = '';
        $totReceivable = $totamt + $totexpamt;

        if ($totReceivable > 0) {
            $minus_receivable = $totReceivable * -1;

            // customer part — ONE entry for the combined total
            $tn = str_pad($trnno++, 3, '0', STR_PAD_LEFT);
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,vouchno, source, trnno, accode, grpcode, feamt, roe, amount, prodtype, actamt)
                                      VALUES ('$vd','$vd','$qvouch', '$source', '$tn', '$customer', '010', '$minus_receivable', '1','$minus_receivable','$prodtype','$minus_receivable')")
            or die(mysqli_error($conn));
        }

        if ($totamt > 0) {
            // sale part — credit
            $tn = str_pad($trnno++, 3, '0', STR_PAD_LEFT);
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,vouchno, source, trnno, accode, grpcode, feamt, roe, amount, prodtype, actamt)
                                      VALUES ('$vd','$vd','$qvouch', '$source', '$tn', '15', '005', '$totamt','1', '$totamt','$prodtype','$totamt')")
            or die(mysqli_error($conn));
        }

        foreach ($expLines as $eln) {
            // expense account part — credit (recovered from customer)
            $tn = str_pad($trnno++, 3, '0', STR_PAD_LEFT);
            mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,vouchno, source, trnno, accode, grpcode, feamt, roe, amount, prodtype, actamt)
                                      VALUES ('$vd','$vd','$qvouch', '$source', '$tn', '{$eln['expense']}', '020', '{$eln['expamt']}','1', '{$eln['expamt']}','$prodtype','{$eln['expamt']}')")
            or die(mysqli_error($conn));
        }

        if ($addflag == 1) {
            insmess();
        } else {
            updmess();
        }
        header("refresh:1; url=$file?$keyfld=$qvouch&mode=edit");
    }
}

// ── Fetch record ─────────────────────────────────────────────────────────────
$get   = [];
$lines = [];
$expRows = [];
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 = [];

    $tres = mysqli_query($conn, "SELECT * FROM `saletr` WHERE `vouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_array($tres)) {
        $lines[] = $r;
    }

    $eres = mysqli_query($conn, "SELECT * FROM `saleexp` WHERE `vouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_array($eres)) {
        $expRows[] = $r;
    }
}

// Lookup name for customer (accmast)
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']) : '';

// Account lists for Customer (grpcode 010) and Expense (grpcode 020) select combos
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');
$expenseList  = acc_list($conn, '020');

// Always have at least one blank row for new entries
if (count($lines) == 0) {
    $lines[] = ['picfile'=>'','description'=>'','modelno'=>'','marka'=>'',
                 'ctn'=>'','qty'=>'','tqty'=>'','rate'=>'','amt'=>'','cbm'=>'','tcbm'=>'','weight'=>'','tweight'=>''];
}
if (count($expRows) == 0) {
    $expRows[] = ['expense'=>'','expamt'=>''];
}

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    $tres = mysqli_query($conn, "SELECT `picfile` FROM `saletr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_assoc($tres)) {
        if ($r['picfile'] != '' && file_exists($uploaddir . $r['picfile'])) {
            @unlink($uploaddir . $r['picfile']);
        }
    }
    mysqli_query($conn, "DELETE FROM `saletr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `saleexp` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `actran` 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();
    header("refresh:1; url=$file?mode=last");
    exit;
}

// Helper: get value safely
function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}
function fvn($get, $key) {
    if (!isset($get[$key]) || $get[$key] === '' || $get[$key] === null) return '';
    $v = (float)$get[$key];
    return ($v == 0) ? '' : (($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;
        letter-spacing:.01em;
    }
    .sim-badge {
        font-size:11px;
        background:#f1f5f9;
        color:#64748b;
        border-radius:20px;
        padding:3px 10px;
        font-weight:600;
    }
    .btn-pickup {
        font-size:11.5px; font-weight:600; border:none; border-radius:20px;
        padding:5px 14px; cursor:pointer; color:#fff; display:inline-flex; align-items:center; gap:5px;
        background:#7c3aed;
    }
    .btn-pickup:hover { background:#6d28d9; }

    .sim-body { padding:20px; }

    .fr { display:flex; align-items:center; margin-bottom:9px; gap:0; }
    .fr.fr-grid { display:grid; grid-template-columns: 1fr 1fr 1fr; gap:9px 14px; }

    .fl { display:flex; align-items:center; flex:1; }

    .lbl {
        font-size:12px;
        font-weight:500;
        color:#64748b;
        white-space:nowrap;
        text-align:right;
        padding-right:10px;
        min-width:110px;
        flex-shrink:0;
    }

    .finp {
        flex:1;
        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;
        cursor:not-allowed;
        border-color:#e2e8f0;
    }
    .finp.required-star { border-left:3px solid #3b82f6; }

    /* Make select2 boxes match .finp exactly (height, border, background, radius) */
    .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;
    }

    .pick-btn {
        padding:7px 11px;
        margin-left:6px;
        background:#2563eb;
        color:#fff;
        border:none;
        border-radius:6px;
        cursor:pointer;
        font-size:12px;
    }
    .pick-btn:hover { background:#1d4ed8; }
    .pick-btn:disabled, .row-del:disabled, .add-row-btn:disabled, .pic-btn:disabled {
        opacity:.45; cursor:not-allowed;
    }

    .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 th.marka-col { color:#dc2626; }
    table.dgrid td { padding:4px 6px; border-bottom:1px solid #f1f5f9; }
    table.dgrid input {
        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 { background:#fff; border-color:#3b82f6; }
    table.dgrid input:read-only { background:#f1f5f9; color:#64748b; }
    table.dgrid tfoot td {
        background:#f8fafc; font-weight:700; color:#1e293b; padding:8px 6px;
        border-top:2px solid #e2e8f0;
    }
    .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; }

    .pic-cell { display:flex; flex-direction:column; align-items:center; gap:3px; width:56px; }
    .pic-thumb {
        width:50px; height:50px; object-fit:cover; border-radius:5px; border:1px solid #e2e8f0;
        background:#f8fafc; display:block;
    }
    .pic-placeholder {
        width:50px; height:50px; border-radius:5px; border:1px dashed #cbd5e1;
        background:#f8fafc; display:flex; align-items:center; justify-content:center;
        color:#cbd5e1; font-size:16px;
    }
    .pic-btn {
        font-size:10px; padding:2px 6px; border:none; border-radius:4px;
        background:#e2e8f0; color:#475569; cursor:pointer; font-weight:600;
    }
    .pic-btn:hover { background:#cbd5e1; }
    .pic-input { display:none; }

    .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:#db2777; }
    .abtn-print  { background:#7c3aed; }
    .abtn-add    { background:#16a34a; }
    .abtn-edit   { background:#ea580c; }
    .abtn-del    { background:#dc2626; }
    .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; }

    .audit-info {
        margin-top:14px;
        padding-top:10px;
        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; }

    .pickModal {
        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;
    }
    .pickModal .pm-box {
        background:#fff; border-radius:12px; width:94%; max-width:700px; overflow:hidden;
        box-shadow:0 24px 64px rgba(0,0,0,.3); max-height:80vh; display:flex; flex-direction:column;
    }
    .pickModal .pm-box.pm-wide { max-width:900px; }

    /* ── 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,
        .fr[style*="grid-template-columns"] {
            display:flex !important;
            flex-direction:column !important;
            grid-template-columns:none !important;
            align-items:stretch;
            gap:10px;
        }
        .fl { width:100%; }
        .lbl { width:100%; text-align:left; padding-right:0; 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:640px; }
        table.dgrid th, table.dgrid td { padding:5px 5px; }
        table.dgrid input, table.dgrid select { font-size:11px; padding:5px 4px; }

        .add-row-btn { width:100%; justify-content:center; margin-top:8px; }
        .btn-bar { gap:6px; padding:12px 10px; flex-wrap:wrap; }
        .abtn { flex:1 1 auto; min-width:42px; height:42px; font-size:13px; }
        .abtn::after { display:none; }

        .pickModal { padding-top:20px; }
        .pickModal .pm-box, .pickModal .pm-box.pm-wide { width:96%; max-width:96%; max-height:90vh; }
    }
</style>

<body>
<form action="" method="POST" enctype="multipart/form-data">

<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-cart-arrow-down" 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" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:9px 14px;">
            <div class="fl">
                <span class="lbl">Voucher No</span>
                <input type="text" class="finp" disabled value="<?php echo $qvouch > 0 ? $qvouch : 'New'; ?>">
            </div>
            <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 datepick" required
                    placeholder="dd-mm-yyyy"
                    value="<?php echo htmlspecialchars($vouchdt_disp); ?>">
            </div>
            <div class="fl">
                <span class="lbl">Ship Marka</span>
                <input type="text" name="shipmarka" id="shipmarka" class="finp form" maxlength="50"
                    value="<?php echo fv($get,'shipmarka'); ?>">
            </div>
        </div>

        <div class="fr fr-grid">
            <div class="fl">
                <span class="lbl">Customer <span style="color:#ef4444;">*</span></span>
                <select name="customer" id="customer" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Customer --</option>
                    <?php foreach ($customerList as $row): ?>
                    <option value="<?php echo (int)$row['accode']; ?>" <?php echo (fv($get,'customer') == $row['accode']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($row['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Remarks</span>
                <input type="text" name="remarks" class="finp form" maxlength="100"
                    value="<?php echo fv($get,'remarks'); ?>">
            </div>
        </div>

        <div class="grid-wrap">
            <datalist id="productList">
                        <?php
                        $res = mysqli_query($conn, "SELECT DISTINCT name FROM product ORDER BY name");
                            while ($row = mysqli_fetch_assoc($res)) {
                        ?>
                            <option value="<?php echo htmlspecialchars($row['name']); ?>">
                        <?php } ?>
                    </datalist>
            <table class="dgrid" id="dgrid">
                <thead>
                    <tr>
                        <th style="width:32px;">#</th>
                        <th style="width:28px;"></th>
                        <th style="width:56px;">Goods Pic</th>
                        <th style="text-align:left;min-width:100px;">Description</th>
                        <th style="width:100px;text-align:left;">Model No.</th>
                        <th class="marka-col" style="width:80px;text-align:left;">Marka</th>
                        <th style="width:65px;text-align:right;">CTN</th>
                        <th style="width:80px;text-align:right;">QTY</th>
                        <th style="width:85px;text-align:right;">T.QTY</th>
                        <th style="width:75px;text-align:right;">Rate</th>
                        <th style="width:100px;text-align:right;">T.Amount</th>
                        <th style="width:80px;text-align:right;">CBM</th>
                        <th style="width:85px;text-align:right;">T.CBM</th>
                        <th style="width:80px;text-align:right;">Weight</th>
                        <th style="width:90px;text-align:right;">T.Weight</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 style="text-align:center;">
                            <button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button>
                        </td>
                        <td>
                            <div class="pic-cell">
                                <?php if (!empty($ln['picfile'])): ?>
                                <img class="pic-thumb" src="<?php echo $uploadurl . htmlspecialchars($ln['picfile']); ?>" alt="">
                                <?php else: ?>
                                <div class="pic-placeholder"><i class="fa fa-image"></i></div>
                                <?php endif; ?>
                                <input type="hidden" name="picfile[]" value="<?php echo fv($ln,'picfile'); ?>">
                                <input type="file" name="pic[]" class="pic-input form" accept="image/*" onchange="picPreview(this)">
                                <button type="button" class="pic-btn form" onclick="this.previousElementSibling.click()">Upload</button>
                            </div>
                        </td>
                        <td><input type="text" name="description[]" class="desc-inp form" list="productList" value="<?php echo fv($ln,'description'); ?>" autocomplete="off"></td>
                        <td><input type="text" name="modelno[]" class="txt-inp form" value="<?php echo fv($ln,'modelno'); ?>"></td>
                        <td><input type="text" name="marka[]" class="txt-inp form" value="<?php echo fv($ln,'marka'); ?>"></td>
                        <td><input type="number" step="any" name="ctn[]" class="numfld form" value="<?php echo fvn($ln,'ctn'); ?>" oninput="onCalcInput(this)"></td>
                        <td><input type="number" step="any" name="qty[]" class="numfld form" value="<?php echo fvn($ln,'qty'); ?>" oninput="onCalcInput(this)"></td>
                        <td><input type="number" step="any" name="tqty[]" class="numfld form" value="<?php echo fvn($ln,'tqty'); ?>" readonly tabindex="-1"></td>
                        <td><input type="number" step="any" name="rate[]" class="numfld form" value="<?php echo fvn($ln,'rate'); ?>" oninput="onCalcInput(this)"></td>
                        <td><input type="number" step="any" name="amt[]" class="numfld form" value="<?php echo fvn($ln,'amt'); ?>" readonly tabindex="-1"></td>
                        <td><input type="number" step="any" name="cbm[]" class="numfld form" value="<?php echo fvn($ln,'cbm'); ?>" oninput="onCalcInput(this)"></td>
                        <td><input type="number" step="any" name="tcbm[]" class="numfld form" value="<?php echo fvn($ln,'tcbm'); ?>" readonly tabindex="-1"></td>
                        <td><input type="number" step="any" name="weight[]" class="numfld form" value="<?php echo fvn($ln,'weight'); ?>" oninput="onCalcInput(this)"></td>
                        <td><input type="number" step="any" name="tweight[]" class="numfld form" value="<?php echo fvn($ln,'tweight'); ?>" readonly tabindex="-1"></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="6" style="text-align:right;">Total</td>
                        <td id="t_ctn" style="text-align:right;"></td>
                        <td id="t_qty" style="text-align:right;"></td>
                        <td id="t_tqty" style="text-align:right;"></td>
                        <td></td>
                        <td id="t_amt" style="text-align:right;"></td>
                        <td id="t_cbm" style="text-align:right;"></td>
                        <td id="t_tcbm" style="text-align:right;"></td>
                        <td id="t_weight" style="text-align:right;"></td>
                        <td id="t_tweight" style="text-align:right;"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <button type="button" class="add-row-btn form" onclick="addRow()"><i class="fa fa-plus"></i> Add Row</button>

        <div style="margin-top:22px;padding-top:16px;border-top:1px dashed #e2e8f0;">
            <div style="font-size:12.5px;font-weight:700;color:#374151;margin-bottom:10px;">
                <i class="fa fa-receipt" style="color:#ea580c;margin-right:6px;"></i>Expense Allocation
            </div>
            <div class="grid-wrap">
                <table class="dgrid" id="expgrid">
                    <thead>
                        <tr>
                            <th style="width:32px;">#</th>
                            <th style="width:28px;"></th>
                            <th style="text-align:left;">Expense Account</th>
                            <th style="width:140px;">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($expRows as $i => $er): ?>
                        <tr>
                            <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;"></td>
                            <td style="text-align:center;">
                                <button type="button" class="row-del form" onclick="delExpRow(this)"><i class="fa fa-times"></i></button>
                            </td>
                            <td>
                                <select name="expacc[]" class="form expacc-select" style="width:100%;padding:6px 8px;font-size:12px;border:1px solid #e2e8f0;border-radius:5px;background:#f8fafc;">
                                    <option value="">-- Select Expense --</option>
                                    <?php foreach ($expenseList as $erow): ?>
                                    <option value="<?php echo (int)$erow['accode']; ?>" <?php echo (fv($er,'expense') == $erow['accode']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($erow['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td><input type="number" step="any" name="expamt[]" class="numfld form" value="<?php echo fvn($er,'expamt'); ?>" oninput="recalcExp()"></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" style="text-align:right;">Total Expense</td>
                            <td id="t_expamt" style="text-align:right;"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <button type="button" class="add-row-btn form" onclick="addExpRow()"><i class="fa fa-plus"></i> Add Expense Row</button>
        </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><!-- /sim-card -->
</form>

<table style="display:none;"><tbody id="rowTemplate">
    <tr>
        <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;"></td>
        <td style="text-align:center;">
            <button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button>
        </td>
        <td>
            <div class="pic-cell">
                <div class="pic-placeholder"><i class="fa fa-image"></i></div>
                <input type="hidden" name="picfile[]" value="">
                <input type="file" name="pic[]" class="pic-input form" accept="image/*" onchange="picPreview(this)">
                <button type="button" class="pic-btn form" onclick="this.previousElementSibling.click()">Upload</button>
            </div>
        </td>
        <td><input type="text" name="description[]" class="desc-inp form" list="productList" autocomplete="off"></td>
        <td><input type="text" name="modelno[]" class="txt-inp form"></td>
        <td><input type="text" name="marka[]" class="txt-inp form"></td>
        <td><input type="number" step="any" name="ctn[]" class="numfld form" oninput="onCalcInput(this)"></td>
        <td><input type="number" step="any" name="qty[]" class="numfld form" oninput="onCalcInput(this)"></td>
        <td><input type="number" step="any" name="tqty[]" class="numfld form" readonly tabindex="-1"></td>
        <td><input type="number" step="any" name="rate[]" class="numfld form" oninput="onCalcInput(this)"></td>
        <td><input type="number" step="any" name="amt[]" class="numfld form" readonly tabindex="-1"></td>
        <td><input type="number" step="any" name="cbm[]" class="numfld form" oninput="onCalcInput(this)"></td>
        <td><input type="number" step="any" name="tcbm[]" class="numfld form" readonly tabindex="-1"></td>
        <td><input type="number" step="any" name="weight[]" class="numfld form" oninput="onCalcInput(this)"></td>
        <td><input type="number" step="any" name="tweight[]" class="numfld form" readonly tabindex="-1"></td>
    </tr>
</tbody></table>

<table style="display:none;"><tbody id="expRowTemplate">
    <tr>
        <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;"></td>
        <td style="text-align:center;">
            <button type="button" class="row-del form" onclick="delExpRow(this)"><i class="fa fa-times"></i></button>
        </td>
        <td>
            <select name="expacc[]" class="form expacc-select" style="width:100%;padding:6px 8px;font-size:12px;border:1px solid #e2e8f0;border-radius:5px;background:#f8fafc;">
                <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="number" step="any" name="expamt[]" class="numfld form" oninput="recalcExp()"></td>
    </tr>
</tbody></table>

<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:#db2777;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;">Ship Marka / Customer / 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;">Ship Marka</th>
                        <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Amount</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>

<script>
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);
    renumber();
}

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

function delRow(btn) {
    var tbody = document.querySelector('#dgrid tbody');
    if (tbody.rows.length > 1) {
        btn.closest('tr').remove();
        recalc();
        renumber();
    } else {
        var tr = btn.closest('tr');
        tr.querySelectorAll('input').forEach(function(i){
            i.value = '';
        });
        var cell = tr.querySelector('.pic-cell');
        var existingImg = cell.querySelector('.pic-thumb');
        if (existingImg) existingImg.remove();
        if (!cell.querySelector('.pic-placeholder')) {
            var ph = document.createElement('div');
            ph.className = 'pic-placeholder';
            ph.innerHTML = '<i class="fa fa-image"></i>';
            cell.insertBefore(ph, cell.firstChild);
        }
        recalc();
    }
}

function picPreview(input) {
    var cell = input.closest('.pic-cell');
    if (!input.files || !input.files[0]) return;
    var reader = new FileReader();
    reader.onload = function (e) {
        var existing = cell.querySelector('.pic-thumb, .pic-placeholder');
        var img = document.createElement('img');
        img.className = 'pic-thumb';
        img.src = e.target.result;
        if (existing) {
            cell.replaceChild(img, existing);
        } else {
            cell.insertBefore(img, cell.firstChild);
        }
    };
    reader.readAsDataURL(input.files[0]);
}

function calcRow(tr) {
    function val(name) {
        var inp = tr.querySelector('input[name="' + name + '[]"]');
        var v = inp && inp.value !== '' ? parseFloat(inp.value) : 0;
        return isNaN(v) ? 0 : v;
    }
    function setVal(name, v) {
        var inp = tr.querySelector('input[name="' + name + '[]"]');
        if (inp) inp.value = v ? v : '';
    }

    var ctn = val('ctn');
    var qty = val('qty');
    var cbm = val('cbm');
    var wt  = val('weight');
    var rate = val('rate');

    var tqty = ctn * qty;
    var tcbm = ctn * cbm;
    var twt  = ctn * wt;
    var amt  = twt * rate;

    setVal('tqty', tqty);
    setVal('tcbm', tcbm);
    setVal('tweight', twt);
    setVal('amt', amt);
}

function onCalcInput(input) {
    calcRow(input.closest('tr'));
    recalc();
}

function fmt2(n) {
    return n ? n.toFixed(2) : '';
}

function recalc() {
    var cols = ['ctn','qty','tqty','amt','cbm','tcbm','weight','tweight'];
    var totals = {ctn:0, qty:0, tqty:0, amt:0, cbm:0, tcbm:0, weight:0, tweight: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;
        });
    });
    document.getElementById('t_ctn').textContent     = fmt2(totals.ctn);
    document.getElementById('t_qty').textContent     = fmt2(totals.qty);
    document.getElementById('t_tqty').textContent    = fmt2(totals.tqty);
    document.getElementById('t_amt').textContent     = fmt2(totals.amt);
    document.getElementById('t_cbm').textContent     = fmt2(totals.cbm);
    document.getElementById('t_tcbm').textContent    = fmt2(totals.tcbm);
    document.getElementById('t_weight').textContent  = fmt2(totals.weight);
    document.getElementById('t_tweight').textContent = fmt2(totals.tweight);
}
recalc();
renumber();

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

function srchLoad(page) {
    srchPage = page;
    $.post('includes/sale_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);
});

// ── Expense Allocation rows ──────────────────────────────────────────────────
function addExpRow() {
    var tpl = document.getElementById('expRowTemplate').innerHTML;
    var tbody = document.querySelector('#expgrid tbody');
    var tr = document.createElement('tr');
    tr.innerHTML = tpl;
    tbody.appendChild(tr);
    renumberExp();
    if (window.jQuery) {
        $(tr).find('select.expacc-select').each(function () {
            // plain select, no select2 init needed (kept lightweight inside grid)
        });
    }
}

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

function delExpRow(btn) {
    var tbody = document.querySelector('#expgrid tbody');
    if (tbody.rows.length > 1) {
        btn.closest('tr').remove();
    } else {
        var tr = btn.closest('tr');
        var sel = tr.querySelector('select');
        if (sel) sel.value = '';
        var inp = tr.querySelector('input');
        if (inp) inp.value = '';
    }
    recalcExp();
    renumberExp();
}

function recalcExp() {
    var total = 0;
    document.querySelectorAll('#expgrid tbody 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_expamt').textContent = total ? total.toFixed(2) : '';
}
recalcExp();
renumberExp();

// Re-enable ALL disabled .form inputs before submit so computed readonly fields are included in POST
document.getElementById('ssubmit').addEventListener('click', function () {
    document.querySelectorAll('input.form[disabled], select.form[disabled]').forEach(function (inp) {
        inp.disabled = false;
    });
});
</script>

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