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

$formname  = 'Inward Entry';
$maindb    = 'inward';
$printfile = 'inward_print.php';
$file      = 'inward.php';
$keyfld    = 'vouchno';
$source    = 'INW';

$zdb       = $_SESSION["zdbyear_" . $dbname];
$compcd    = $_SESSION["comp_"    . $dbname];
$usertype  = (int)$_SESSION["usertype_" . $dbname];
$agentcode = (int)($_SESSION["agentcode_".$dbname] ?? 0);
$keycond   = ''; // Inward is not party/salesman scoped — all users see all entries

mysqli_select_db($conn, $zdb);

// ── Auto-create tables (self-contained, no separate migration needed) ─────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `inward` (
    `vouchno` INT(11) NOT NULL,
    `vouchdt` DATE NULL,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `remarks` VARCHAR(200) NOT NULL DEFAULT '',
    `totqty` DOUBLE NOT NULL DEFAULT 0,
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL,
    `addtime` TIME NULL,
    `edituser` VARCHAR(50) NOT NULL DEFAULT '',
    `editdate` DATE NULL,
    `edittime` TIME NULL,
    PRIMARY KEY (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));

// ── Migrate any missing columns onto an already-existing `inward` table ───
// (CREATE TABLE IF NOT EXISTS is a no-op when the table pre-dates this schema,
// so columns added later must be migrated in explicitly, same as `transacn` below.)
foreach ([
    'godown'    => "INT(11) NOT NULL DEFAULT 0",
    'remarks'   => "VARCHAR(200) NOT NULL DEFAULT ''",
    'totqty'    => "DOUBLE NOT NULL DEFAULT 0",
    'adduser'   => "VARCHAR(50) NOT NULL DEFAULT ''",
    'adddate'   => "DATE NULL",
    'addtime'   => "TIME NULL",
    'edituser'  => "VARCHAR(50) NOT NULL DEFAULT ''",
    'editdate'  => "DATE NULL",
    'edittime'  => "TIME NULL",
] as $_col => $_def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `inward` LIKE '$_col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `inward` ADD COLUMN `$_col` $_def");
}

// ── Fix columns that already exist on an older `inward` table but were
//    created NOT NULL with no default (e.g. edituser) — INSERTs that don't
//    set every column (adduser only, on new entries) then fail with
//    "Field 'edituser' doesn't have a default value". ────────────────────
$_fixRes = mysqli_query($conn, "SHOW COLUMNS FROM `inward`");
if ($_fixRes) {
    while ($_fc = mysqli_fetch_assoc($_fixRes)) {
        $_field = $_fc['Field'];
        if ($_field === 'vouchno') continue; // primary key, always supplied explicitly
        $_type = $_fc['Type'];
        if ($_fc['Null'] === 'NO' && $_fc['Default'] === null) {
            if (stripos($_type, 'char') !== false || stripos($_type, 'text') !== false) {
                @mysqli_query($conn, "ALTER TABLE `inward` MODIFY COLUMN `$_field` $_type NOT NULL DEFAULT ''");
            } elseif (stripos($_type, 'date') !== false || stripos($_type, 'time') !== false) {
                @mysqli_query($conn, "ALTER TABLE `inward` MODIFY COLUMN `$_field` $_type NULL DEFAULT NULL");
            } else {
                @mysqli_query($conn, "ALTER TABLE `inward` MODIFY COLUMN `$_field` $_type NOT NULL DEFAULT 0");
            }
        }
    }
}

mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `inwarddtl` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `product` INT(11) NOT NULL DEFAULT 0,
    `brand` INT(11) NOT NULL DEFAULT 0,
    `qty` DOUBLE NOT NULL DEFAULT 0,
    `stockqty` DOUBLE NOT NULL DEFAULT 0,
    PRIMARY KEY (`srl`),
    KEY `vouchno` (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));

// ── Migrate any missing columns onto an already-existing `inwarddtl` table ─
foreach ([
    'product'  => "INT(11) NOT NULL DEFAULT 0",
    'brand'    => "INT(11) NOT NULL DEFAULT 0",
    'qty'      => "DOUBLE NOT NULL DEFAULT 0",
    'stockqty' => "DOUBLE NOT NULL DEFAULT 0",
] as $_col => $_def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `inwarddtl` LIKE '$_col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `inwarddtl` ADD COLUMN `$_col` $_def");
}

// ── transacn (product stock ledger) — shared across all stock modules ─────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `transacn` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchdt` DATE NULL,
    `source` VARCHAR(10) NOT NULL DEFAULT '',
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `product` INT(11) NOT NULL DEFAULT 0,
    `qty` DOUBLE NOT NULL DEFAULT 0,
    `cost` DOUBLE NOT NULL DEFAULT 0,
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL,
    `addtime` TIME NULL,
    PRIMARY KEY (`srl`),
    KEY `vouchno` (`vouchno`),
    KEY `product` (`product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

foreach ([
    'godown'   => "INT(11) NOT NULL DEFAULT 0",
    'product'  => "INT(11) NOT NULL DEFAULT 0",
    'cost'     => "DOUBLE NOT NULL DEFAULT 0",
    'adduser'  => "VARCHAR(50) NOT NULL DEFAULT ''",
    'adddate'  => "DATE NULL",
    'addtime'  => "TIME NULL",
] as $_col => $_def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `transacn` LIKE '$_col'");
    if ($chk && mysqli_num_rows($chk) == 0) {
        try { mysqli_query($conn, "ALTER TABLE `transacn` ADD COLUMN `$_col` $_def"); }
        catch (Exception $e) { /* skip on strict-mode conflicts */ }
    }
}

// ── Defensive: godown / brand tables + brand column on product ────────────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `godown` (
    `code` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100) NOT NULL DEFAULT '',
    `country` VARCHAR(100) NOT NULL DEFAULT '',
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL, `addtime` TIME NULL,
    `edituser` VARCHAR(50) NOT NULL DEFAULT '',
    `editdate` DATE NULL, `edittime` TIME NULL,
    PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

foreach (['brand' => "VARCHAR(100) NOT NULL DEFAULT ''"] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `product` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `product` ADD COLUMN `$col` $def");
}
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `brand` (
    `code` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100) NOT NULL DEFAULT '',
    `country` VARCHAR(100) NOT NULL DEFAULT '',
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL, `addtime` TIME NULL,
    `edituser` VARCHAR(50) NOT NULL DEFAULT '',
    `editdate` DATE NULL, `edittime` TIME NULL,
    PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

$audituser = audituser();

$brandList = [];
$bres = mysqli_query($conn, "SELECT `code`,`name` FROM `brand` ORDER BY `name`") or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($bres)) $brandList[] = $r;

$productList = [];
$pres = mysqli_query($conn, "SELECT `id`,`name`,`brand` FROM `product` ORDER BY `name`") or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($pres)) $productList[] = $r;

$godownList = [];
$gres = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` ORDER BY `name`") or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($gres)) $godownList[] = $r;

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

    $prodA  = $_POST['product'] ?? [];
    $brandA = $_POST['brand']   ?? [];
    $qtyA   = $_POST['qty']     ?? [];

    $lines = []; $totqty = 0;
    foreach ($prodA as $i => $p) {
        $p     = (int)$p;
        $brand = (int)($brandA[$i] ?? 0);
        $qty   = (float)($qtyA[$i]  ?? 0);
        if ($p == 0 && $qty == 0) continue;
        $lines[] = ['product' => $p, 'brand' => $brand, 'qty' => $qty];
        $totqty += $qty;
    }

    // Stock-at-entry snapshot: balance before THIS voucher's own effect (excludes its own transacn rows)
    foreach ($lines as $k => $ln) {
        $prod = (int)$ln['product'];
        $sq = 0;
        if ($prod > 0) {
            $sqSql = "SELECT COALESCE(SUM(`qty`),0) AS q FROM `transacn` WHERE `product`='$prod' AND NOT (`source`='INW' AND `vouchno`='$qvouch')";
            if ($godown > 0) $sqSql .= " AND `godown`='$godown'";
            $sqRes = mysqli_query($conn, $sqSql);
            $sqRow = $sqRes ? mysqli_fetch_assoc($sqRes) : null;
            $sq = $sqRow ? (float)$sqRow['q'] : 0;
        }
        $lines[$k]['stockqty'] = $sq;
    }

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

    foreach ($lines as $ln) {
        mysqli_query($conn, "INSERT INTO `inwarddtl`
            (`vouchno`,`product`,`brand`,`qty`,`stockqty`)
            VALUES ('$qvouch','{$ln['product']}','{$ln['brand']}','{$ln['qty']}','{$ln['stockqty']}')")
        or die(mysqli_error($conn));
    }

    // ── Stock IN → transacn (idempotent delete+insert) ────────────────────
    mysqli_query($conn, "DELETE FROM `transacn` WHERE `source`='INW' AND `vouchno`='$qvouch'");
    foreach ($lines as $ln) {
        $prod = (int)$ln['product'];
        $qty  = (float)$ln['qty'];
        if ($prod > 0 && $qty != 0) {
            mysqli_query($conn, "INSERT INTO `transacn`
                (`vouchdt`,`source`,`vouchno`,`godown`,`product`,`qty`,`cost`,`adduser`,`adddate`,`addtime`)
                VALUES ('$vouchdt','INW','$qvouch','$godown','$prod','$qty','0','$audituser',CURDATE(),CURTIME())")
            or die(mysqli_error($conn));
        }
    }

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

// ── DELETE ────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    if ($usertype == 1) {
        mysqli_query($conn, "DELETE FROM `inwarddtl` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `transacn` WHERE `source`='INW' 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");
    } else {
        header("refresh:1; url=$file?mode=last");
    }
    exit;
}

function fv($a,$k,$d='') { return isset($a[$k]) ? htmlspecialchars($a[$k]) : $d; }
function fvn($a,$k)      { $v=(float)($a[$k]??0); return $v?$v:''; }

// ── Fetch ─────────────────────────────────────────────────────────────────
$get = []; $lines = [];
if ($addflag != 1 && $qvouch > 0) {
    $res = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch'");
    $get = mysqli_fetch_assoc($res) ?: [];
    $tr  = mysqli_query($conn, "SELECT d.*, d.brand AS pbrand
                                 FROM `inwarddtl` d
                                 WHERE d.`vouchno`='$qvouch' ORDER BY d.`srl`");
    while ($r = mysqli_fetch_assoc($tr)) $lines[] = $r;
}
if (!$lines) {
    $lines[] = ['product'=>0,'qty'=>'','pbrand'=>''];
}

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

include("includes/linkshead.php");
?>
<style>
body { background:#f0f2f5; padding:10px 14px; }
.sim-card { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08),0 4px 16px rgba(0,0,0,.06); overflow:hidden; }
.sim-card-header { background:#fff; border-bottom:2px solid #f1f5f9; padding:12px 20px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
.sim-card-header h2 { font-size:15px; font-weight:700; color:#1e293b; margin:0; }
.sim-badge { font-size:11.5px; font-weight:600; color:#64748b; background:#f1f5f9; padding:4px 12px; border-radius:20px; }
.sim-body { padding:16px 20px; }
.fr-grid { display:flex; flex-wrap:wrap; gap:0 20px; }
.fl { flex:1; min-width:200px; display:flex; flex-direction:column; margin-bottom:11px; }
.lbl { font-size:13px; font-weight:600; color:#374151; margin-bottom:4px; }
.finp { padding:8px 12px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:6px; font-size:13.5px; color:#1e293b; outline:none; width:100%; box-sizing:border-box; font-family:inherit; }
.finp:focus { background:#fff; border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
.finp.required-star { border-left:3px solid #3b82f6; }
.fl .select2-container { flex:1; }
.fl .select2-container .select2-selection--single { height:36px; border:1px solid #e2e8f0; border-radius:6px; background:#f8fafc; display:flex; align-items:center; }
.fl .select2-container--default .select2-selection--single .select2-selection__rendered { line-height:normal; font-size:13.5px; color:#1e293b; padding-left:12px; }
.fl .select2-container--default .select2-selection--single .select2-selection__arrow { height:34px; right:6px; }
.fl .select2-container--default.select2-container--focus .select2-selection--single { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
.sum-strip { margin:12px 0 10px; padding:14px 16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; display:flex; align-items:center; justify-content:flex-end; gap:16px; }
.sum-strip-lbl { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; }
.sum-fld label { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
.sum-fld input { width:140px; box-sizing:border-box; padding:6px 8px; font-size:13px; font-weight:700; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#15803d; text-align:right; font-family:inherit; }
.grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; margin-top:4px; }
table.dgrid { width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; min-width:650px; }
table.dgrid th { background:#1e293b; color:#e2e8f0; font-weight:700; font-size:10.5px; text-transform:uppercase; letter-spacing:.04em; padding:9px 6px; border-bottom:2px solid #334155; text-align:center; white-space:nowrap; overflow:hidden; }
table.dgrid th.num { text-align:right; }
table.dgrid td { padding:4px 4px; border-bottom:1px solid #f1f5f9; overflow:hidden; }
table.dgrid tbody tr:hover { background:#f8faff; }
table.dgrid input { width:100%; padding:5px 5px; font-size:12px; border:1px solid #e2e8f0; border-radius:4px; background:#fff; font-family:inherit; box-sizing:border-box; color:#1e293b; }
table.dgrid input:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
table.dgrid input[readonly] { background:#f8fafc; color:#64748b; border-color:#f1f5f9; }
table.dgrid input.numfld { text-align:right; }
table.dgrid input.stockqty-fld { text-align:right; }
table.dgrid td .select2-container { width:100% !important; }
table.dgrid td .select2-container .select2-selection--single { height:28px; border:1px solid #e2e8f0; border-radius:4px; background:#fff; display:flex; align-items:center; }
table.dgrid td .select2-container--default .select2-selection--single .select2-selection__rendered { line-height:normal; font-size:11.5px; color:#1e293b; padding-left:7px; padding-right:18px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
table.dgrid td .select2-container--default .select2-selection--single .select2-selection__arrow { height:26px; right:2px; width:14px; }
table.dgrid td .select2-container--default.select2-container--focus .select2-selection--single { border-color:#3b82f6; }
.row-del { background:#fee2e2; border:none; border-radius:4px; color:#dc2626; cursor:pointer; padding:4px 8px; font-size:12px; }
.row-del:hover { background:#fecaca; }
.row-del:disabled { opacity:.35; pointer-events:none; }
.add-row-btn { display:inline-flex; align-items:center; gap:6px; margin-top:10px; padding:8px 18px; background:#16a34a; color:#fff; border:none; border-radius:8px; font-size:12.5px; font-weight:600; cursor:pointer; }
.add-row-btn:disabled { opacity:.35; pointer-events:none; }
.audit-info { margin-top:10px; font-size:11px; color:#94a3b8; display:flex; gap:16px; flex-wrap:wrap; }
.btn-bar { display:flex; justify-content:center; align-items:center; gap:8px; padding:16px 20px; border-top:1px solid #f1f5f9; background:#fafafa; flex-wrap:wrap; }
.abtn { width:46px; height:46px; border-radius:10px; border:none; cursor:pointer; font-size:15px; color:#fff; display:inline-flex; align-items:center; justify-content:center; text-decoration:none; transition:transform .12s,box-shadow .12s; position:relative; }
.abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); }
.abtn[disabled] { opacity:.4; pointer-events:none; }
.abtn-prev{background:#2563eb;} .abtn-next{background:#38bdf8;} .abtn-search{background:#7f5539;} .abtn-print{background:#4a5759;} .abtn-add{background:#16a34a;} .abtn-edit{background:#ffba08;} .abtn-del{background:#e71d36;} .abtn-exit{background:#e2e8f0;color:#64748b;}
.abtn::after { content:attr(data-tip); position:absolute; bottom:calc(100% + 6px); left:50%; transform:translateX(-50%); background:#1e293b; color:#fff; font-size:10px; font-weight:600; padding:3px 8px; border-radius:4px; white-space:nowrap; opacity:0; pointer-events:none; transition:opacity .15s; }
.abtn:hover::after { opacity:1; }
.abtn-save { width:auto; padding:0 18px; background:#16a34a; gap:6px; font-size:12.5px; font-weight:600; }
.abtn-cancel { width:auto; padding:0 16px; background:#64748b; gap:6px; font-size:12.5px; font-weight:600; }
</style>
</head>
<body>
<form action="" method="POST">
<input type="hidden" name="submit" value="1">
<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-arrow-down" style="color:#16a34a;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <span class="sim-badge">Voucher No: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
    </div>

    <div class="sim-body">

        <div class="fr-grid">
            <div class="fl">
                <span class="lbl">Date <span style="color:#ef4444;">*</span></span>
                <input type="date" name="vouchdt" id="vouchdt" class="finp form focusfield required-star" value="<?php echo htmlspecialchars($vouchdt_val ?: date('Y-m-d')); ?>">
            </div>
            <div class="fl">
                <span class="lbl">Godown</span>
                <select name="godown" id="godown" class="finp form select2" 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">Remarks</span>
                <input type="text" name="remarks" class="finp form" maxlength="200" value="<?php echo fv($get,'remarks'); ?>">
            </div>
        </div>

        <!-- Detail grid -->
        <div class="grid-wrap">
        <table class="dgrid" id="dgrid">
            <thead>
                <tr>
                    <th style="width:5%;">Sr</th>
                    <th style="width:5%;"></th>
                    <th style="width:20%;text-align:left;">Brand</th>
                    <th style="width:40%;text-align:left;">Product</th>
                    <th class="num" style="width:14%;">Stock Qty</th>
                    <th class="num" style="width:16%;">Qty (In)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lines as $i => $ln): ?>
                <tr>
                    <td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;font-size:11px;"></td>
                    <td><button type="button" class="row-del form" onclick="delRow(this)"><i class="fa fa-times"></i></button></td>
                    <td>
                        <select name="brand[]" class="form brand-sel">
                            <option value="">-- All Brands --</option>
                            <?php foreach ($brandList as $b): ?>
                            <option value="<?php echo (int)$b['code']; ?>" <?php echo ((string)($ln['pbrand'] ?? '') === (string)$b['code']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($b['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td>
                        <select name="product[]" class="form product-sel">
                            <option value="">-- Select Product --</option>
                            <?php foreach ($productList as $p): ?>
                            <option value="<?php echo (int)$p['id']; ?>" data-brand="<?php echo htmlspecialchars($p['brand']); ?>" <?php echo ((int)($ln['product']??0)==$p['id'])?'selected':''; ?>><?php echo htmlspecialchars($p['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input type="text" class="stockqty-fld form" readonly tabindex="-1" value="<?php echo fvn($ln,'stockqty'); ?>"></td>
                    <td><input type="number" step="any" name="qty[]"  class="numfld form" value="<?php echo fvn($ln,'qty'); ?>"  oninput="recalc()"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>

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

        <!-- Total Qty -->
        <div class="sum-strip">
            <span class="sum-strip-lbl"><i class="fa fa-layer-group" style="margin-right:5px;color:#6366f1;"></i>Total Qty (In)</span>
            <div class="sum-fld">
                <input type="text" id="sum_totqty" readonly tabindex="-1">
            </div>
        </div>

        <?php if ($qvouch > 0 && (fv($get,'adduser') || fv($get,'edituser'))): ?>
        <div class="audit-info">
            <?php if (fv($get,'adduser')): ?><span><i class="fa fa-plus-circle"></i> Added by <b><?php echo fv($get,'adduser'); ?></b> on <?php echo fv($get,'adddate'); ?></span><?php endif; ?>
            <?php if (fv($get,'edituser')): ?><span><i class="fa fa-pencil"></i> Edited by <b><?php echo fv($get,'edituser'); ?></b> on <?php echo fv($get,'editdate'); ?></span><?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <div class="btn-bar">
        <button id="hprevious" type="button" class="abtn abtn-prev buttonform" data-tip="Previous" style="display:<?php echo $pdisabled; ?>;" <?php echo $pdisabled1; ?> onclick="window.location.href='<?php echo $file.'?mode=edit&'.$keyfld.'='.$prevvouch; ?>'"><i class="fa fa-chevron-left"></i></button>
        <button id="hnext"     type="button" class="abtn abtn-next buttonform" data-tip="Next"     style="display:<?php echo $ndisabled; ?>;" <?php echo $ndisabled1; ?> onclick="window.location.href='<?php echo $file.'?mode=edit&'.$keyfld.'='.$nextvouch; ?>'"><i class="fa fa-chevron-right"></i></button>
        <button id="hsearch"   type="button" class="abtn abtn-search buttonform" data-tip="Search" style="display:<?php echo $searchdisabled; ?>;" onclick="document.getElementById('searchModal').style.display='flex'"><i class="fa fa-search"></i></button>
        <button id="hprint"    type="button" class="abtn abtn-print buttonform" data-tip="Print"   style="display:<?php echo $printdisabled; ?>;" onclick="window.open('<?php echo $printfile.'?'.$keyfld.'='.$qvouch; ?>','_blank')"><i class="fa fa-print"></i></button>
        <button id="hadd"      type="button" class="abtn abtn-add buttonform"   data-tip="Add New" style="display:<?php echo $adddisabled; ?>;"   onclick="window.location.href='<?php echo $file.'?mode=true'; ?>'"><i class="fa fa-plus"></i></button>
        <button id="hedit"     type="button" class="abtn abtn-edit buttonform"  data-tip="Edit"    style="display:<?php echo $editdisabled; ?>;"><i class="fa fa-pencil"></i></button>
        <a      id="hdelete"                 class="abtn abtn-del buttonform"   data-tip="Delete"  style="display:<?php echo $deletedisabled; ?>;" href="javascript:void(0)" onclick="confirmDelete('?delete&<?php echo $keyfld.'='.$qvouch; ?>')"><i class="fa fa-trash"></i></a>
        <button id="hexit"     type="button" class="abtn abtn-exit buttonform"  data-tip="Exit"    style="display:<?php echo $exitdisabled; ?>;"   onclick="window.location.href='default.php'"><i class="fa fa-power-off"></i></button>
        <button id="ssubmit"   type="submit" class="abtn abtn-save buttonform"  style="display:<?php echo $savedisabled; ?>;"><i class="fa fa-check"></i> <?php echo ($addflag==1)?'Save':'Update'; ?></button>
        <button id="scancel"   type="button" class="abtn abtn-cancel buttonform" style="display:<?php echo $canceldisabled; ?>;" onclick="window.location.href='<?php echo $file.'?mode=last'; ?>'"><i class="fa fa-times"></i> Cancel</button>
    </div>
</div>
</form>

<!-- Search Modal -->
<div id="searchModal" style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:9999;align-items:flex-start;justify-content:center;padding-top:60px;">
    <div style="background:#fff;border-radius:12px;width:94%;max-width:700px;overflow:hidden;box-shadow:0 24px 64px rgba(0,0,0,.3);max-height:85vh;display:flex;flex-direction:column;">
        <div style="padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f1f5f9;">
            <span style="font-size:14px;font-weight:700;color:#1e293b;">Search <?php echo $formname; ?></span>
            <button type="button" style="background:#f1f5f9;border:none;color:#64748b;width:30px;height:30px;border-radius:6px;cursor:pointer;font-size:16px;" onclick="document.getElementById('searchModal').style.display='none'">&times;</button>
        </div>
        <div style="padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;gap:8px;background:#fafbfc;">
            <input type="text" id="srchInput" placeholder="Remarks..." style="flex:1;padding:7px 11px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;">
            <button type="button" id="srchGoBtn" style="padding:8px 18px;border-radius:6px;border:none;background:#2563eb;color:#fff;font-size:12.5px;font-weight:600;cursor:pointer;"><i class="fa fa-search"></i> Search</button>
        </div>
        <div style="overflow:auto;flex:1;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead><tr style="position:sticky;top:0;background:#f8fafc;">
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Voucher</th>
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Date</th>
                    <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Remarks</th>
                    <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Total Qty</th>
                </tr></thead>
                <tbody id="srchBody"></tbody>
            </table>
        </div>
        <div style="display:flex;border-top:1px solid #f1f5f9;">
            <button type="button" id="srchPrevBtn" style="flex:1;padding:10px;border:none;background:#f8fafc;font-size:12.5px;font-weight:600;cursor:pointer;border-right:1px solid #f1f5f9;"><i class="fa fa-chevron-left"></i> Previous</button>
            <span id="srchPageInfo" style="padding:10px 16px;font-size:12px;color:#64748b;white-space:nowrap;align-self:center;"></span>
            <button type="button" id="srchNextBtn" style="flex:1;padding:10px;border:none;background:#f8fafc;font-size:12.5px;font-weight:600;cursor:pointer;border-left:1px solid #f1f5f9;">Next <i class="fa fa-chevron-right"></i></button>
        </div>
    </div>
</div>

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

<script>
var ALL_BRANDS = <?php echo json_encode(array_map(function($b){
    return ['code'=>(int)$b['code'], 'name'=>$b['name']];
}, $brandList)); ?>;

var ALL_PRODUCTS = <?php echo json_encode(array_map(function($p){
    return ['id'=>(int)$p['id'], 'name'=>$p['name'], 'brand'=>$p['brand']];
}, $productList)); ?>;

function filterProductsForRow(tr) {
    var brandSel = tr.querySelector('.brand-sel');
    var prodSel  = tr.querySelector('.product-sel');
    if (!brandSel || !prodSel) return;
    var brand = brandSel.value;
    var keepVal = prodSel.value;
    var hasSel2 = !!$(prodSel).data('select2');
    if (hasSel2) $(prodSel).select2('destroy');

    var html = '<option value="">-- Select Product --</option>';
    var keepStillValid = false;
    ALL_PRODUCTS.forEach(function(p) {
        if (!brand || String(p.brand) === String(brand)) {
            var sel = (String(p.id) === String(keepVal)) ? ' selected' : '';
            if (sel) keepStillValid = true;
            html += '<option value="' + p.id + '" data-brand="' + (p.brand || '').replace(/"/g,'&quot;') + '"' + sel + '>' + escapeHtml(p.name) + '</option>';
        }
    });
    prodSel.innerHTML = html;
    if (!keepStillValid) prodSel.value = '';

    var editable = !document.getElementById('vouchdt').disabled;
    $(prodSel).select2({ dropdownAutoWidth:true, width:'100%', placeholder:'-- Select Product --', allowClear:false });
    $(prodSel).prop('disabled', !editable).trigger('change.select2');
}

function escapeHtml(s) {
    return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
        return { '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c];
    });
}

function initRowSelects(tr, isNewRow) {
    $(tr).find('select.brand-sel').each(function() {
        if (!$(this).data('select2')) {
            $(this).select2({ dropdownAutoWidth:true, width:'100%', placeholder:'-- All Brands --', allowClear:true });
        }
        var editable = !document.getElementById('vouchdt').disabled;
        $(this).prop('disabled', !editable).trigger('change.select2');
    });

    filterProductsForRow(tr);

    $(tr).find('select.brand-sel').off('change.brandfilter').on('change.brandfilter', function() {
        filterProductsForRow(tr);
        recalc();
    });

    $(tr).find('select.product-sel').off('change.stockqty').on('change.stockqty', function() {
        var godownEl = document.getElementById('godown');
        if (this.value && godownEl && !godownEl.value) {
            Swal.fire({ icon:'warning', title:'Select Godown First', text:'Please select a Godown before picking a product, so stock can be shown correctly.', confirmButtonColor:'#2563eb' });
            if ($(godownEl).data('select2')) { $(godownEl).select2('open'); } else { godownEl.focus(); }
        }
        fetchStockQty(tr);
    });

    // Skip the live stock lookup for rows that already have a saved product
    // + stock snapshot from the database (i.e. this is the initial render
    // of an existing entry) — Stock Qty should keep showing the figure that
    // was recorded at save time, not silently swap in today's current
    // stock. Freshly added rows, or a product change the user makes
    // (handled by the change.stockqty listener above), still fetch live.
    var prodSel = tr.querySelector('.product-sel');
    var hasExistingProduct = prodSel && prodSel.value;
    if (isNewRow || !hasExistingProduct) {
        fetchStockQty(tr);
    }
}

function fetchStockQty(tr) {
    var prodSel = tr.querySelector('.product-sel');
    var $stockFld = $(tr).find('.stockqty-fld');
    if (!prodSel || !prodSel.value) { $stockFld.val('').attr('placeholder',''); return; }
    var godownEl = document.getElementById('godown');
    var godown = godownEl ? godownEl.value : '';
    if (!godown) { $stockFld.val('').attr('placeholder','Select Godown'); return; }
    $stockFld.attr('placeholder','');
    $.post('includes/stock_lookup.php', { product: prodSel.value, godown: godown }, function(data) {
        $stockFld.val(data && data.success ? data.qty : '');
    }, 'json');
}

function refreshAllStockQty() {
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr){ fetchStockQty(tr); });
}

function buildRowHtml() {
    var brandOpts = '<option value="">-- All Brands --</option>';
    ALL_BRANDS.forEach(function(b) {
        brandOpts += '<option value="' + b.code + '">' + escapeHtml(b.name) + '</option>';
    });
    var prodOpts = '<option value="">-- Select Product --</option>';
    ALL_PRODUCTS.forEach(function(p) {
        prodOpts += '<option value="' + p.id + '" data-brand="' + (p.brand||'') + '">' + escapeHtml(p.name) + '</option>';
    });
    return '<tr>' +
        '<td class="srno" style="text-align:center;color:#94a3b8;font-weight:600;font-size:11px;"></td>' +
        '<td><button type="button" class="row-del form" onclick="delRow(this)"><i class=\'fa fa-times\'></i></button></td>' +
        '<td><select name="brand[]" class="form brand-sel">' + brandOpts + '</select></td>' +
        '<td><select name="product[]" class="form product-sel">' + prodOpts + '</select></td>' +
        '<td><input type="text" class="stockqty-fld form" readonly tabindex="-1" value=""></td>' +
        '<td><input type="number" step="any" name="qty[]" class="numfld form" oninput="recalc()"></td>' +
        '</tr>';
}

function addRow() {
    var tbody = document.querySelector('#dgrid tbody');
    tbody.insertAdjacentHTML('beforeend', buildRowHtml());
    var tr = tbody.rows[tbody.rows.length - 1];
    initRowSelects(tr, true);
    renumber();
}

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

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

function recalc() {
    var totQty = 0;
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
        var qtyInp = tr.querySelector('input[name="qty[]"]');
        var qty = qtyInp && qtyInp.value !== '' ? parseFloat(qtyInp.value) : 0;
        if (isNaN(qty)) qty = 0;
        totQty += qty;
    });
    var fmt = function(v){ return v==0?'':Number(v.toFixed(2)).toString(); };
    document.getElementById('sum_totqty').value = fmt(totQty);
}

// Validation + re-enable on submit
document.getElementById('ssubmit').addEventListener('click', function(e) {
    document.querySelectorAll('input.form[disabled], select.form[disabled]').forEach(function(inp){ inp.disabled=false; });
    var errors = [];
    if (!document.getElementById('vouchdt').value) errors.push('Date is required');
    var hasRow = false;
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr){
        var p = tr.querySelector('select[name="product[]"]');
        var q = tr.querySelector('input[name="qty[]"]');
        if (p && p.value && q && parseFloat(q.value||0) > 0) hasRow = true;
    });
    if (!hasRow) errors.push('At least one row with Product and Qty is required');
    if (errors.length) {
        e.preventDefault(); e.stopImmediatePropagation();
        Swal.fire({ icon:'warning', title:'Required Fields',
            html:'<ul style="text-align:left;padding-left:20px;margin:0;">'+errors.map(function(m){return '<li style="margin-bottom:4px;">'+m+'</li>';}).join('')+'</ul>',
            confirmButtonColor:'#2563eb' });
    }
});

// hedit re-enable select2
$('#hedit').on('click', function() {
    setTimeout(function() {
        document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
            $(tr).find('select.product-sel').each(function(){ $(this).prop('disabled',false).trigger('change.select2'); });
        });
    }, 0);
});

// Search
var srchPage=1, srchPages=1;
function srchLoad(page) {
    srchPage = page;
    $.post('includes/inward_search.php', { search:$('#srchInput').val(), page:page }, function(data) {
        $('#srchBody').html(data.rows);
        srchPage=data.page; srchPages=data.pages;
        $('#srchPageInfo').text('Page '+srchPage+' of '+srchPages+' ('+data.total+' records)');
        $('#srchPrevBtn').prop('disabled',srchPage<=1).css('opacity',srchPage<=1?.5:1);
        $('#srchNextBtn').prop('disabled',srchPage>=srchPages).css('opacity',srchPage>=srchPages?.5:1);
    },'json');
}
$('#srchGoBtn').on('click',function(){srchLoad(1);});
$('#srchInput').on('keyup',function(e){if(e.key==='Enter')srchLoad(1);});
$('#srchPrevBtn').on('click',function(){if(srchPage>1)srchLoad(srchPage-1);});
$('#srchNextBtn').on('click',function(){if(srchPage<srchPages)srchLoad(srchPage+1);});
document.getElementById('searchModal').addEventListener('click',function(e){if(e.target===this)this.style.display='none';});
document.getElementById('hsearch')&&document.getElementById('hsearch').addEventListener('click',function(){srchLoad(1);setTimeout(function(){document.getElementById('srchInput').focus();},60);});

renumber();
recalc();
$(function(){
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr){ initRowSelects(tr); });
    $('#godown').on('change', function(){ refreshAllStockQty(); });
});
</script>

</body>
</html>
