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

$formname = 'Bill Confirming';
$maindb = 'billconf';
$printfile = 'billconf_print.php';
$file = 'billconf.php';
$keyfld = 'vouchno';
$keycond = '';

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

mysqli_select_db($conn, $zdb);

// Auto-add picfile column to billconftr if not yet present
$colCheck = mysqli_query($conn, "SHOW COLUMNS FROM `billconftr` LIKE 'picfile'");
if ($colCheck && mysqli_num_rows($colCheck) == 0) {
    mysqli_query($conn, "ALTER TABLE `billconftr` ADD COLUMN `picfile` varchar(100) NOT NULL DEFAULT '' AFTER `vouchno`");
}

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

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

$_upBc   = upload_path('billconf');
$uploaddir = $_upBc['dir'];
$uploadurl = $_upBc['url'];
const BILLCONF_IMAGE_MAXSIZE = 512000; // 500 KB

// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vouchdt = mysqli_real_escape_string($conn, trim($_POST["vouchdt"]));
    $party = isset($_POST["party"]) ? (int) $_POST["party"] : 0;
    $supplier = isset($_POST["supplier"]) ? (int) $_POST["supplier"] : 0;
    $shipmark = mysqli_real_escape_string($conn, trim($_POST["shipmark"]));
    $origin = mysqli_real_escape_string($conn, trim($_POST["origin"]));
    $remarks = mysqli_real_escape_string($conn, trim($_POST["remarks"]));
    $advance = isset($_POST["advance"]) && $_POST["advance"] !== '' ? (float)$_POST["advance"] : 0;

    $descA = isset($_POST['description']) ? $_POST['description'] : [];
    $ctnA = isset($_POST['ctn']) ? $_POST['ctn'] : [];
    $qtyA = isset($_POST['qty']) ? $_POST['qty'] : [];
    $tqtyA = isset($_POST['tqty']) ? $_POST['tqty'] : [];
    $amtA = isset($_POST['amt']) ? $_POST['amt'] : [];
    $cbmA = isset($_POST['cbm']) ? $_POST['cbm'] : [];
    $wtA = isset($_POST['weight']) ? $_POST['weight'] : [];
    $picfileA = isset($_POST['picfile']) ? $_POST['picfile'] : [];
    // imgb64A: base64-encoded images from Excel import (new images not from file input)
    $imgb64A = isset($_POST['imgb64']) ? $_POST['imgb64'] : [];

    $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 ($party <= 0) {
        $a = 0;
        browse("Please Select Party");
        header("refresh:1; url=$file?mode=last");
    }

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

    // Build clean line rows (skip fully empty rows)
    $lines = [];
    $totctn = $totqty = $tottqty = $totamt = $totcbm = $totweight = 0;

    if ($a == 1) {
        $cnt = count($descA);
        for ($i = 0; $i < $cnt; $i++) {
            $desc = trim($descA[$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;
            $amt = isset($amtA[$i]) && $amtA[$i] !== '' ? (float) $amtA[$i] : 0;
            $cbm = isset($cbmA[$i]) && $cbmA[$i] !== '' ? (float) $cbmA[$i] : 0;
            $wt = isset($wtA[$i]) && $wtA[$i] !== '' ? (float) $wtA[$i] : 0;
            $oldpic = isset($picfileA[$i]) ? trim($picfileA[$i]) : '';

            if ($desc == '' && $ctn == 0 && $qty == 0 && $tqty == 0 && $amt == 0 && $cbm == 0 && $wt == 0) {
                continue;
            }

            // ── Image handling: file upload takes priority, then base64 from Excel ──
            $picname = $oldpic;
            $hasFileUpload = isset($_FILES['pic']['name'][$i]) && $_FILES['pic']['error'][$i] != UPLOAD_ERR_NO_FILE;

            if ($hasFileUpload) {
                $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 && $size <= BILLCONF_IMAGE_MAXSIZE) {
                    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                    $ext = strtolower(pathinfo($nm, PATHINFO_EXTENSION));
                    if (in_array($ext, $allowedExt)) {
                        $newname = 'bc_' . $qvouch . '_' . ($i + 1) . '_' . time() . '.' . $ext;
                        if (move_uploaded_file($tmp, $uploaddir . $newname)) {
                            if ($oldpic != '' && $oldpic != $newname && file_exists($uploaddir . $oldpic)) {
                                @unlink($uploaddir . $oldpic);
                            }
                            $picname = $newname;
                        }
                    }
                }
            } elseif (!$hasFileUpload && isset($imgb64A[$i]) && $imgb64A[$i] !== '') {
                // Save base64 image from Excel import
                $b64 = $imgb64A[$i];
                if (preg_match('/^data:image\/(\w+);base64,/', $b64, $match)) {
                    $ext = $match[1];
                    $imgdata = base64_decode(preg_replace('/^data:image\/\w+;base64,/', '', $b64));
                } else {
                    $ext = 'png';
                    $imgdata = base64_decode($b64);
                }
                if ($imgdata !== false && strlen($imgdata) > 0) {
                    $newname = 'bc_' . $qvouch . '_' . ($i + 1) . '_' . time() . '.' . $ext;
                    if (file_put_contents($uploaddir . $newname, $imgdata) !== false) {
                        if ($oldpic != '' && $oldpic != $newname && file_exists($uploaddir . $oldpic)) {
                            @unlink($uploaddir . $oldpic);
                        }
                        $picname = $newname;
                    }
                }
            }

            $lines[] = [
                'picfile'     => $picname,
                'description' => $desc,
                'ctn' => $ctn,
                'qty' => $qty,
                'tqty' => $tqty,
                'amt' => $amt,
                'cbm' => $cbm,
                'weight' => $wt,
            ];

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

        if (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`,`party`,`supplier`,`shipmark`,`origin`,`remarks`,
                 `totctn`,`totqty`,`tottqty`,`totamt`,`totcbm`,`totweight`,`advance`,
                 `adduser`,`adddate`,`addtime`)
                VALUES
                ('$qvouch','$vd','$party','$supplier','$shipmark','$origin','$remarks',
                 '$totctn','$totqty','$tottqty','$totamt','$totcbm','$totweight','$advance',
                 '$audituser',CURDATE(),CURTIME())")
                    or die(mysqli_error($conn));
        } else {
            mysqli_query($conn, "UPDATE `$maindb` SET
                `vouchdt`='$vd', `party`='$party', `supplier`='$supplier',
                `shipmark`='$shipmark', `origin`='$origin', `remarks`='$remarks',
                `totctn`='$totctn', `totqty`='$totqty', `tottqty`='$tottqty',
                `totamt`='$totamt', `totcbm`='$totcbm', `totweight`='$totweight', `advance`='$advance',
                `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
                WHERE `$keyfld`='$qvouch'")
                    or die(mysqli_error($conn));

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

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

            if ($origin == 'China') {
                // Self-provision `notifications` — see includes/notifications.php
                // for why this needs to exist before any insert/list against it.
                mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `notifications` (
                    `id` INT(11) NOT NULL AUTO_INCREMENT,
                    `vouchno` INT(11) NOT NULL DEFAULT 0,
                    `reftype` VARCHAR(20) NOT NULL DEFAULT '',
                    `audience` VARCHAR(30) NOT NULL DEFAULT '',
                    `action` VARCHAR(20) NOT NULL DEFAULT '',
                    `message` VARCHAR(255) NOT NULL DEFAULT '',
                    `readflag` VARCHAR(1) NOT NULL DEFAULT '',
                    `createduser` VARCHAR(50) NOT NULL DEFAULT '',
                    `createddate` DATE NULL,
                    `createdtime` TIME NULL,
                    PRIMARY KEY (`id`),
                    KEY `audience` (`audience`),
                    KEY `vouchno` (`vouchno`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                $vd_disp = date('d-m-Y', strtotime($vd));
                $msgChina = "New Bill Confirming voucher #$qvouch (Date: $vd_disp) added by " . mysqli_real_escape_string($conn, $audituser) . ". Please confirm or decline.";
                mysqli_query($conn, "INSERT INTO `notifications`
                    (`vouchno`,`reftype`,`audience`,`action`,`message`,`createduser`,`createddate`,`createdtime`)
                    VALUES ('$qvouch','billconf','china','pending','$msgChina','$audituser',CURDATE(),CURTIME())")
                        or die(mysqli_error($conn));

                $msgAdmin = "New Bill Confirming voucher #$qvouch (Date: $vd_disp, Origin: China) added by " . mysqli_real_escape_string($conn, $audituser) . ". Awaiting China team confirmation.";
                mysqli_query($conn, "INSERT INTO `notifications`
                    (`vouchno`,`reftype`,`audience`,`action`,`message`,`createduser`,`createddate`,`createdtime`)
                    VALUES ('$qvouch','billconf','admin','info','$msgAdmin','$audituser',CURDATE(),CURTIME())")
                        or die(mysqli_error($conn));
            }
        } 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 `billconftr` WHERE `vouchno`='$qvouch' ORDER BY `srl`") or die(mysqli_error($conn));
    while ($r = mysqli_fetch_array($tres)) {
        $lines[] = $r;
    }
}

// Lookup names for party / supplier (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'] : '';
}

$partyname = isset($get['party']) ? acc_name($conn, $get['party']) : '';
$suppliername = isset($get['supplier']) ? acc_name($conn, $get['supplier']) : '';

// Account lists for Party (Customer, grpcode 010) and Supplier (grpcode 009) 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;
}

$partyList = acc_list($conn, '010');
$supplierList = acc_list($conn, '009');

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

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    $picRes = mysqli_query($conn, "SELECT `picfile` FROM `billconftr` WHERE `vouchno`='$qvouch'");
    if ($picRes) {
        while ($pr = mysqli_fetch_assoc($picRes)) {
            if (!empty($pr['picfile']) && file_exists($uploaddir . $pr['picfile'])) {
                @unlink($uploaddir . $pr['picfile']);
            }
        }
    }
    mysqli_query($conn, "DELETE FROM `billconftr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    delmess("$file?mode=last");
    exit;
}

// 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-resp {
        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;
    }
    .btn-resp-confirm {
        background:#16a34a;
    }
    .btn-resp-confirm:hover {
        background:#15803d;
    }
    .btn-resp-decline {
        background:#dc2626;
    }
    .btn-resp-decline:hover {
        background:#b91c1c;
    }

    .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 {
        opacity:.45;
        cursor:not-allowed;
    }

    .grid-wrap {
        margin-top:16px;
        border:1px solid #e2e8f0;
        border-radius:8px;
        overflow:hidden;
    }
    table.dgrid {
        width:100%;
        border-collapse:collapse;
        font-size:12px;
        table-layout:fixed;
        min-width:900px;
    }
    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;
    }
    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 {
        text-align:left;
    }
    table.dgrid input:focus {
        background:#fff;
        border-color:#3b82f6;
    }
    table.dgrid tfoot td {
        background:#f8fafc;
        font-weight:700;
        color:#1e293b;
        padding:8px 6px;
        border-top:2px solid #e2e8f0;
    }
    .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;
    }

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

    /* ── 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:600px;
        }
        table.dgrid th, table.dgrid td {
            padding:5px 5px;
        }
        table.dgrid input {
            font-size:11px;
            padding:5px 4px;
        }

        .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 {
            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-file-invoice" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
                <div style="display:flex;gap:8px;align-items:center;">
                    <?php
                    if ($qvouch > 0):
                        $st = fv($get, 'status', 'Pending');
                        $stcolor = $st == 'Confirmed' ? '#16a34a' : ($st == 'Declined' ? '#dc2626' : '#f59e0b');
                        ?>
                        <span class="sim-badge" style="background:<?php echo $stcolor; ?>;color:#fff;"><?php echo htmlspecialchars($st); ?></span>
                    <?php endif; ?>
                    <span class="sim-badge">Voucher No: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
                    <?php
                    $userorigin = isset($_SESSION["origin_" . $dbname]) ? $_SESSION["origin_" . $dbname] : '';
                    if ($qvouch > 0 && $userorigin == 'China' && fv($get, 'status', 'Pending') == 'Pending'):
                        ?>
                        <button type="button" class="btn-resp btn-resp-confirm" data-vouchno="<?php echo $qvouch; ?>" data-decision="Confirmed">
                            <i class="fa fa-check"></i> Confirm
                        </button>
                        <button type="button" class="btn-resp btn-resp-decline" data-vouchno="<?php echo $qvouch; ?>" data-decision="Declined">
                            <i class="fa fa-times"></i> Decline
                        </button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="sim-body">

                <div class="fr" style="display:grid;grid-template-columns:1fr 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 Mark</span>
                        <input type="text" name="shipmark" class="finp form" maxlength="50"
                               value="<?php echo fv($get, 'shipmark'); ?>">
                    </div>
                    <div class="fl">
                        <span class="lbl">Origin</span>
                        <select name="origin" class="finp form">
                            <option value="">-- Select --</option>
                            <option value="India" <?php echo (fv($get, 'origin') == 'India') ? 'selected' : ''; ?>>India</option>
                            <option value="China" <?php echo (fv($get, 'origin') == 'China') ? 'selected' : ''; ?>>China</option>
                        </select>
                    </div>
                </div>

                <div class="fr fr-grid">
                    <div class="fl">
                        <span class="lbl" style="display:flex;align-items:center;justify-content:space-between;">
                            <span>Party Name <span style="color:#ef4444;">*</span></span>
                            <button type="button" class="form" onclick="openQuickCreate('customer')"
                                style="background:#2563eb;color:#fff;border:none;border-radius:5px;padding:1px 7px;font-size:11px;cursor:pointer;font-weight:600;line-height:18px;">
                                + New
                            </button>
                        </span>
                        <select name="party" id="party" class="finp form select2 required-star" style="width:100%;">
                            <option value="">-- Select Party --</option>
                            <?php foreach ($partyList as $row): ?>
                                <option value="<?php echo (int) $row['accode']; ?>" <?php echo (fv($get, 'party') == $row['accode']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($row['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fl">
                        <span class="lbl" style="display:flex;align-items:center;justify-content:space-between;">
                            <span>Supplier Name <span style="color:#ef4444;">*</span></span>
                            <button type="button" class="form" onclick="openQuickCreate('supplier')"
                                style="background:#7f5539;color:#fff;border:none;border-radius:5px;padding:1px 7px;font-size:11px;cursor:pointer;font-weight:600;line-height:18px;">
                                + New
                            </button>
                        </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">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(6,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_weight', 'label'=>'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:260px;">
                        <span style="font-size:11px;font-weight:700;color:#64748b;white-space:nowrap;">Advance</span>
                        <input type="number" step="any" name="advance" id="advance" class="finp form"
                            style="text-align:right;font-weight:700;"
                            placeholder="0.00"
                            value="<?php echo fvn($get,'advance'); ?>">
                    </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:4%;">#</th>
                                <th style="width:3%;"></th>
                                <th style="width:7%;">Image</th>
                                <th style="text-align:left;width:21%;">Description / Product</th>
                                <th style="width:10%;">CTN</th>
                                <th style="width:10%;">QTY</th>
                                <th style="width:11%;">T.QTY</th>
                                <th style="width:12%;">AMT</th>
                                <th style="width:11%;">CBM</th>
                                <th style="width:11%;">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 style="text-align:center;">
                                        <div style="position:relative;display:inline-block;">
                                            <?php if (!empty($ln['picfile'])): ?>
                                            <img class="pic-thumb" src="<?php echo $uploadurl . htmlspecialchars($ln['picfile']); ?>" alt=""
                                                style="width:44px;height:44px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;display:block;cursor:pointer;"
                                                onclick="this.nextElementSibling.nextElementSibling.click()">
                                            <?php else: ?>
                                            <div class="pic-thumb" style="width:44px;height:44px;background:#f1f5f9;border-radius:4px;border:1px solid #e2e8f0;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:18px;color:#94a3b8;"
                                                onclick="this.nextElementSibling.nextElementSibling.click()">
                                                <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/*" style="display:none;" onchange="picPreview(this)">
                                            <input type="hidden" name="imgb64[]" class="imgb64-inp" value="">
                                        </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="number" step="any" name="ctn[]" class="numfld form" value="<?php echo fvn($ln, 'ctn'); ?>" oninput="onQtyInput(this)"></td>
                                    <td><input type="number" step="any" name="qty[]" class="numfld form" value="<?php echo fvn($ln, 'qty'); ?>" oninput="onQtyInput(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="amt[]" class="numfld form" value="<?php echo fvn($ln, 'amt'); ?>" oninput="recalc()"></td>
                                    <td><input type="number" step="any" name="cbm[]" class="numfld form" value="<?php echo fvn($ln, 'cbm'); ?>" oninput="recalc()"></td>
                                    <td><input type="number" step="any" name="weight[]" class="numfld form" value="<?php echo fvn($ln, 'weight'); ?>" oninput="recalc()"></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4" 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_amt" style="text-align:right;"></td>
                                <td id="t_cbm" style="text-align:right;"></td>
                                <td id="t_weight" 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 ($addflag == 1): ?>
                <button type="button" class="add-row-btn form" onclick="document.getElementById('xlsxUploadInput').click()"
                    style="background:#0891b2;margin-left:8px;">
                    <i class="fa fa-file-excel"></i> Upload Excel
                </button>
                <input type="file" id="xlsxUploadInput" accept=".xlsx,.xls" style="display:none;" onchange="importExcel(this)">
                <?php endif; ?>

                <?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 style="text-align:center;">
                    <div style="position:relative;display:inline-block;">
                        <div class="pic-thumb" style="width:44px;height:44px;background:#f1f5f9;border-radius:4px;border:1px solid #e2e8f0;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:18px;color:#94a3b8;"
                            onclick="this.nextElementSibling.nextElementSibling.click()">
                            <i class="fa fa-image"></i>
                        </div>
                        <input type="hidden" name="picfile[]" value="">
                        <input type="file" name="pic[]" class="pic-input form" accept="image/*" style="display:none;" onchange="picPreview(this)">
                        <input type="hidden" name="imgb64[]" class="imgb64-inp" value="">
                    </div>
                </td>
                <td><input type="text" name="description[]" class="desc-inp form" list="productList" autocomplete="off" oninput="recalc()"></td>
                <td><input type="number" step="any" name="ctn[]" class="numfld form" oninput="onQtyInput(this)"></td>
                <td><input type="number" step="any" name="qty[]" class="numfld form" oninput="onQtyInput(this)"></td>
                <td><input type="number" step="any" name="tqty[]" class="numfld form" readonly tabindex="-1"></td>
                <td><input type="number" step="any" name="amt[]" class="numfld form" oninput="recalc()"></td>
                <td><input type="number" step="any" name="cbm[]" class="numfld form" oninput="recalc()"></td>
                <td><input type="number" step="any" name="weight[]" class="numfld form" oninput="recalc()"></td>
            </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 Mark / 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;">Party</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;">Ship Mark</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 {
                btn.closest('tr').querySelectorAll('input').forEach(function (i) {
                    i.value = '';
                });
                recalc();
            }
        }

        function calcTQty(tr) {
            var ctnInp = tr.querySelector('input[name="ctn[]"]');
            var qtyInp = tr.querySelector('input[name="qty[]"]');
            var tqtyInp = tr.querySelector('input[name="tqty[]"]');
            var ctn = ctnInp && ctnInp.value !== '' ? parseFloat(ctnInp.value) : 0;
            var qty = qtyInp && qtyInp.value !== '' ? parseFloat(qtyInp.value) : 0;
            if (isNaN(ctn))
                ctn = 0;
            if (isNaN(qty))
                qty = 0;
            if (tqtyInp) {
                var t = ctn * qty;
                tqtyInp.value = t ? t : '';
            }
        }

        function onQtyInput(input) {
            calcTQty(input.closest('tr'));
            recalc();
        }

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

        function recalc() {
            var cols = ['ctn', 'qty', 'tqty', 'amt', 'cbm', 'weight'];
            var totals = {ctn: 0, qty: 0, tqty: 0, amt: 0, cbm: 0, weight: 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_weight').textContent = fmt2(totals.weight);

            // ── 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_weight').value = fmtSum(totals.weight);
        }
        recalc();
        renumber();

        var srchPage = 1;
        var srchPages = 1;

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

        $('.btn-resp').on('click', function () {
            var $btn = $(this);
            var vouchno = $btn.data('vouchno');
            var decision = $btn.data('decision');
            var label = decision === 'Confirmed' ? 'confirm' : 'decline';

            Swal.fire({
                icon: 'question',
                title: 'Are you sure?',
                text: 'Do you want to ' + label + ' this Bill Confirming entry?',
                showCancelButton: true,
                confirmButtonColor: decision === 'Confirmed' ? '#16a34a' : '#dc2626',
                confirmButtonText: 'Yes, ' + label
            }).then(function (result) {
                if (result.isConfirmed) {
                    $.post('includes/notifications.php', {action: 'respond', vouchno: vouchno, decision: decision}, function (data) {
                        if (data.ok) {
                            location.reload();
                        } else {
                            Swal.fire({icon: 'error', title: 'Error', text: data.error || 'Could not update.'});
                        }
                    }, 'json');
                }
            });
        });

        // ── Image preview when file chosen manually ───────────────────────────────
        function picPreview(input) {
            if (!input.files || !input.files[0]) return;
            var reader = new FileReader();
            var td = input.closest('td');
            reader.onload = function (e) {
                var thumb = td.querySelector('.pic-thumb, img.pic-thumb');
                if (thumb && thumb.tagName === 'DIV') {
                    // Replace placeholder div with img
                    var img = document.createElement('img');
                    img.className = 'pic-thumb';
                    img.src = e.target.result;
                    img.style.cssText = 'width:44px;height:44px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;display:block;cursor:pointer;';
                    img.onclick = function () { input.click(); };
                    td.querySelector('div').replaceChild(img, thumb);
                } else if (thumb) {
                    thumb.src = e.target.result;
                }
                // Clear any existing base64 (file upload takes priority)
                var b64inp = td.querySelector('.imgb64-inp');
                if (b64inp) b64inp.value = '';
            };
            reader.readAsDataURL(input.files[0]);
        }

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

        // ── Excel Import (Add mode only) ─────────────────────────────────────────
        function importExcel(input) {
            if (!input || !input.files || !input.files[0]) return;
            var file = input.files[0];
            input.value = '';

            var formData = new FormData();
            formData.append('xlsxfile', file);

            Swal.fire({
                title: 'Reading Excel...',
                allowOutsideClick: false,
                didOpen: function () { Swal.showLoading(); }
            });

            $.ajax({
                url: 'includes/billconf_excel_import.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function (data) {
                    Swal.close();
                    if (!data.ok) {
                        Swal.fire({ icon: 'error', title: 'Error', text: data.error || 'Could not parse file.' });
                        return;
                    }
                    var rows = data.rows;
                    if (!rows || rows.length === 0) {
                        Swal.fire({ icon: 'warning', title: 'No Data', text: 'No valid rows found in the Excel file.' });
                        return;
                    }

                    Swal.fire({
                        icon: 'question',
                        title: 'Import ' + rows.length + ' rows?',
                        text: 'This will REPLACE all current detail rows with the Excel data.',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, Import',
                        cancelButtonText: 'Cancel',
                        confirmButtonColor: '#0891b2',
                    }).then(function (result) {
                        if (!result.isConfirmed) return;

                        // Clear existing rows
                        var tbody = document.querySelector('#dgrid tbody');
                        tbody.innerHTML = '';

                        var tpl = document.getElementById('rowTemplate').innerHTML;
                        rows.forEach(function (r) {
                            var tr = document.createElement('tr');
                            tr.innerHTML = tpl;

                            function setField(name, val) {
                                var inp = tr.querySelector('input[name="' + name + '[]"]');
                                if (inp && val !== '' && val !== null && val !== undefined) {
                                    inp.value = val;
                                }
                            }

                            setField('description', r.description);
                            setField('ctn',  r.ctn);
                            setField('qty',  r.qty);
                            setField('tqty', r.tqty);
                            setField('amt',  r.amt);
                            setField('cbm',  r.cbm);
                            setField('weight', r.weight);

                            // Inject image if present
                            if (r.image && r.image !== '') {
                                var td = tr.querySelector('td:nth-child(3)');
                                var wrapper = td.querySelector('div');

                                // Build img element
                                var img = document.createElement('img');
                                img.className = 'pic-thumb';
                                img.src = r.image;
                                img.style.cssText = 'width:44px;height:44px;object-fit:cover;border-radius:4px;border:1px solid #e2e8f0;display:block;cursor:pointer;';

                                // Replace placeholder div with img
                                var placeholder = wrapper.querySelector('.pic-thumb');
                                if (placeholder) wrapper.replaceChild(img, placeholder);

                                // Store base64 so it POSTs with the form
                                var b64inp = wrapper.querySelector('.imgb64-inp');
                                if (b64inp) b64inp.value = r.image;

                                img.onclick = function () {
                                    wrapper.querySelector('.pic-input').click();
                                };
                            }

                            tbody.appendChild(tr);
                        });

                        renumber();
                        recalc();

                        Swal.fire({ icon: 'success', title: rows.length + ' rows imported', timer: 1500, showConfirmButton: false });
                    });
                },
                error: function () {
                    Swal.close();
                    Swal.fire({ icon: 'error', title: 'Upload Error', text: 'Could not reach the server. Please try again.' });
                }
            });
        }
    </script>

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

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

<script>
var _qcType = '';

function openQuickCreate(type) {
    _qcType = type;
    document.getElementById('qcTitle').textContent = 'New ' + (type === 'customer' ? 'Customer (Party)' : 'Supplier');
    document.getElementById('qcSaveBtn').style.background = type === 'customer' ? '#2563eb' : '#7f5539';
    document.getElementById('qcName').value = '';
    document.getElementById('qcMobile').value = '';
    document.getElementById('qcError').style.display = 'none';
    document.getElementById('quickCreateModal').style.display = 'flex';
    setTimeout(function () { document.getElementById('qcName').focus(); }, 60);
}

function closeQuickCreate() {
    document.getElementById('quickCreateModal').style.display = 'none';
}

function saveQuickCreate() {
    var name   = document.getElementById('qcName').value.trim();
    var mobile = document.getElementById('qcMobile').value.trim();
    var errEl  = document.getElementById('qcError');

    if (!name) {
        errEl.textContent = 'Name is required.';
        errEl.style.display = 'block';
        document.getElementById('qcName').focus();
        return;
    }

    var btn = document.getElementById('qcSaveBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Saving...';
    errEl.style.display = 'none';

    $.post('includes/quick_create_account.php', { type: _qcType, name: name, mobile: mobile }, function (data) {
        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-check"></i> Save';

        if (!data.ok) {
            errEl.textContent = data.error || 'Could not save.';
            errEl.style.display = 'block';
            return;
        }

        // Add the new option to the correct select and auto-select it
        var selId = _qcType === 'customer' ? 'party' : 'supplier';
        var $sel  = $('#' + selId);
        var newOpt = new Option(data.name, data.accode, true, true);
        $sel.append(newOpt).trigger('change');

        closeQuickCreate();
        Swal.fire({ icon: 'success', title: data.name + ' added!', timer: 1200, showConfirmButton: false });
    }, 'json').fail(function () {
        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-check"></i> Save';
        errEl.textContent = 'Server error. Please try again.';
        errEl.style.display = 'block';
    });
}

// Close on backdrop click
document.getElementById('quickCreateModal').addEventListener('click', function (e) {
    if (e.target === this) closeQuickCreate();
});
</script>
</body>
</html>
