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

$formname  = 'Purchase';
$maindb    = 'purchase';
$printfile = 'purchase_print.php';
$file      = 'purchase.php';
$keyfld    = 'vouchno';
$source    = 'PUR';      // actran source code

$zdb       = $_SESSION["zdbyear_" . $dbname];
$compcd    = $_SESSION["comp_"    . $dbname];
$usertype  = (int)$_SESSION["usertype_" . $dbname];
$agentcode = (int)($_SESSION["agentcode_".$dbname] ?? 0);
$keycond   = ($usertype === 3 && $agentcode > 0) ? "AND `salesman`='$agentcode'" : '';

mysqli_select_db($conn, $zdb);

// Auto-add custpaid column to purchase table if not yet present
$cpCheck = mysqli_query($conn, "SHOW COLUMNS FROM `purchase` LIKE 'custpaid'");
if ($cpCheck && mysqli_num_rows($cpCheck) == 0) {
    mysqli_query($conn, "ALTER TABLE `purchase` ADD COLUMN `custpaid` double NOT NULL DEFAULT 0");
}

// Auto-add salesman column to purchase table if not yet present
$smCheck = mysqli_query($conn, "SHOW COLUMNS FROM `purchase` LIKE 'salesman'");
if ($smCheck && mysqli_num_rows($smCheck) == 0) {
    mysqli_query($conn, "ALTER TABLE `purchase` ADD COLUMN `salesman` int(11) NOT NULL DEFAULT 0");
}

// Auto-add calby column to purchasetr if not yet present
$cbCheck = mysqli_query($conn, "SHOW COLUMNS FROM `purchasetr` LIKE 'calby'");
if ($cbCheck && mysqli_num_rows($cbCheck) == 0) {
    mysqli_query($conn, "ALTER TABLE `purchasetr` ADD COLUMN `calby` varchar(10) NOT NULL DEFAULT 'weight' AFTER `modelno`");
}

// Auto-add new dimension + metric columns to stockledger
$slMigrations = [
    'customer' => "bigint NOT NULL DEFAULT 0",
    'supplier' => "bigint NOT NULL DEFAULT 0",
    'ctn'      => "double NOT NULL DEFAULT 0",
    'tcbm'     => "double NOT NULL DEFAULT 0",
    'tweight'  => "double NOT NULL DEFAULT 0",
];
foreach ($slMigrations as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `stockledger` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0) {
        mysqli_query($conn, "ALTER TABLE `stockledger` ADD COLUMN `$col` $def");
    }
}

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

$_upPurchase = upload_path('purchase');
$uploaddir   = $_upPurchase['dir'];
$uploadurl   = $_upPurchase['url'];

const PURCHASE_IMAGE_MAXSIZE = 512000; // 500 KB

// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vouchdt     = mysqli_real_escape_string($conn, trim($_POST["vouchdt"]));
    $supplier    = isset($_POST["supplier"])    ? (int)$_POST["supplier"]    : 0;
    $customer    = isset($_POST["customer"])    ? (int)$_POST["customer"]    : 0;
    $godown      = isset($_POST["godown"])      ? (int)$_POST["godown"]      : 0;
    $shipmarka   = mysqli_real_escape_string($conn, trim($_POST["shipmarka"]));
    $remarks     = mysqli_real_escape_string($conn, trim($_POST["remarks"]));
    $custpaid    = isset($_POST["custpaid"]) && $_POST["custpaid"] !== '' ? (float)$_POST["custpaid"] : 0;
    // Salesman: staff always use own agentcode; supervisor/admin can pick any
    $salesman    = ($usertype == 3) ? $agentcode : (int)($_POST["salesman"] ?? $agentcode);

    $descA   = isset($_POST['description']) ? $_POST['description'] : [];
    $modelA  = isset($_POST['modelno'])      ? $_POST['modelno']      : [];
    $calbyA  = isset($_POST['calby'])        ? $_POST['calby']        : [];
    $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']      : [];

    $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 && $supplier <= 0) {
        $a = 0;
        browse("Please Select Supplier");
        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");
    }

    if ($a == 1 && $godown <= 0) {
        $a = 0;
        browse("Please Select Godown");
        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]) : '';
            $calby = isset($calbyA[$i]) && in_array($calbyA[$i], ['qty','weight']) ? $calbyA[$i] : 'weight';
            $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 > PURCHASE_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', 'jpeg', 'png', 'gif', 'webp'];
                    $ext = strtolower(pathinfo($nm, PATHINFO_EXTENSION));

                    if (!in_array($ext, $allowedExt)) {
                        $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;
                        }
                    }
                }
            } elseif (!$hasUpload && $oldpic == '') {
                // No file upload and no existing pic — check if a base64 image was passed
                $imgb64Arr = isset($_POST['imgb64']) ? $_POST['imgb64'] : [];
                $b64 = isset($imgb64Arr[$i]) ? trim($imgb64Arr[$i]) : '';
                if ($b64 !== '') {
                    if (preg_match('/^data:image\/(\w+);base64,/', $b64, $bm)) {
                        $bext = $bm[1] === 'jpeg' ? 'jpg' : $bm[1];
                        $bdata = base64_decode(preg_replace('/^data:image\/\w+;base64,/', '', $b64));
                    } else {
                        $bext = 'png';
                        $bdata = base64_decode($b64);
                    }
                    if ($bdata !== false && strlen($bdata) > 100) {
                        $bname = 'purch_' . $qvouch . '_' . ($i + 1) . '_' . time() . '.' . $bext;
                        if (file_put_contents($uploaddir . $bname, $bdata) !== false) {
                            $picname = $bname;
                        }
                    }
                }
            }

            if ($desc == '' && $model == '' && $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,
                'calby'       => $calby,
                '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");
        }
    }

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

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

            mysqli_query($conn, "DELETE FROM `purchasetr` 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']);
            $cb  = mysqli_real_escape_string($conn, $ln['calby']);
            mysqli_query($conn, "INSERT INTO `purchasetr`
                (`vouchno`,`picfile`,`description`,`modelno`,`calby`,
                 `ctn`,`qty`,`tqty`,`rate`,`amt`,`cbm`,`tcbm`,`weight`,`tweight`)
                VALUES
                ('$qvouch','$pic','$d','$mo','$cb',
                 '{$ln['ctn']}','{$ln['qty']}','{$ln['tqty']}','{$ln['rate']}','{$ln['amt']}',
                 '{$ln['cbm']}','{$ln['tcbm']}','{$ln['weight']}','{$ln['tweight']}')")
            or die(mysqli_error($conn));
        }

        // ── Posting to stockledger (stock-in) ─────────────────────────────────
        mysqli_query($conn, "DELETE FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
        foreach ($lines as $ln) {
            $ctnIn    = (float)($ln['ctn']     ?? 0);
            $tcbmIn   = (float)($ln['tcbm']    ?? 0);
            $tweightIn= (float)($ln['tweight'] ?? 0);
            $tqtyIn   = (float)$ln['tqty'];
            if ($ctnIn <= 0) continue;   // skip rows with no CTN
            $d  = mysqli_real_escape_string($conn, $ln['description']);
            $mo = mysqli_real_escape_string($conn, $ln['modelno']);
            $mk = mysqli_real_escape_string($conn, isset($ln['marka']) ? $ln['marka'] : '');
            mysqli_query($conn, "INSERT INTO `stockledger`
                (`vouchdt`,`source`,`vouchno`,`godown`,`customer`,`supplier`,`description`,`modelno`,`marka`,`qty`,`ctn`,`tcbm`,`tweight`)
                VALUES ('$vd','$source','$qvouch','$godown','$customer','$supplier','$d','$mo','$mk','$tqtyIn','$ctnIn','$tcbmIn','$tweightIn')")
            or die(mysqli_error($conn));
        }

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

// ── Fetch record ─────────────────────────────────────────────────────────────
$get   = [];
$lines = [];
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 `purchasetr` WHERE `vouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_array($tres)) {
        $lines[] = $r;
    }
}

// Lookup names for supplier / 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'] : '';
}
$suppliername = isset($get['supplier']) ? acc_name($conn, $get['supplier']) : '';
$customername = isset($get['customer']) ? acc_name($conn, $get['customer']) : '';

// Account lists for Supplier (grpcode 009) and Customer (grpcode 010) 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;
}
$supplierList = acc_list($conn, '009');
$customerList = acc_list($conn, '010');
$godownList = [];
$gres = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` WHERE `country`='China' ORDER BY `name` ASC");
if ($gres) { while ($grow = mysqli_fetch_assoc($gres)) { $godownList[] = $grow; } }

// Agent (salesman) list
$agentList = [];
$ares = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `grpcode`='040' AND `accode`>50 ORDER BY `name`");
if ($ares) while ($r = mysqli_fetch_assoc($ares)) $agentList[] = $r;

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

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    // Safety check: don't delete if stock from this purchase has already been despatched
    // (i.e. would make stock for this description/godown go negative)
    $stockChk = mysqli_query($conn, "SELECT `description`,`godown`, SUM(`qty`) AS bal FROM `stockledger`
                                       WHERE `description` IN (SELECT `description` FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch')
                                       AND `godown` IN (SELECT `godown` FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch')
                                       GROUP BY `description`,`godown`") or die(mysqli_error($conn));
    $thisVouchQty = mysqli_query($conn, "SELECT `description`,`godown`,`qty` FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    $wouldGoNegative = false;
    $thisRows = [];
    while ($tr = mysqli_fetch_assoc($thisVouchQty)) { $thisRows[] = $tr; }
    $balMap = [];
    mysqli_data_seek($stockChk, 0);
    while ($br = mysqli_fetch_assoc($stockChk)) { $balMap[$br['description'] . '|' . $br['godown']] = (float)$br['bal']; }
    foreach ($thisRows as $tr) {
        $key = $tr['description'] . '|' . $tr['godown'];
        $currentBal = isset($balMap[$key]) ? $balMap[$key] : 0;
        if ($currentBal - (float)$tr['qty'] < -0.005) { $wouldGoNegative = true; break; }
    }

    if ($wouldGoNegative) {
        browse("Cannot Delete: Stock From This Purchase Has Already Been Despatched");
        header("refresh:1; url=$file?mode=edit&vouchno=$qvouch");
        exit;
    }

    $tres = mysqli_query($conn, "SELECT `picfile` FROM `purchasetr` 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 `purchasetr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `stockledger` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `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("$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;
    }
    .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-layout:fixed; min-width:1050px; }
    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 td:has(input.desc-inp) { max-width:120px; overflow:hidden; }
    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; }

    /* ── 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 { 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; }
    }
</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-plus" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <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" style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr 1fr;gap:9px 14px;">
            <div class="fl">
                <span class="lbl">Supplier <span style="color:#ef4444;">*</span></span>
                <select name="supplier" id="supplier" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Supplier --</option>
                    <?php foreach ($supplierList as $row): ?>
                    <option value="<?php echo (int)$row['accode']; ?>" <?php echo (fv($get,'supplier') == $row['accode']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($row['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <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">Godown <span style="color:#ef4444;">*</span></span>
                <select name="godown" id="godown" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Godown --</option>
                    <?php foreach ($godownList as $row): ?>
                    <option value="<?php echo (int)$row['code']; ?>" <?php echo (fv($get,'godown') == $row['code']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($row['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Salesman</span>
                <?php
                // Staff: locked to own agent; supervisor/admin: dropdown
                $curSalesman = (int)(fv($get,'salesman',0) ?: ($agentcode ?: 0));
                if ($usertype == 3): ?>
                <input type="hidden" name="salesman" value="<?php echo $agentcode; ?>">
                <?php
                $selfName = '';
                foreach ($agentList as $ag) { if ((int)$ag['accode'] == $agentcode) { $selfName = $ag['name']; break; } }
                ?>
                <input type="text" class="finp" value="<?php echo htmlspecialchars($selfName ?: 'My Account'); ?>" readonly style="background:#f1f5f9;color:#64748b;">
                <?php else: ?>
                <select name="salesman" class="finp form select2" style="width:100%;">
                    <option value="0">-- None --</option>
                    <?php foreach ($agentList as $ag): ?>
                    <option value="<?php echo (int)$ag['accode']; ?>" <?php echo ($curSalesman==(int)$ag['accode'])?'selected':''; ?>><?php echo htmlspecialchars($ag['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
            </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>

        <!-- ── Summary strip ─────────────────────────────────────────────────── -->
        <div style="margin:14px 0 10px;padding:14px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;">
            <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:10px;">
                <i class="fa fa-layer-group" style="margin-right:5px;color:#6366f1;"></i>Summary
            </div>
            <div style="margin-bottom:10px;">
                <span style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:4px;">Description</span>
                <textarea id="sum_description" rows="2" readonly tabindex="-1"
                    style="width:100%;box-sizing:border-box;padding:6px 10px;font-size:12px;
                           background:#fff;border:1px solid #e2e8f0;border-radius:6px;
                           color:#1e293b;resize:none;font-family:inherit;line-height:1.5;"></textarea>
            </div>
            <div style="display:grid;grid-template-columns:repeat(8,1fr);gap:8px;">
                <?php
                $sumFields = [
                    ['id'=>'sum_ctn',     'label'=>'CTN'],
                    ['id'=>'sum_qty',     'label'=>'QTY'],
                    ['id'=>'sum_tqty',    'label'=>'T.QTY'],
                    ['id'=>'sum_amt',     'label'=>'AMT'],
                    ['id'=>'sum_cbm',     'label'=>'CBM'],
                    ['id'=>'sum_tcbm',    'label'=>'T.CBM'],
                    ['id'=>'sum_weight',  'label'=>'Weight'],
                    ['id'=>'sum_tweight', 'label'=>'T.Weight'],
                ];
                foreach ($sumFields as $sf): ?>
                <div>
                    <span style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:3px;"><?php echo $sf['label']; ?></span>
                    <input type="text" id="<?php echo $sf['id']; ?>" readonly tabindex="-1"
                        style="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;">
                </div>
                <?php endforeach; ?>
            </div>
            <div style="margin-top:10px;display:flex;align-items:center;gap:10px;max-width:280px;">
                <span style="font-size:11px;font-weight:700;color:#64748b;white-space:nowrap;">Customer Paid</span>
                <input type="number" step="any" name="custpaid" id="custpaid" class="finp form"
                    style="text-align:right;font-weight:700;"
                    placeholder="0.00"
                    value="<?php echo fvn($get,'custpaid'); ?>">
            </div>
        </div>
        <!-- ── End Summary strip ─────────────────────────────────────────────── -->

        <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:3%;">#</th>
                        <th style="width:2%;"></th>
                        <th style="width:5%;">Goods Pic</th>
                        <th style="text-align:left;width:9%;">Description</th>
                        <th style="width:9%;text-align:left;">Model No.</th>
                        <th style="width:6%;text-align:right;">CTN</th>
                        <th style="width:7%;text-align:right;">QTY</th>
                        <th style="width:7%;text-align:right;">T.QTY</th>
                        <th style="width:7%;text-align:right;">CBM</th>
                        <th style="width:8%;text-align:right;">T.CBM</th>
                        <th style="width:7%;text-align:right;">Weight</th>
                        <th style="width:8%;text-align:right;">T.Weight</th>
                        <th style="width:7%;text-align:center;">Cal By</th>
                        <th style="width:7%;text-align:right;">Rate</th>
                        <th style="width:8%;text-align:right;">T.Amount</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" oninput="recalc()"></td>
                        <td><input type="text" name="modelno[]" class="txt-inp form" value="<?php echo fv($ln,'modelno'); ?>"></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="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>
                        <td>
                            <select name="calby[]" class="form calby-sel" onchange="onCalcInput(this)" style="width:100%;padding:5px 4px;font-size:11.5px;border:1px solid #e2e8f0;border-radius:5px;background:#f8fafc;font-family:inherit;">
                                <option value="weight" <?php echo (fv($ln,'calby','weight') === 'weight') ? 'selected' : ''; ?>>Weight</option>
                                <option value="qty"    <?php echo (fv($ln,'calby','weight') === 'qty')    ? 'selected' : ''; ?>>Qty</option>
                            </select>
                        </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>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" 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 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>
                        <td></td>
                        <td></td>
                        <td id="t_amt" 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>

        <?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" oninput="recalc()"></td>
        <td><input type="text" name="modelno[]" 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="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>
        <td>
            <select name="calby[]" class="form calby-sel" onchange="onCalcInput(this)" style="width:100%;padding:5px 4px;font-size:11.5px;border:1px solid #e2e8f0;border-radius:5px;background:#f8fafc;font-family:inherit;">
                <option value="weight">Weight</option>
                <option value="qty">Qty</option>
            </select>
        </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>
    </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 / Supplier / 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;">Supplier</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 tweight = ctn * wt;

    // Cal By: use tqty or tweight as the multiplier for amount
    var calbyEl = tr.querySelector('select[name="calby[]"]');
    var calby   = calbyEl ? calbyEl.value : 'weight';
    var amt     = (calby === 'qty' ? tqty : tweight) * rate;

    setVal('tqty',    tqty);
    setVal('tcbm',    tcbm);
    setVal('tweight', tweight);
    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};
    var descs = [];
    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;
        });
        var dinp = tr.querySelector('input[name="description[]"]');
        if (dinp && dinp.value.trim() !== '' && descs.indexOf(dinp.value.trim()) === -1) {
            descs.push(dinp.value.trim());
        }
    });
    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);

    // ── Update summary strip ─────────────────────────────────────────────────
    var fmtSum = function(v) { return v == 0 ? '' : Number(v.toFixed(3)).toString(); };
    document.getElementById('sum_description').value = descs.join('\n');
    document.getElementById('sum_ctn').value     = fmtSum(totals.ctn);
    document.getElementById('sum_qty').value     = fmtSum(totals.qty);
    document.getElementById('sum_tqty').value    = fmtSum(totals.tqty);
    document.getElementById('sum_amt').value     = fmtSum(totals.amt);
    document.getElementById('sum_cbm').value     = fmtSum(totals.cbm);
    document.getElementById('sum_tcbm').value    = fmtSum(totals.tcbm);
    document.getElementById('sum_weight').value  = fmtSum(totals.weight);
    document.getElementById('sum_tweight').value = fmtSum(totals.tweight);
}
recalc();
renumber();

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

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

// Re-enable file inputs just before form submits so $_FILES includes them
// (disabled inputs are excluded from POST, causing index mismatch with $_POST arrays)
document.getElementById('ssubmit').addEventListener('click', function (e) {
    // Re-enable ALL disabled .form inputs before POST so computed readonly fields are included
    document.querySelectorAll('input.form[disabled], select.form[disabled]').forEach(function (inp) {
        inp.disabled = false;
    });

    // ── Required field validation ────────────────────────────────────────────
    var errors = [];

    var vouchdt = document.getElementById('vouchdt');
    if (!vouchdt || !vouchdt.value) errors.push('Date is required');

    var supplier = document.getElementById('supplier');
    if (!supplier || !supplier.value) errors.push('Supplier is required');

    var customer = document.getElementById('customer');
    if (!customer || !customer.value) errors.push('Customer is required');

    var godown = document.getElementById('godown');
    if (!godown || !godown.value) errors.push('Godown is required');

    // At least one valid detail row (description filled)
    var hasRow = false;
    document.querySelectorAll('#dgrid tbody tr').forEach(function (tr) {
        var dinp = tr.querySelector('input[name="description[]"]');
        if (dinp && dinp.value.trim() !== '') hasRow = true;
    });
    if (!hasRow) errors.push('At least one item row with a Description is required');

    if (errors.length > 0) {
        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',
        });
    }
});
</script>

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