<?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  = 'Sale GST Invoice';
$maindb    = 'salegst';
$printfile = 'salegst_pdf.php';
$file      = 'salegst.php';
$keyfld    = 'vouchno';
$source    = 'SLTX';

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

mysqli_select_db($conn, $zdb);

require_once("includes/upload_path.php");
$_upSaleGst = upload_path('salegst');
$uploaddir  = $_upSaleGst['dir'];
$uploadurl  = $_upSaleGst['url'];

// ── Defensive: ensure header table exists ───────────────────────────────────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `salegst` (
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `vouchdt` DATE NULL,
    `customer` INT(11) NOT NULL DEFAULT 0,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `salesman` INT(11) NOT NULL DEFAULT 0,
    `remarks` VARCHAR(100) NOT NULL DEFAULT '',
    `tottqty` DOUBLE NOT NULL DEFAULT 0,
    `subtotal` DOUBLE NOT NULL DEFAULT 0,
    `totdiscamt` DOUBLE NOT NULL DEFAULT 0,
    `taxableamt` DOUBLE NOT NULL DEFAULT 0,
    `totgstamt` DOUBLE NOT NULL DEFAULT 0,
    `totcgst` DOUBLE NOT NULL DEFAULT 0,
    `totsgst` DOUBLE NOT NULL DEFAULT 0,
    `totigst` DOUBLE NOT NULL DEFAULT 0,
    `packingcharges` DOUBLE NOT NULL DEFAULT 0,
    `transport_charges` DOUBLE NOT NULL DEFAULT 0,
    `other_charges` DOUBLE NOT NULL DEFAULT 0,
    `totamt` 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");

// ── Defensive: ensure detail table exists ───────────────────────────────────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `salegsttr` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `description` VARCHAR(150) NOT NULL DEFAULT '',
    `product` INT(11) NOT NULL DEFAULT 0,
    `brand` INT(11) NOT NULL DEFAULT 0,
    `hsncode` VARCHAR(20) NOT NULL DEFAULT '',
    `tqty` DOUBLE NOT NULL DEFAULT 0,
    `cost` DOUBLE NOT NULL DEFAULT 0,
    `amt` DOUBLE NOT NULL DEFAULT 0,
    `discpercent` DOUBLE NOT NULL DEFAULT 0,
    `discamt` DOUBLE NOT NULL DEFAULT 0,
    `gstpercent` DOUBLE NOT NULL DEFAULT 0,
    `gstamt` DOUBLE NOT NULL DEFAULT 0,
    `cgstamt` DOUBLE NOT NULL DEFAULT 0,
    `sgstamt` DOUBLE NOT NULL DEFAULT 0,
    `igstamt` DOUBLE NOT NULL DEFAULT 0,
    `netamt` DOUBLE NOT NULL DEFAULT 0,
    `stockqty` DOUBLE NOT NULL DEFAULT 0,
    PRIMARY KEY (`srl`),
    KEY `vouchno` (`vouchno`),
    KEY `product` (`product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// ── Defensive auto-migrate: ensure hsncode column exists on salegsttr for
// installs where the table was created before this column was added ────────
$chkHsnTr = mysqli_query($conn, "SHOW COLUMNS FROM `salegsttr` LIKE 'hsncode'");
if ($chkHsnTr && mysqli_num_rows($chkHsnTr) == 0)
    mysqli_query($conn, "ALTER TABLE `salegsttr` ADD COLUMN `hsncode` VARCHAR(20) NOT NULL DEFAULT ''");
// ── Defensive auto-migrate: CGST/SGST/IGST split columns (header + detail) ──
foreach (['totcgst', 'totsgst', 'totigst'] as $_col) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `salegst` LIKE '$_col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `salegst` ADD COLUMN `$_col` DOUBLE NOT NULL DEFAULT 0");
}
foreach (['cgstamt', 'sgstamt', 'igstamt'] as $_col) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `salegsttr` LIKE '$_col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `salegsttr` ADD COLUMN `$_col` DOUBLE NOT NULL DEFAULT 0");
}

// ── Defensive: ensure godown master table exists (shared with Sale Invoice) ─
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");
// ── Defensive: ensure brand column on product + brand master table exist ──
foreach ([
    'brand'      => "VARCHAR(100) NOT NULL DEFAULT ''",
    'gstpercent' => "DOUBLE NOT NULL DEFAULT 0",
    'hsncode'    => "VARCHAR(20) 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");

function acc_list($conn, $grpcode, $salesmanFilter = 0) {
    $list = [];
    $cond = ($salesmanFilter > 0) ? " AND `salesman`='" . (int)$salesmanFilter . "'" : '';
    $r = mysqli_query($conn, "SELECT `accode`,`name`,`salesman`,`statecode` FROM `accmast` WHERE `grpcode`='$grpcode' AND `accode`>50 $cond ORDER BY `name`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $list[] = $row;
    return $list;
}

// ── Interstate/Intrastate GST determination ─────────────────────────────────
// Company Setup (company.php) has a dedicated State Code field now — use it
// when set. Older installs / companies that haven't filled it in yet fall
// back to the first two digits of the GSTIN, which is the official GST TIN
// numbering scheme (state code is always the first two characters of any
// GSTIN). The customer's state code comes straight from Customer master
// (accmast.statecode, populated from the `state` master list). When the two
// differ, the sale is interstate and attracts IGST; otherwise it's
// intrastate and the tax splits evenly into CGST + SGST.
$companyStateCode = '';
$compGstRes = mysqli_query($conn, "SELECT `gstno`,`statecode` FROM `$dbname`.`company` WHERE `code`='$compcd'");
if ($compGstRes && ($compGstRow = mysqli_fetch_assoc($compGstRes))) {
    $companyStateCode = trim($compGstRow['statecode'] ?? '');
    if ($companyStateCode === '') {
        $companyStateCode = substr(trim($compGstRow['gstno'] ?? ''), 0, 2);
    }
}
$companyStateCodeEsc = mysqli_real_escape_string($conn, $companyStateCode);

// ── One-time self-healing backfill ──────────────────────────────────────────
// Invoices saved before the CGST/SGST/IGST columns existed have them sitting
// at their default 0 even though gstamt is populated, so they print/PDF as
// blank. Backfill any row still at 0/0/0 with a positive gstamt, using the
// exact same interstate rule as the live save path above (customer statecode
// blank, or company GSTIN unknown, both fall back to intrastate CGST+SGST —
// never IGST — matching $isInterstate's default below). Harmless to re-run
// on every page load: once a row is backfilled it's no longer 0/0/0.
mysqli_query($conn, "UPDATE `salegsttr` t
    INNER JOIN `salegst` s ON s.`vouchno` = t.`vouchno`
    LEFT JOIN `accmast` a ON a.`accode` = s.`customer`
    SET
        t.`cgstamt` = IF(TRIM(COALESCE(a.`statecode`,'')) <> '' AND '$companyStateCodeEsc' <> '' AND TRIM(a.`statecode`) <> '$companyStateCodeEsc', 0, ROUND(t.`gstamt`/2, 2)),
        t.`sgstamt` = IF(TRIM(COALESCE(a.`statecode`,'')) <> '' AND '$companyStateCodeEsc' <> '' AND TRIM(a.`statecode`) <> '$companyStateCodeEsc', 0, t.`gstamt` - ROUND(t.`gstamt`/2, 2)),
        t.`igstamt` = IF(TRIM(COALESCE(a.`statecode`,'')) <> '' AND '$companyStateCodeEsc' <> '' AND TRIM(a.`statecode`) <> '$companyStateCodeEsc', t.`gstamt`, 0)
    WHERE t.`cgstamt` = 0 AND t.`sgstamt` = 0 AND t.`igstamt` = 0 AND t.`gstamt` > 0");

mysqli_query($conn, "UPDATE `salegst` s
    SET
        s.`totcgst` = (SELECT COALESCE(SUM(`cgstamt`),0) FROM `salegsttr` WHERE `vouchno` = s.`vouchno`),
        s.`totsgst` = (SELECT COALESCE(SUM(`sgstamt`),0) FROM `salegsttr` WHERE `vouchno` = s.`vouchno`),
        s.`totigst` = (SELECT COALESCE(SUM(`igstamt`),0) FROM `salegsttr` WHERE `vouchno` = s.`vouchno`)
    WHERE s.`totcgst` = 0 AND s.`totsgst` = 0 AND s.`totigst` = 0 AND s.`totgstamt` > 0");

// Salesman login (usertype 3): only show customers linked to this salesman
$customerList = acc_list($conn, '010', ($usertype === 3 ? $agentcode : 0));
$audituser    = audituser();

// Brand master list (for line-item Brand filter)
$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;

// Product master list (for line-item dropdown) — includes brand + gst% + hsncode for auto-fill
$productList = [];
$pres = mysqli_query($conn, "SELECT `id`,`name`,`cost`,`brand`,`gstpercent`,`hsncode` FROM `product` ORDER BY `name`") or die(mysqli_error($conn));
while ($r = mysqli_fetch_assoc($pres)) $productList[] = $r;
$productById = [];
foreach ($productList as $p) $productById[(int)$p['id']] = $p;

// Godown master list (header-level)
$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;

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

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

    // Defense-in-depth: salesman login can only save invoices for their own linked customers
    if ($usertype === 3 && $agentcode > 0 && $customer > 0) {
        $chkc = mysqli_query($conn, "SELECT `accode` FROM `accmast` WHERE `accode`='$customer' AND `salesman`='$agentcode'");
        if (!$chkc || mysqli_num_rows($chkc) == 0) {
            errmess('Not allowed', 'This customer is not linked to your salesman account.', $file . '?mode=add');
            exit;
        }
    }

    // Interstate (IGST) vs intrastate (CGST+SGST) for this customer — see
    // note above on how $companyStateCode is derived.
    $customerStateCode = '';
    if ($customer > 0) {
        $custStateRes = mysqli_query($conn, "SELECT `statecode` FROM `accmast` WHERE `accode`='$customer'");
        if ($custStateRes && ($custStateRow = mysqli_fetch_assoc($custStateRes))) {
            $customerStateCode = trim($custStateRow['statecode'] ?? '');
        }
    }
    $isInterstate = ($companyStateCode !== '' && $customerStateCode !== '' && $companyStateCode !== $customerStateCode);

    // Detail arrays
    $prodA   = $_POST['product']     ?? [];
    $brandA  = $_POST['brand']       ?? [];
    $tqtyA   = $_POST['tqty']        ?? [];
    $costA   = $_POST['cost']        ?? [];
    $discpA  = $_POST['discpercent'] ?? [];
    $discaA  = $_POST['discamt']     ?? [];
    $gstpA   = $_POST['gstpercent']  ?? [];
    $hsnA    = $_POST['hsncode']     ?? [];

    $vd = $vouchdt;

    $lines = []; $tottqty = $subtotal = $totdiscamt = $taxabletotal = $totgstamt = 0;
    $totcgst = $totsgst = $totigst = 0;
    foreach ($prodA as $i => $prod) {
        $prod  = (int)$prod;
        $brand = (int)($brandA[$i] ?? 0);
        $tqty  = (float)($tqtyA[$i] ?? 0);
        $cost  = (float)($costA[$i] ?? 0);
        if ($prod == 0 && $tqty == 0) continue;

        $amt = $tqty * $cost;

        // Discount: percent is the source of truth when supplied; otherwise
        // fall back to a directly-entered discount amount.
        $discpercent = (float)($discpA[$i] ?? 0);
        $discamt     = (float)($discaA[$i] ?? 0);
        if ($amt > 0 && $discpercent > 0) {
            $discamt = round($amt * $discpercent / 100, 2);
        } elseif ($amt > 0 && $discamt > 0) {
            $discpercent = round($discamt / $amt * 100, 4);
        } else {
            $discpercent = 0; $discamt = 0;
        }
        if ($discamt > $amt) { $discamt = $amt; }

        $taxable = $amt - $discamt;

        // GST%: auto-filled from product master client-side, editable per line
        $gstpercent = (float)($gstpA[$i] ?? ($prod > 0 && isset($productById[$prod]) ? $productById[$prod]['gstpercent'] : 0));
        $gstamt     = round($taxable * $gstpercent / 100, 2);
        $netamt     = $taxable + $gstamt;

        // CGST/SGST/IGST split — see $isInterstate above.
        if ($isInterstate) {
            $cgstamt = 0; $sgstamt = 0; $igstamt = $gstamt;
        } else {
            $cgstamt = round($gstamt / 2, 2);
            $sgstamt = round($gstamt - $cgstamt, 2);
            $igstamt = 0;
        }

        $desc = $prod > 0 && isset($productById[$prod]) ? $productById[$prod]['name'] : '';

        // HSN Code: auto-filled from product master client-side, editable per line
        $hsncode = mysqli_real_escape_string($conn, trim($hsnA[$i] ?? ($prod > 0 && isset($productById[$prod]) ? $productById[$prod]['hsncode'] : '')));

        $lines[] = [
            'description' => $desc,
            'product'     => $prod,
            'brand'       => $brand,
            'hsncode'     => $hsncode,
            'tqty'        => $tqty,
            'cost'        => $cost,
            'amt'         => $amt,
            'discpercent' => $discpercent,
            'discamt'     => $discamt,
            'gstpercent'  => $gstpercent,
            'gstamt'      => $gstamt,
            'cgstamt'     => $cgstamt,
            'sgstamt'     => $sgstamt,
            'igstamt'     => $igstamt,
            'netamt'      => $netamt,
        ];
        $tottqty      += $tqty;
        $subtotal     += $amt;
        $totdiscamt   += $discamt;
        $taxabletotal += $taxable;
        $totgstamt    += $gstamt;
        $totcgst      += $cgstamt;
        $totsgst      += $sgstamt;
        $totigst      += $igstamt;
    }
    $totamt = $taxabletotal + $totgstamt + $packingcharges + $transport_charges + $other_charges;

    // 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`='$source' 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`,`customer`,`godown`,`salesman`,`remarks`,
             `tottqty`,`subtotal`,`totdiscamt`,`taxableamt`,`totgstamt`,`totcgst`,`totsgst`,`totigst`,
             `packingcharges`,`transport_charges`,`other_charges`,`totamt`,
             `adduser`,`adddate`,`addtime`)
            VALUES
            ('$qvouch','$vd','$customer','$godown','$salesman','$remarks',
             '$tottqty','$subtotal','$totdiscamt','$taxabletotal','$totgstamt','$totcgst','$totsgst','$totigst',
             '$packingcharges','$transport_charges','$other_charges','$totamt',
             '$audituser',CURDATE(),CURTIME())")
        or die(mysqli_error($conn));
    } else {
        mysqli_query($conn, "UPDATE `$maindb` SET
            `vouchdt`='$vd', `customer`='$customer', `godown`='$godown', `salesman`='$salesman',
            `remarks`='$remarks',
            `tottqty`='$tottqty', `subtotal`='$subtotal', `totdiscamt`='$totdiscamt',
            `taxableamt`='$taxabletotal', `totgstamt`='$totgstamt',
            `totcgst`='$totcgst', `totsgst`='$totsgst', `totigst`='$totigst',
            `packingcharges`='$packingcharges', `transport_charges`='$transport_charges', `other_charges`='$other_charges',
            `totamt`='$totamt',
            `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
            WHERE `$keyfld`='$qvouch'")
        or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `salegsttr` WHERE `vouchno`='$qvouch'");
    }

    foreach ($lines as $ln) {
        $d = mysqli_real_escape_string($conn, $ln['description']);
        mysqli_query($conn, "INSERT INTO `salegsttr`
            (`vouchno`,`description`,`product`,`brand`,`hsncode`,`tqty`,`cost`,`amt`,
             `discpercent`,`discamt`,`gstpercent`,`gstamt`,`cgstamt`,`sgstamt`,`igstamt`,`netamt`,`stockqty`)
            VALUES ('$qvouch','$d','{$ln['product']}','{$ln['brand']}','{$ln['hsncode']}','{$ln['tqty']}','{$ln['cost']}','{$ln['amt']}',
             '{$ln['discpercent']}','{$ln['discamt']}','{$ln['gstpercent']}','{$ln['gstamt']}','{$ln['cgstamt']}','{$ln['sgstamt']}','{$ln['igstamt']}','{$ln['netamt']}','{$ln['stockqty']}')")
        or die(mysqli_error($conn));
    }

    // ── transacn stock OUT (delete+reinsert for idempotency on edit) ─────
    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");
    mysqli_query($conn, "DELETE FROM `transacn` WHERE `source`='$source' AND `vouchno`='$qvouch'");
    foreach ($lines as $ln) {
        $prod = (int)$ln['product'];
        $qty  = (float)$ln['tqty'];
        $cost = (float)$ln['cost'];
        if ($prod > 0 && $qty != 0) {
            $negQty = $qty * -1;
            mysqli_query($conn, "INSERT INTO `transacn`
                (`vouchdt`,`source`,`vouchno`,`godown`,`product`,`qty`,`cost`,`adduser`,`adddate`,`addtime`)
                VALUES ('$vd','$source','$qvouch','$godown','$prod','$negQty','$cost','$audituser',CURDATE(),CURTIME())");
        }
    }

    // ── Actran: Dr customer / Cr Sales for the GST-inclusive grand total.
    // Kept as a single Sales-account credit line (same simplified model the
    // regular Sale Invoice uses) rather than splitting out a separate GST
    // payable ledger, since no such account is defined in this install.
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'");
    if ($totamt > 0) {
        $dr = $totamt * -1;
        mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                                          VALUES ('$vd','$vd','$qvouch','$source','001','$customer','010','$dr','1','$dr','','$dr','Sale GST Invoice')") or die(mysqli_error($conn));
        mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`feamt`,`roe`,`amount`,`prodtype`,`actamt`,`narr`)
                                          VALUES ('$vd','$vd','$qvouch','$source','002','15','005','$totamt','1','$totamt','','$totamt','Sale GST Invoice')") 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"])) {
    // Only Admin can delete — double-check server-side
    if ($usertype != 1) {
        header("refresh:1; url=$file?mode=last");
        exit;
    }
    mysqli_query($conn, "DELETE FROM `salegsttr` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `transacn` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    delmess("$file?mode=last");
    exit;
}

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 t.*, t.brand AS pbrand
                                 FROM `salegsttr` t
                                 WHERE t.`vouchno`='$qvouch' ORDER BY t.`srl`");
    while ($r = mysqli_fetch_assoc($tr)) $lines[] = $r;
}
if (!$lines) {
    $lines[] = ['description'=>'','product'=>0,'tqty'=>'','cost'=>'','amt'=>'','discpercent'=>'','discamt'=>'','gstpercent'=>'','gstamt'=>'','netamt'=>'','pbrand'=>'','hsncode'=>''];
}

$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); }

/* Grid */
.grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; margin-top:4px; }
table.dgrid { width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; min-width:1180px; }
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 tfoot td { font-weight:700; background:#f1f5f9; border-top:2px solid #e2e8f0; text-align:right; font-size:12px; padding:7px 5px; color:#1e293b; }
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.desc-td { max-width:150px; }
/* Select2 in dgrid */
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; }
.sum-strip-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(130px,1fr)); gap:8px; max-width:100%; }
.sum-fld-lbl { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
.sum-fld-ro { width:100%; box-sizing:border-box; padding:6px 8px; font-size:13px; font-weight:700; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#1e293b; text-align:right; font-family:inherit; }
.sum-fld-in { width:100%; box-sizing:border-box; padding:6px 8px; font-size:13px; font-weight:700; background:#fff; border:1px solid #93c5fd; border-radius:6px; color:#1e293b; text-align:right; font-family:inherit; }
</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-file-invoice-dollar" style="color:#f59e0b;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">Customer <span style="color:#ef4444;">*</span></span>
                <select name="customer" id="customer" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Customer --</option>
                    <?php foreach ($customerList as $row): ?>
                    <option value="<?php echo (int)$row['accode']; ?>" data-salesman="<?php echo (int)($row['salesman'] ?? 0); ?>" data-statecode="<?php echo htmlspecialchars($row['statecode'] ?? ''); ?>" <?php echo (fv($get,'customer')==$row['accode'])?'selected':''; ?>><?php echo htmlspecialchars($row['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Godown</span>
                <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">Salesman</span>
                <?php
                $curSalesman = (int)(fv($get,'salesman',0) ?: ($agentcode ?: 0));
                if ($usertype == 3): ?>
                <input type="hidden" name="salesman" value="<?php echo $agentcode; ?>">
                <?php
                $selfName = '';
                foreach ($agentList as $ag) { if ((int)$ag['accode'] == $agentcode) { $selfName = $ag['name']; break; } }
                ?>
                <input type="text" class="finp" value="<?php echo htmlspecialchars($selfName ?: 'My Account'); ?>" readonly style="background:#f1f5f9;color:#64748b;">
                <?php else: ?>
                <select name="salesman" id="salesman" class="finp form select2" style="width:100%;">
                    <option value="0">-- None --</option>
                    <?php foreach ($agentList as $ag): ?>
                    <option value="<?php echo (int)$ag['accode']; ?>" <?php echo ($curSalesman==(int)$ag['accode'])?'selected':''; ?>><?php echo htmlspecialchars($ag['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
            </div>
            <div class="fl">
                <span class="lbl">Remarks</span>
                <input type="text" name="remarks" class="finp form" maxlength="100" value="<?php echo fv($get,'remarks'); ?>">
            </div>
        </div>

        <!-- Detail grid -->
        <div class="grid-wrap">
        <table class="dgrid" id="dgrid">
            <thead>
                <tr>
                    <th style="width:2%;">#</th>
                    <th style="width:2%;"></th>
                    <th style="width:9%;text-align:left;">Brand</th>
                    <th style="width:17%;text-align:left;">Product</th>
                    <th style="width:7%;text-align:left;">HSN Code</th>
                    <th class="num" style="width:6%;">Stock Qty</th>
                    <th class="num" style="width:6%;">Qty</th>
                    <th class="num" style="width:6%;">Rate</th>
                    <th class="num" style="width:7%;">Amount</th>
                    <th class="num" style="width:6%;">Disc %</th>
                    <th class="num" style="width:7%;">Disc Amt</th>
                    <th class="num" style="width:6%;">GST %</th>
                    <th class="num" style="width:7%;">GST Amt</th>
                    <th class="num" style="width:9%;">Net Amt</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-cost="<?php echo htmlspecialchars($p['cost']); ?>" data-brand="<?php echo htmlspecialchars($p['brand']); ?>" data-gst="<?php echo htmlspecialchars($p['gstpercent']); ?>" data-hsn="<?php echo htmlspecialchars($p['hsncode']); ?>" <?php echo ((int)($ln['product']??0)==$p['id'])?'selected':''; ?>><?php echo htmlspecialchars($p['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input type="text" name="hsncode[]" class="form hsn-fld" value="<?php echo fv($ln,'hsncode'); ?>"></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="tqty[]" class="numfld form" value="<?php echo fvn($ln,'tqty'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="cost[]" class="numfld form" value="<?php echo fvn($ln,'cost'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="amt[]"  class="numfld form" value="<?php echo fvn($ln,'amt'); ?>"  readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="discpercent[]" class="numfld form discp-fld" value="<?php echo fvn($ln,'discpercent'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="discamt[]" class="numfld form" value="<?php echo fvn($ln,'discamt'); ?>" readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="gstpercent[]" class="numfld form gstp-fld" value="<?php echo fvn($ln,'gstpercent'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="gstamt[]" class="numfld form" value="<?php echo fvn($ln,'gstamt'); ?>" readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="netamt[]" class="numfld form" value="<?php echo fvn($ln,'netamt'); ?>" readonly tabindex="-1"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="6" style="text-align:right;font-size:11px;color:#64748b;">Total</td>
                    <td id="t_tqty"></td>
                    <td></td>
                    <td id="t_amt"></td>
                    <td></td>
                    <td id="t_discamt"></td>
                    <td></td>
                    <td id="t_gstamt"></td>
                    <td id="t_netamt"></td>
                </tr>
            </tfoot>
        </table>
        </div>

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

        <!-- Charges / Net Amount -->
        <div class="sum-strip" style="margin-top:12px;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>Totals</div>
            <div class="sum-strip-grid">
                <div>
                    <label class="sum-fld-lbl">Gross Amount</label>
                    <input type="text" id="sum_gross" readonly tabindex="-1" class="sum-fld-ro">
                </div>
                <div>
                    <label class="sum-fld-lbl">Total Discount</label>
                    <input type="text" id="sum_disc" readonly tabindex="-1" class="sum-fld-ro">
                </div>
                <div>
                    <label class="sum-fld-lbl">Total GST</label>
                    <input type="text" id="sum_gst" readonly tabindex="-1" class="sum-fld-ro">
                </div>
                <div>
                    <label class="sum-fld-lbl">Subtotal</label>
                    <input type="text" id="sum_subtotal" readonly tabindex="-1" class="sum-fld-ro">
                </div>
                <div>
                    <label class="sum-fld-lbl">Packing Charges</label>
                    <input type="number" step="any" name="packingcharges" id="packingcharges" class="form sum-fld-in" value="<?php echo fvn($get,'packingcharges'); ?>" oninput="recalc()">
                </div>
                <div>
                    <label class="sum-fld-lbl">Transport Charges</label>
                    <input type="number" step="any" name="transport_charges" id="transport_charges" class="form sum-fld-in" value="<?php echo fvn($get,'transport_charges'); ?>" oninput="recalc()">
                </div>
                <div>
                    <label class="sum-fld-lbl">Other Charges</label>
                    <input type="number" step="any" name="other_charges" id="other_charges" class="form sum-fld-in" value="<?php echo fvn($get,'other_charges'); ?>" oninput="recalc()">
                </div>
                <div>
                    <label class="sum-fld-lbl">Net Amount</label>
                    <input type="text" id="sum_netamount" readonly tabindex="-1" class="sum-fld-ro" style="color:#15803d;">
                </div>
            </div>
        </div>

        <!-- GST Rate-wise Breakup: when line items carry different GST%, break the
             single "Total GST" figure down per rate (5%, 12%, 18% etc.) so the
             invoice shows how much taxable value and GST falls under each slab. -->
        <div class="gst-breakup-strip" style="margin-top:12px;padding:14px 16px;background:#fffbeb;border:1px solid #fde68a;border-radius:8px;">
            <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:10px;">
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#92400e;"><i class="fa fa-percent" style="margin-right:5px;color:#d97706;"></i>GST Rate-wise Breakup</div>
                <span id="gstTaxTypeBadge" style="font-size:10.5px;font-weight:700;color:#78350f;background:#fef3c7;border:1px solid #fde68a;padding:3px 10px;border-radius:20px;"></span>
            </div>
            <table style="width:100%;border-collapse:collapse;font-size:12.5px;">
                <thead>
                    <tr>
                        <th style="padding:6px 8px;text-align:center;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">GST %</th>
                        <th style="padding:6px 8px;text-align:right;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">Taxable Amount</th>
                        <th style="padding:6px 8px;text-align:right;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">CGST</th>
                        <th style="padding:6px 8px;text-align:right;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">SGST</th>
                        <th style="padding:6px 8px;text-align:right;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">IGST</th>
                        <th style="padding:6px 8px;text-align:right;font-size:11px;font-weight:700;color:#78350f;background:#fef3c7;border-bottom:1px solid #fde68a;">Total GST</th>
                    </tr>
                </thead>
                <tbody id="gstBreakupBody">
                    <tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:8px;">No items yet</td></tr>
                </tbody>
                <tfoot>
                    <tr style="font-weight:700;">
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;">Total</td>
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;" id="bk_taxable_total">0.00</td>
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;" id="bk_cgst_total">0.00</td>
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;" id="bk_sgst_total">0.00</td>
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;" id="bk_igst_total">0.00</td>
                        <td style="padding:6px 8px;text-align:right;color:#78350f;background:#fef3c7;" id="bk_gst_total">0.00</td>
                    </tr>
                </tfoot>
            </table>
        </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="Customer / 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;">Customer</th>
                    <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;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;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>
// Company's GST state code (first two digits of its GSTIN) — used client-side
// to preview whether the invoice is interstate (IGST) or intrastate
// (CGST+SGST), matching the same rule salegst.php applies server-side on save.
var COMPANY_STATECODE = <?php echo json_encode($companyStateCode); ?>;

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'], 'cost'=>$p['cost'], 'brand'=>$p['brand'], 'gst'=>$p['gstpercent'], 'hsn'=>$p['hsncode']];
}, $productList)); ?>;

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

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-cost="' + p.cost + '" data-brand="' + (p.brand || '').replace(/"/g,'&quot;') + '" data-gst="' + (p.gst || 0) + '" data-hsn="' + (p.hsn || '').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 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.autocost').on('change.autocost', function() {
        var opt = this.options[this.selectedIndex];
        var cost = opt ? (opt.getAttribute('data-cost') || '') : '';
        var gst  = opt ? (opt.getAttribute('data-gst')  || '') : '';
        var hsn  = opt ? (opt.getAttribute('data-hsn')  || '') : '';
        var $costInp = $(tr).find('input[name="cost[]"]');
        if (cost !== '' && parseFloat(cost) > 0) { $costInp.val(cost); }
        // Auto-fill GST% from product master whenever a product is (re)selected.
        var $gstpInp = $(tr).find('input[name="gstpercent[]"]');
        $gstpInp.val(gst !== '' ? gst : 0);
        // Auto-fill HSN Code from product master whenever a product is (re)selected.
        var $hsnInp = $(tr).find('input[name="hsncode[]"]');
        $hsnInp.val(hsn || '');
        recalc();
        // Auto-add a fresh blank row once a product is picked in the last
        // row, so entry can continue without clicking "Add Row" each time.
        if (this.value) {
            var tbody = document.querySelector('#dgrid tbody');
            if (tr === tbody.rows[tbody.rows.length - 1]) { addRow(); }
        }
    });
    $(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-cost="' + p.cost + '" data-brand="' + (p.brand||'') + '" data-gst="' + (p.gst||0) + '" data-hsn="' + (p.hsn||'') + '">' + 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" name="hsncode[]" class="form hsn-fld" value=""></td>' +
        '<td><input type="text" class="stockqty-fld form" readonly tabindex="-1" value=""></td>' +
        '<td><input type="number" step="any" name="tqty[]" class="numfld form" oninput="recalc()"></td>' +
        '<td><input type="number" step="any" name="cost[]" class="numfld form" oninput="recalc()"></td>' +
        '<td><input type="number" step="any" name="amt[]" class="numfld form" readonly tabindex="-1"></td>' +
        '<td><input type="number" step="any" name="discpercent[]" class="numfld form discp-fld" oninput="recalc()"></td>' +
        '<td><input type="number" step="any" name="discamt[]" class="numfld form" readonly tabindex="-1"></td>' +
        '<td><input type="number" step="any" name="gstpercent[]" class="numfld form gstp-fld" oninput="recalc()"></td>' +
        '<td><input type="number" step="any" name="gstamt[]" class="numfld form" readonly tabindex="-1"></td>' +
        '<td><input type="number" step="any" name="netamt[]" class="numfld form" readonly tabindex="-1"></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 totAmt = 0, totQty = 0, totDisc = 0, totGst = 0, totNet = 0;
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
        var qtyInp   = tr.querySelector('input[name="tqty[]"]');
        var costInp  = tr.querySelector('input[name="cost[]"]');
        var amtInp   = tr.querySelector('input[name="amt[]"]');
        var discpInp = tr.querySelector('input[name="discpercent[]"]');
        var discaInp = tr.querySelector('input[name="discamt[]"]');
        var gstpInp  = tr.querySelector('input[name="gstpercent[]"]');
        var gstaInp  = tr.querySelector('input[name="gstamt[]"]');
        var netInp   = tr.querySelector('input[name="netamt[]"]');

        var qty  = qtyInp  && qtyInp.value  !== '' ? parseFloat(qtyInp.value)  : 0;
        var cost = costInp && costInp.value !== '' ? parseFloat(costInp.value) : 0;
        if (isNaN(qty)) qty = 0;
        if (isNaN(cost)) cost = 0;
        var amt = qty * cost;
        if (amtInp) amtInp.value = amt ? amt.toFixed(2) : '';

        var discp = discpInp && discpInp.value !== '' ? parseFloat(discpInp.value) : 0;
        if (isNaN(discp)) discp = 0;
        var discamt = amt * discp / 100;
        if (discamt > amt) discamt = amt;
        if (discaInp) discaInp.value = discamt ? discamt.toFixed(2) : '';

        var taxable = amt - discamt;

        var gstp = gstpInp && gstpInp.value !== '' ? parseFloat(gstpInp.value) : 0;
        if (isNaN(gstp)) gstp = 0;
        var gstamt = taxable * gstp / 100;
        if (gstaInp) gstaInp.value = gstamt ? gstamt.toFixed(2) : '';

        var net = taxable + gstamt;
        if (netInp) netInp.value = net ? net.toFixed(2) : '';

        totAmt += amt; totQty += qty; totDisc += discamt; totGst += gstamt; totNet += net;
    });

    var fmt2 = function(v, el){ if (el) el.textContent = v ? v.toFixed(2) : ''; };
    fmt2(totQty, document.getElementById('t_tqty'));
    fmt2(totAmt, document.getElementById('t_amt'));
    fmt2(totDisc, document.getElementById('t_discamt'));
    fmt2(totGst, document.getElementById('t_gstamt'));
    fmt2(totNet, document.getElementById('t_netamt'));

    var packing   = parseFloat(document.getElementById('packingcharges').value    || 0) || 0;
    var transport = parseFloat(document.getElementById('transport_charges').value  || 0) || 0;
    var other     = parseFloat(document.getElementById('other_charges').value      || 0) || 0;
    var netamount = totNet + packing + transport + other;
    var fmt = function(v){ return v==0?'':Number(v.toFixed(2)).toString(); };
    var sg = document.getElementById('sum_gross');     if (sg) sg.value = fmt(totAmt);
    var sd = document.getElementById('sum_disc');      if (sd) sd.value = fmt(totDisc);
    var sx = document.getElementById('sum_gst');       if (sx) sx.value = fmt(totGst);
    var ss = document.getElementById('sum_subtotal');  if (ss) ss.value = fmt(totNet);
    var sn = document.getElementById('sum_netamount'); if (sn) sn.value = fmt(netamount);

    updateGstBreakup();
}

// GST Rate-wise Breakup: group the already-computed per-row Taxable/GST
// amounts by GST% so an invoice mixing multiple rates (e.g. 5% + 18%) shows
// how much falls under each slab, instead of only a single lumped total.
// Each slab's GST is further split into CGST+SGST (intrastate) or IGST
// (interstate) by comparing the selected customer's state code against the
// company's — same rule applied server-side in salegst.php on save.
function getSelectedCustomerStateCode() {
    var custSel = document.getElementById('customer');
    if (!custSel) return '';
    var opt = custSel.options[custSel.selectedIndex];
    return opt ? (opt.getAttribute('data-statecode') || '') : '';
}

function updateGstBreakup() {
    var custStateCode = getSelectedCustomerStateCode();
    var isInterstate = !!(COMPANY_STATECODE && custStateCode && COMPANY_STATECODE !== custStateCode);

    var badge = document.getElementById('gstTaxTypeBadge');
    if (badge) {
        if (!custStateCode) { badge.textContent = ''; }
        else { badge.textContent = isInterstate ? 'Interstate — IGST' : 'Intrastate — CGST + SGST'; }
    }

    var groups = {};
    var order = [];
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr) {
        var prodSel = tr.querySelector('select[name="product[]"]');
        if (!prodSel || !prodSel.value) return;
        var amtInp   = tr.querySelector('input[name="amt[]"]');
        var discaInp = tr.querySelector('input[name="discamt[]"]');
        var gstpInp  = tr.querySelector('input[name="gstpercent[]"]');
        var gstaInp  = tr.querySelector('input[name="gstamt[]"]');
        var amt   = parseFloat(amtInp   && amtInp.value   || 0) || 0;
        var disca = parseFloat(discaInp && discaInp.value || 0) || 0;
        var gstp  = parseFloat(gstpInp  && gstpInp.value  || 0) || 0;
        var gsta  = parseFloat(gstaInp  && gstaInp.value  || 0) || 0;
        var taxable = amt - disca;
        var key = gstp.toFixed(2);
        if (!groups[key]) { groups[key] = { rate: gstp, taxable: 0, gst: 0 }; order.push(key); }
        groups[key].taxable += taxable;
        groups[key].gst += gsta;
    });
    order.sort(function(a, b) { return parseFloat(a) - parseFloat(b); });

    var tbody = document.getElementById('gstBreakupBody');
    var totTax = 0, totCgst = 0, totSgst = 0, totIgst = 0, totGst = 0, html = '';
    order.forEach(function(key) {
        var g = groups[key];
        var cgst = 0, sgst = 0, igst = 0;
        if (isInterstate) { igst = g.gst; } else { cgst = g.gst / 2; sgst = g.gst - cgst; }
        totTax += g.taxable; totCgst += cgst; totSgst += sgst; totIgst += igst; totGst += g.gst;
        html += '<tr>' +
            '<td style="padding:5px 8px;text-align:center;border-bottom:1px solid #fef3c7;">' + g.rate.toFixed(2).replace(/\.00$/, '') + '%</td>' +
            '<td style="padding:5px 8px;text-align:right;border-bottom:1px solid #fef3c7;">' + g.taxable.toFixed(2) + '</td>' +
            '<td style="padding:5px 8px;text-align:right;border-bottom:1px solid #fef3c7;">' + (cgst ? cgst.toFixed(2) : '') + '</td>' +
            '<td style="padding:5px 8px;text-align:right;border-bottom:1px solid #fef3c7;">' + (sgst ? sgst.toFixed(2) : '') + '</td>' +
            '<td style="padding:5px 8px;text-align:right;border-bottom:1px solid #fef3c7;">' + (igst ? igst.toFixed(2) : '') + '</td>' +
            '<td style="padding:5px 8px;text-align:right;border-bottom:1px solid #fef3c7;">' + g.gst.toFixed(2) + '</td>' +
            '</tr>';
    });
    if (!order.length) html = '<tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:8px;">No items yet</td></tr>';
    if (tbody) tbody.innerHTML = html;
    var bt  = document.getElementById('bk_taxable_total'); if (bt)  bt.textContent  = totTax.toFixed(2);
    var bc  = document.getElementById('bk_cgst_total');    if (bc)  bc.textContent  = totCgst.toFixed(2);
    var bs  = document.getElementById('bk_sgst_total');    if (bs)  bs.textContent  = totSgst.toFixed(2);
    var bi  = document.getElementById('bk_igst_total');    if (bi)  bi.textContent  = totIgst.toFixed(2);
    var bg  = document.getElementById('bk_gst_total');     if (bg)  bg.textContent  = totGst.toFixed(2);
}

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');
    if (!document.getElementById('customer').value) errors.push('Customer is required');
    var hasRow = false;
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr){
        var p = tr.querySelector('select[name="product[]"]'); if (p && p.value) hasRow = true;
    });
    if (!hasRow) errors.push('At least one row with Product 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').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);
});

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

$(function(){
    document.querySelectorAll('#dgrid tbody tr').forEach(function(tr){ initRowSelects(tr); });
    $('#customer,#godown').select2({ dropdownAutoWidth:true, width:'100%' });
    $('#godown').on('change', function(){ refreshAllStockQty(); });
    // Auto-fill Salesman from the Customer master's linked salesman whenever
    // the customer changes. Only applies when Salesman is a real dropdown
    // (supervisor/admin); staff logins keep their locked hidden field as-is.
    $('#customer').on('change', function(){
        var opt = this.options[this.selectedIndex];
        var sm  = opt ? (opt.getAttribute('data-salesman') || '0') : '0';
        var $salesmanSel = $('#salesman');
        if ($salesmanSel.length && $salesmanSel.is('select')) {
            $salesmanSel.val(sm).trigger('change.select2');
        }
        // Customer change can flip interstate/intrastate status, which
        // changes how the GST Rate-wise Breakup splits into CGST/SGST/IGST.
        updateGstBreakup();
    });
});
renumber();
recalc();
</script>
</body>
</html>
