<?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  = 'Purchase Import';
$maindb    = 'purchaseimport';
$printfile = 'purchaseexport_print.php';
$file      = 'purchaseexport.php';
$keyfld    = 'vouchno';
$source    = 'IMP';

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

mysqli_select_db($conn, $zdb);

// ── One-time rename: this module used to be called Purchase Export, and its
//    tables were named purchaseexport/purchaseexportdtl/purchaseexportchg.
//    Renamed here (preserving existing data) rather than losing history. ───
foreach ([
    'purchaseexport'    => 'purchaseimport',
    'purchaseexportdtl' => 'purchaseimportdtl',
    'purchaseexportchg' => 'purchaseimportchg',
] as $_oldTbl => $_newTbl) {
    $_oldChk = mysqli_query($conn, "SHOW TABLES LIKE '$_oldTbl'");
    $_newChk = mysqli_query($conn, "SHOW TABLES LIKE '$_newTbl'");
    if ($_oldChk && mysqli_num_rows($_oldChk) > 0 && $_newChk && mysqli_num_rows($_newChk) == 0) {
        mysqli_query($conn, "RENAME TABLE `$_oldTbl` TO `$_newTbl`");
    }
}

// ── Auto-create tables ────────────────────────────────────────────────────
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `purchaseimport` (
    `vouchno` INT(11) NOT NULL,
    `vouchdt` DATE NULL,
    `supplier` INT(11) NOT NULL DEFAULT 0,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `remarks` VARCHAR(200) NOT NULL DEFAULT '',
    `currency` VARCHAR(10) NOT NULL DEFAULT 'INR',
    `roe` DOUBLE NOT NULL DEFAULT 1,
    `subtotal` DOUBLE NOT NULL DEFAULT 0,
    `freight_charges` DOUBLE NOT NULL DEFAULT 0,
    `charges_total` DOUBLE NOT NULL DEFAULT 0,
    `netamount` 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));

mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `purchaseimportdtl` (
    `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,
    `ctnqty` DOUBLE NOT NULL DEFAULT 0,
    `percarton` DOUBLE NOT NULL DEFAULT 0,
    `qty` DOUBLE NOT NULL DEFAULT 0,
    `cbm` DOUBLE NOT NULL DEFAULT 0,
    `weight` DOUBLE NOT NULL DEFAULT 0,
    `calby` VARCHAR(10) NOT NULL DEFAULT 'QTY',
    `cost` DOUBLE NOT NULL DEFAULT 0,
    `amount` 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));

// ── Charges are a multi-row list picked from the Purchase Expense master
//    (accmast grpcode 007) — any number of charge lines per voucher, each
//    tied to a real expense account, all summed into charges_total below.
//    Freight Charges stays a separate fixed field (see header table) since
//    it applies to every bill; this list is for the variable/occasional ones.
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `purchaseimportchg` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `expense` INT(11) NOT NULL DEFAULT 0,
    `amount` DOUBLE NOT NULL DEFAULT 0,
    PRIMARY KEY (`srl`),
    KEY `vouchno` (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") or die(mysqli_error($conn));

// ── Migrate carton / CBM / Weight / Calby columns onto an existing purchaseimportdtl ──
foreach ([
    'ctnqty'    => "DOUBLE NOT NULL DEFAULT 0",
    'percarton' => "DOUBLE NOT NULL DEFAULT 0",
    'cbm'       => "DOUBLE NOT NULL DEFAULT 0",
    'weight'    => "DOUBLE NOT NULL DEFAULT 0",
    'calby'     => "VARCHAR(10) NOT NULL DEFAULT 'QTY'",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `purchaseimportdtl` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `purchaseimportdtl` ADD COLUMN `$col` $def");
}

// ── Migrate currency / ROE / charges_total columns onto an existing purchaseimport ──
foreach ([
    'currency'        => "VARCHAR(10) NOT NULL DEFAULT 'INR'",
    'roe'             => "DOUBLE NOT NULL DEFAULT 1",
    'freight_charges' => "DOUBLE NOT NULL DEFAULT 0",
    'charges_total'   => "DOUBLE NOT NULL DEFAULT 0",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `purchaseimport` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `purchaseimport` ADD COLUMN `$col` $def");
}

// ── Migrate Freight A/C block columns (party select + its own currency/ROE
//    breakdown, prefixed fr_ since `currency`/`roe` already exist above as the
//    header-level fields) + Provision for Bad Debts / DO onto purchaseimport ──
foreach ([
    'fr_accode'   => "INT(11) NOT NULL DEFAULT 0",
    'fr_currency' => "VARCHAR(10) NOT NULL DEFAULT 'INR'",
    'fr_roe'      => "DOUBLE NOT NULL DEFAULT 1",
    'fr_inramt'   => "DOUBLE NOT NULL DEFAULT 0",
    'fr_feamt'    => "DOUBLE NOT NULL DEFAULT 0",
    'baddebts'    => "DOUBLE NOT NULL DEFAULT 0",
    'doamt'       => "DOUBLE NOT NULL DEFAULT 0",
    'cha_accode'  => "INT(11) NOT NULL DEFAULT 0",
    'container_no' => "VARCHAR(30) NOT NULL DEFAULT ''",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `purchaseimport` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `purchaseimport` ADD COLUMN `$col` $def");
}

// ── Seed fixed system ledger accounts used by the Freight / Bad Debts / DO
//    postings below (accmast accode<=50 = system-reserved, same convention
//    as Cash/Bank). Only inserted if not already present, so this never
//    clobbers an existing account occupying the same code on a live install. ──
foreach ([
    ['accode' => 8,  'grpcode' => '012', 'name' => 'Freight A/C'],
    ['accode' => 9,  'grpcode' => '012', 'name' => 'Provision For Bad Debts'],
    ['accode' => 10, 'grpcode' => '012', 'name' => 'DO Charges'],
    ['accode' => 11, 'grpcode' => '004', 'name' => 'Purchase Import'],
] as $_sa) {
    $_chkAcc = mysqli_query($conn, "SELECT `accode` FROM `accmast` WHERE `accode`='{$_sa['accode']}'");
    if ($_chkAcc && mysqli_num_rows($_chkAcc) == 0) {
        mysqli_query($conn, "INSERT INTO `accmast` (`accode`,`grpcode`,`name`,`dc`,`adduser`,`adddate`,`addtime`)
            VALUES ('{$_sa['accode']}','{$_sa['grpcode']}','{$_sa['name']}','D','system',CURDATE(),CURTIME())");
    }
}

// ── Self-healing: ensure `actran` carries the columns the Freight / Bad Debts
//    / DO postings below write to. `feamt`/`roe`/`currency` already exist on
//    a typical install (used by bankpay.php etc.); `inramt` is new — the
//    INR-converted amount for these entries (inramt = ROE x entered amount).
foreach ([
    'feamt'    => "DOUBLE NOT NULL DEFAULT 0",
    'inramt'   => "DOUBLE NOT NULL DEFAULT 0",
    'roe'      => "DOUBLE NOT NULL DEFAULT 1",
    'currency' => "VARCHAR(10) NOT NULL DEFAULT 'INR'",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `actran` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `actran` ADD COLUMN `$col` $def");
}

// ── transacn (shared product stock ledger) ───────────────────────────────
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");

// ── Defensive: godown / brand / currency masters ──────────────────────────
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");

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");

// Same `currency` master already relied on (but never created) by
// bankrecp.php / bankpay.php / cashrecp.php / cashpay.php — created here
// defensively (with a starter seed) so this page stays self-contained even
// on a fresh install, matching this file's own godown/brand pattern.
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `currency` (
    `code` VARCHAR(10) NOT NULL,
    `name` VARCHAR(50) NOT NULL DEFAULT '',
    PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$curCntRes = mysqli_query($conn, "SELECT COUNT(*) AS c FROM `currency`");
$curCnt    = $curCntRes ? (int)mysqli_fetch_assoc($curCntRes)['c'] : 0;
if ($curCnt == 0) {
    mysqli_query($conn, "INSERT INTO `currency` (`code`,`name`) VALUES
        ('INR','INR'),('USD','USD'),('CNY','CNY'),('EUR','EUR'),('GBP','GBP')");
}

foreach ([
    'brand'         => "VARCHAR(100) NOT NULL DEFAULT ''",
    'unitpercarton' => "DOUBLE NOT NULL DEFAULT 0",
] 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");
}

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

function pex_acc_list($conn, $grpcode, $currCond = '') {
    $list = [];
    $r = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `grpcode`='$grpcode' AND `accode`>50 $currCond ORDER BY `name`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $list[] = $row;
    return $list;
}

// Purchase Export — supplier master restricted to non-INR suppliers only
$chk = mysqli_query($conn, "SHOW COLUMNS FROM `accmast` LIKE 'currency'");
if ($chk && mysqli_num_rows($chk) == 0)
    mysqli_query($conn, "ALTER TABLE `accmast` ADD COLUMN `currency` VARCHAR(10) NOT NULL DEFAULT 'INR'");

$supplierList     = pex_acc_list($conn, '009', "AND `currency`<>'INR'");
$purchExpenseList = pex_acc_list($conn, '007');
$audituser        = audituser();

// Freight A/C — combined Shipper (030) + Supplier (009) accounts, so the
// freight payee can be either type. No currency restriction here (unlike the
// main Supplier field above) since freight can be paid to any local or
// foreign party.
function pex_acc_list_multi($conn, array $grpcodes) {
    $list = [];
    $in = "'" . implode("','", array_map(function ($g) use ($conn) { return mysqli_real_escape_string($conn, $g); }, $grpcodes)) . "'";
    $r = mysqli_query($conn, "SELECT `accode`,`name`,`grpcode` FROM `accmast` WHERE `grpcode` IN ($in) AND `accode`>50  ORDER BY `name`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $list[] = $row;
    return $list;
}
$freightAcList = pex_acc_list_multi($conn, ['030', '009']);

// CHA (Customs House Agent) master — accmast grpcode 044. Selected once per
// voucher; each Other Charges row Drs its own Purchase Expense account and
// Crs this single CHA account (see actran postings below).
$chaList = pex_acc_list($conn, '044');

$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 already carries "Pcs Per Carton" (unitpercarton) — pull it
// through so each line can auto-fill Per Carton from the product record.
$productList = [];
$pres = mysqli_query($conn, "SELECT `id`,`name`,`cost`,`brand`,`unitpercarton` 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;

$currencyList = mysqli_query($conn, "SELECT `code`,`name` FROM `currency` WHERE code != '1'  ORDER BY `code`") or die(mysqli_error($conn));

// ── POST ──────────────────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vouchdt  = mysqli_real_escape_string($conn, trim($_POST["vouchdt"]));
    $container_no = mysqli_real_escape_string($conn, trim($_POST["container_no"] ?? ''));
    $supplier = (int)$_POST["supplier"];
    // Godown belongs to the voucher header (not per line) — applies to every line item below.
    $godown   = (int)($_POST["godown"] ?? 0);
    $remarks  = mysqli_real_escape_string($conn, trim($_POST["remarks"] ?? ''));
    $currency = mysqli_real_escape_string($conn, trim($_POST["currency"] ?? 'INR'));
    if ($currency === '') $currency = 'INR';
    $roe = (float)($_POST["roe"] ?? 1);
    if ($roe <= 0) $roe = 1;
    $freight_charges = (float)($_POST["freight_charges"] ?? 0);

    // ── Freight A/C block: party (Shipper/Supplier) + its own currency/ROE,
    //    used to derive the INR amount for the ledger posting —
    //    inramt (INR amount) = ROE x Freight Amount, feamt = Freight Amount. ──
    $fr_accode   = (int)($_POST["fr_accode"] ?? 0);
    $fr_currency = mysqli_real_escape_string($conn, trim($_POST["fr_currency"] ?? 'INR'));
    if ($fr_currency === '') $fr_currency = 'INR';
    $fr_roe = (float)($_POST["fr_roe"] ?? 1);
    if ($fr_roe <= 0) $fr_roe = 1;
    $fr_feamt  = $freight_charges;
    $fr_inramt = $fr_roe * $fr_feamt;

    // ── Provision for Bad Debts / DO — added after Charges Total, both feed
    //    into Net Amount the same way Freight/Other Charges already do. ──
    $baddebts = (float)($_POST["baddebts"] ?? 0);
    $doamt    = (float)($_POST["doamt"] ?? 0);

    // CHA — the single party Crd for every Other Charges row's Dr leg below.
    $cha_accode = (int)($_POST["cha_accode"] ?? 0);

    $prodA   = $_POST['product']   ?? [];
    $brandA  = $_POST['brand']     ?? [];
    $ctnA    = $_POST['ctnqty']    ?? [];
    $perA    = $_POST['percarton'] ?? [];
    $cbmA    = $_POST['cbm']       ?? [];
    $weightA = $_POST['weight']    ?? [];
    $calbyA  = $_POST['calby']     ?? [];
    $costA   = $_POST['cost']      ?? [];

    // Line amounts / subtotal are kept in the ENTRY currency (whatever was
    // picked above) — the single ROE conversion to INR happens once, on the
    // header total below, the same one-conversion-point pattern bankrecp.php
    // uses for feamt*roe=amount.
    $lines = []; $subtotal = 0;
    foreach ($prodA as $i => $p) {
        $p         = (int)$p;
        $brand     = (int)($brandA[$i] ?? 0);
        $ctnqty    = (float)($ctnA[$i] ?? 0);
        $percarton = (float)($perA[$i] ?? 0);
        // Tot Qty is always derived server-side from Ctn Qty x Per Carton —
        // never trust a client-submitted qty value.
        $qty       = $ctnqty * $percarton;
        $cbm       = (float)($cbmA[$i] ?? 0);
        $weight    = (float)($weightA[$i] ?? 0);
        $calby     = strtoupper(trim($calbyA[$i] ?? 'QTY'));
        if (!in_array($calby, ['QTY','CBM','WEIGHT'], true)) $calby = 'QTY';
        $cost      = (float)($costA[$i] ?? 0);
        if ($p == 0 && $ctnqty == 0 && $qty == 0 && $cost == 0 && $cbm == 0 && $weight == 0) continue;
        // Amount is calculated off whichever basis Calby selects for this line.
        $basis = ($calby === 'CBM') ? $cbm : (($calby === 'WEIGHT') ? $weight : $qty);
        $amt = $basis * $cost;
        $lines[] = ['product' => $p, 'brand' => $brand, 'ctnqty' => $ctnqty, 'percarton' => $percarton, 'qty' => $qty, 'cbm' => $cbm, 'weight' => $weight, 'calby' => $calby, 'cost' => $cost, 'amount' => $amt];
        $subtotal += $amt;
    }

    // ── Charges: any number of rows, each picked from the Purchase Expense
    //    master (accmast grpcode 007) ─────────────────────────────────────
    $chgExpA = $_POST['chgexp'] ?? [];
    $chgAmtA = $_POST['chgamt'] ?? [];
    $charges = []; $chargesTotal = 0;
    foreach ($chgExpA as $i => $ce) {
        $ce  = (int)$ce;
        $amt = (float)($chgAmtA[$i] ?? 0);
        if ($ce == 0 && $amt == 0) continue;
        $charges[] = ['expense' => $ce, 'amount' => $amt];
        $chargesTotal += $amt;
    }

    // Net Amount = (subtotal + Freight + all other charges + Bad Debts + DO) converted to INR via ROE (ROE=1 for INR entries, a no-op).
    $netamount = ($subtotal + $freight_charges + $chargesTotal + $baddebts + $doamt) * $roe;

    // 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);
            $sq = $sqRes ? (float)mysqli_fetch_assoc($sqRes)['q'] : 0;
        }
        $lines[$k]['stockqty'] = $sq;
    }

    if ($addflag == 1) {
        mysqli_query($conn, "INSERT INTO `$maindb`
            (`vouchno`,`vouchdt`,`container_no`,`supplier`,`godown`,`remarks`,`currency`,`roe`,
             `subtotal`,`freight_charges`,`charges_total`,`netamount`,
             `fr_accode`,`fr_currency`,`fr_roe`,`fr_inramt`,`fr_feamt`,
             `baddebts`,`doamt`,`cha_accode`,
             `adduser`,`adddate`,`addtime`)
            VALUES
            ('$qvouch','$vouchdt','$container_no','$supplier','$godown','$remarks','$currency','$roe',
             '$subtotal','$freight_charges','$chargesTotal','$netamount',
             '$fr_accode','$fr_currency','$fr_roe','$fr_inramt','$fr_feamt',
             '$baddebts','$doamt','$cha_accode',
             '$audituser',CURDATE(),CURTIME())")
        or die(mysqli_error($conn));
    } else {
        mysqli_query($conn, "UPDATE `$maindb` SET
            `vouchdt`='$vouchdt', `container_no`='$container_no', `supplier`='$supplier', `godown`='$godown', `remarks`='$remarks',
            `currency`='$currency', `roe`='$roe',
            `subtotal`='$subtotal', `freight_charges`='$freight_charges', `charges_total`='$chargesTotal', `netamount`='$netamount',
            `fr_accode`='$fr_accode', `fr_currency`='$fr_currency', `fr_roe`='$fr_roe', `fr_inramt`='$fr_inramt', `fr_feamt`='$fr_feamt',
            `baddebts`='$baddebts', `doamt`='$doamt', `cha_accode`='$cha_accode',
            `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
            WHERE `$keyfld`='$qvouch'")
        or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `purchaseimportdtl` WHERE `vouchno`='$qvouch'");
        mysqli_query($conn, "DELETE FROM `purchaseimportchg` WHERE `vouchno`='$qvouch'");
    }

    foreach ($lines as $ln) {
        $calbyEsc = mysqli_real_escape_string($conn, $ln['calby']);
        mysqli_query($conn, "INSERT INTO `purchaseimportdtl`
            (`vouchno`,`product`,`brand`,`ctnqty`,`percarton`,`qty`,`cbm`,`weight`,`calby`,`cost`,`amount`,`stockqty`)
            VALUES ('$qvouch','{$ln['product']}','{$ln['brand']}','{$ln['ctnqty']}','{$ln['percarton']}','{$ln['qty']}','{$ln['cbm']}','{$ln['weight']}','$calbyEsc','{$ln['cost']}','{$ln['amount']}','{$ln['stockqty']}')")
        or die(mysqli_error($conn));
    }

    foreach ($charges as $chg) {
        mysqli_query($conn, "INSERT INTO `purchaseimportchg`
            (`vouchno`,`expense`,`amount`)
            VALUES ('$qvouch','{$chg['expense']}','{$chg['amount']}')")
        or die(mysqli_error($conn));
    }

    // ── Stock IN → transacn (idempotent delete+insert). Total qty of every
    //    line (Ctn Qty x Per Carton) is added to stock at the header's single godown.
    //    Cost is stored converted to INR (cost x ROE) so stock valuation / dashboard
    //    figures stay in a single, comparable currency across the whole app. ─
    mysqli_query($conn, "DELETE FROM `transacn` WHERE `source`='$source' AND `vouchno`='$qvouch'");
    foreach ($lines as $ln) {
        $prod    = (int)$ln['product'];
        $qty     = (float)$ln['qty'];
        $costInr = (float)$ln['cost'] * $roe;
        if ($prod > 0 && $qty != 0) {
            mysqli_query($conn, "INSERT INTO `transacn`
                (`vouchdt`,`source`,`vouchno`,`godown`,`product`,`qty`,`cost`,`adduser`,`adddate`,`addtime`)
                VALUES ('$vouchdt','$source','$qvouch','$godown','$prod','$qty','$costInr','$audituser',CURDATE(),CURTIME())")
            or die(mysqli_error($conn));
        }
    }

    // ── Ledger postings (actran) — Freight A/C, Provision for Bad Debts, DO.
    //    Idempotent delete+insert (this voucher's own postings only), same
    //    pattern as bankpay.php: positive amount = Dr leg, negative = Cr leg,
    //    both legs share source+vouchno as the voucher key, trnno disambiguates.
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    $trn = 1;

    // Subtotal (goods value): Dr accode=11/grpcode=004 (Purchase Import); Cr
    // the Supplier selected above (grpcode looked up dynamically, same as the
    // Freight/CHA party legs).
    if ($supplier > 0 && $subtotal != 0) {
        $subInramt = $subtotal * $roe;
        $subNarr   = mysqli_real_escape_string($conn, 'Purchase Import - ' . $qvouch);

        $subTrn1 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$subTrn1','11','004','$subtotal','$subtotal','$subInramt','$currency','$roe','$subInramt','$subNarr')")
        or die(mysqli_error($conn));

        $supPgrpRes = mysqli_query($conn, "SELECT `grpcode` FROM `accmast` WHERE `accode`='$supplier'");
        $supPgrpRow = mysqli_fetch_assoc($supPgrpRes);
        $supPgrp    = $supPgrpRow ? $supPgrpRow['grpcode'] : '';
        $subInramtC = $subInramt * -1;
        $subtotalC  = $subtotal * -1;
        $subTrn2    = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$subTrn2','$supplier','$supPgrp','$subtotalC','$subtotalC','$subInramtC','$currency','$roe','$subInramtC','$subNarr')")
        or die(mysqli_error($conn));
    }

    // Freight: Dr fixed Freight A/C (accode=8, grpcode=012); Cr the selected
    // Freight A/C party (Shipper grpcode=030 or Supplier grpcode=009 — looked
    // up dynamically, same as bankpay.php does for its party leg).
    if ($fr_accode > 0 && $fr_inramt != 0) {
        $frNarr = mysqli_real_escape_string($conn, 'Freight Charges - ' . $qvouch);
        $frTrn1 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$frTrn1','8','012','$fr_feamt','$fr_feamt','$fr_inramt','$fr_currency','$fr_roe','$fr_inramt','$frNarr')")
        or die(mysqli_error($conn));

        $frPgrpRes = mysqli_query($conn, "SELECT `grpcode` FROM `accmast` WHERE `accode`='$fr_accode'");
        $frPgrpRow = mysqli_fetch_assoc($frPgrpRes);
        $frPgrp    = $frPgrpRow ? $frPgrpRow['grpcode'] : '';
        $frInramtC = $fr_inramt * -1;
        $frFeamtC  = $fr_feamt * -1;
        $frTrn2    = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$frTrn2','$fr_accode','$frPgrp','$frFeamtC','$frFeamtC','$frInramtC','$fr_currency','$fr_roe','$frInramtC','$frNarr')")
        or die(mysqli_error($conn));
    }

    // Other Charges: for each Purchase Expense row (accmast grpcode 007) — Dr
    // that row's own expense account, Cr the single selected CHA account
    // (grpcode looked up dynamically, same as the Freight party leg above).
    if ($cha_accode > 0 && count($charges) > 0) {
        $chaPgrpRes = mysqli_query($conn, "SELECT `grpcode` FROM `accmast` WHERE `accode`='$cha_accode'");
        $chaPgrpRow = mysqli_fetch_assoc($chaPgrpRes);
        $chaPgrp    = $chaPgrpRow ? $chaPgrpRow['grpcode'] : '';

        foreach ($charges as $chg) {
            $chgExpense = (int)$chg['expense'];
            $chgAmount  = (float)$chg['amount'];
            if ($chgExpense == 0 || $chgAmount == 0) continue;

            $chgInramt = $chgAmount * $roe;
            $chgNarr   = mysqli_real_escape_string($conn, 'Purchase Expenses For - ' . $qvouch);

            $chgTrn1 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
            mysqli_query($conn, "INSERT INTO `actran`
                (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
                VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$chgTrn1','$chgExpense','007','$chgAmount','$chgAmount','$chgInramt','$currency','$roe','$chgInramt','$chgNarr')")
            or die(mysqli_error($conn));

            $chgInramtC = $chgInramt * -1;
            $chgAmountC = $chgAmount * -1;
            $chgTrn2    = str_pad($trn++, 3, '0', STR_PAD_LEFT);
            mysqli_query($conn, "INSERT INTO `actran`
                (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
                VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$chgTrn2','$cha_accode','$chaPgrp','$chgAmountC','$chgAmountC','$chgInramtC','$currency','$roe','$chgInramtC','$chgNarr')")
            or die(mysqli_error($conn));
        }
    }

    // Provision for Bad Debts: Cr accode=9/grpcode=012 (Bad Debts); Dr accode=11/grpcode=004 (Purchase Import).
    if ($baddebts != 0) {
        $bdNarr = mysqli_real_escape_string($conn, 'Provision For Bad Debts For - ' . $qvouch);
        $bdTrn1 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$bdTrn1','11','004','$baddebts','$baddebts','$baddebts','INR','1','$baddebts','$bdNarr')")
        or die(mysqli_error($conn));

        $baddebtsC = $baddebts * -1;
        $bdTrn2    = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$bdTrn2','9','012','$baddebtsC','$baddebtsC','$baddebtsC','INR','1','$baddebtsC','$bdNarr')")
        or die(mysqli_error($conn));
    }

    // DO: Cr accode=10/grpcode=012 (DO); Dr accode=11/grpcode=004 (Purchase Import).
    if ($doamt != 0) {
        $doNarr = mysqli_real_escape_string($conn, 'DO Charges For - ' . $qvouch);
        $doTrn1 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$doTrn1','11','004','$doamt','$doamt','$doamt','INR','1','$doamt','$doNarr')")
        or die(mysqli_error($conn));

        $doamtC = $doamt * -1;
        $doTrn2 = str_pad($trn++, 3, '0', STR_PAD_LEFT);
        mysqli_query($conn, "INSERT INTO `actran`
            (`vouchdt`,`date`,`vouchno`,`source`,`trnno`,`accode`,`grpcode`,`amount`,`feamt`,`inramt`,`currency`,`roe`,`actamt`,`narr`)
            VALUES ('$vouchdt','$vouchdt','$qvouch','$source','$doTrn2','10','012','$doamtC','$doamtC','$doamtC','INR','1','$doamtC','$doNarr')")
        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 `purchaseimportdtl` WHERE `vouchno`='$qvouch'") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `purchaseimportchg` 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");
    } 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 = []; $charges = [];
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 `purchaseimportdtl` d
                                 WHERE d.`vouchno`='$qvouch' ORDER BY d.`srl`");
    while ($r = mysqli_fetch_assoc($tr)) $lines[] = $r;
    $cr  = mysqli_query($conn, "SELECT c.* FROM `purchaseimportchg` c WHERE c.`vouchno`='$qvouch' ORDER BY c.`srl`");
    while ($r = mysqli_fetch_assoc($cr)) $charges[] = $r;
}
if (!$lines) {
    $lines[] = ['product'=>0,'ctnqty'=>'','percarton'=>'','qty'=>'','cbm'=>'','weight'=>'','calby'=>'QTY','cost'=>'','amount'=>'','pbrand'=>''];
}
if (!$charges) {
    $charges[] = ['expense'=>0,'amount'=>''];
}

$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; }
.fl.narrow { flex:0 1 120px; min-width:110px; }
.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; }
.text-right { text-align:right; }
.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); }
.sec-title { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; margin:16px 0 6px; align-items:center; }
/* Shared right-aligned column for the Other Charges title + table + Add
   Charge button, so all three line up on the same right edge. */
.chg-section { max-width:480px; margin-left:auto; }
@media (max-width:560px) { .chg-section { max-width:100%; margin-left:0; } }
.chg-grid-wrap { border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; max-width:480px; margin-left:auto; }
table.chggrid { width:100%; border-collapse:collapse; font-size:11.5px; }
table.chggrid th { background:#1e293b; color:#e2e8f0; font-weight:700; font-size:10px; text-transform:uppercase; letter-spacing:.04em; padding:6px 5px; text-align:center; white-space:nowrap; }
table.chggrid th.num, table.chggrid td.num { text-align:right; }
table.chggrid td { padding:3px 4px; border-bottom:1px solid #f1f5f9; }
table.chggrid input { width:100%; padding:4px 5px; font-size:11.5px; border:1px solid #e2e8f0; border-radius:4px; background:#fff; font-family:inherit; box-sizing:border-box; color:#1e293b; text-align:right; }
table.chggrid input:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
table.chggrid input.numfld { text-align:right; }
@media (max-width:560px) { .chg-grid-wrap { max-width:100%; margin-left:0; } }
.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.chg-add { background:#7c3aed; margin-top:8px; padding:6px 14px; font-size:12px; }
.chg-add-wrap { display:block; text-align:right; max-width:480px; margin-left:auto; }
.chg-add-wrap .add-row-btn { display:flex; }
@media (max-width:560px) { .chg-add-wrap { max-width:100%; margin-left:0; } }
.add-row-btn:disabled { opacity:.35; pointer-events:none; }
.sum-strip { margin:12px 0 10px; padding:14px 16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; }
.sum-strip-lbl { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; margin-bottom:10px; }
.sum-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; }
@media (max-width:700px) { .sum-grid { grid-template-columns:repeat(2,1fr); } }
@media (max-width:420px) { .sum-grid { grid-template-columns:1fr; } }
.sum-fld label { font-size:11px; font-weight:600; color:#64748b; display:block; margin-bottom:3px; }
.sum-fld input { 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 input.editable { background:#fff; border-color:#93c5fd; }
.sum-fld select { width:100%; box-sizing:border-box; padding:6px 8px; font-size:13px; font-weight:600; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#1e293b; font-family:inherit; }
.sum-line { display:flex; align-items:center; justify-content:flex-end; flex-wrap:wrap; gap:10px 16px; margin:8px 0; padding:10px 14px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; }
.sum-line label { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#64748b; flex-shrink:0; }
.sum-line input, .sum-line select { flex:0 1 180px; width:180px; box-sizing:border-box; padding:6px 9px; font-size:12.5px; font-weight:700; background:#fff; border:1px solid #e2e8f0; border-radius:6px; color:#1e293b; text-align:right; font-family:inherit; }
.sum-line select { text-align:left; font-weight:600; }
.sum-line input.editable { border-color:#93c5fd; }
.sum-line.net { border-color:#86efac; background:#f0fdf4; }
.sum-line.net input { color:#15803d; font-size:13.5px; }
/* select2 injects its own container next to the hidden <select>; override its
   inline width so it stays small like the other .sum-line fields. */
.sum-line .select2-container { width:220px !important; flex:0 0 220px; }
@media (max-width:560px) {
    .sum-line input, .sum-line select, .sum-line .select2-container { flex:1 1 100%; width:100%; }
}
.sum-fld.net input { color:#15803d; }
.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:1100px; }
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 select.calby-fld { 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 select.calby-fld:focus { border-color:#3b82f6; background:#f0f7ff; outline:none; }
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; }
.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-truck-ramp-box" 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">Supplier <span style="color:#ef4444;">*</span></span>
                <select name="supplier" id="supplier" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Supplier --</option>
                    <?php foreach ($supplierList as $row): ?>
                    <option value="<?php echo (int)$row['accode']; ?>" <?php echo (fv($get,'supplier')==$row['accode'])?'selected':''; ?>><?php echo htmlspecialchars($row['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl">
                <span class="lbl">Godown <span style="color:#ef4444;">*</span></span>
                <select name="godown" id="godown" class="finp form select2 required-star" style="width:100%;">
                    <option value="">-- Select Godown --</option>
                    <?php foreach ($godownList as $row): ?>
                    <option value="<?php echo (int)$row['code']; ?>" <?php echo (fv($get,'godown')==$row['code'])?'selected':''; ?>><?php echo htmlspecialchars($row['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fl narrow">
                <span class="lbl">Currency</span>
                <select name="currency" id="currency" class="finp form">
                    <?php
                    $curSel = fv($get,'currency','INR');
                    mysqli_data_seek($currencyList, 0);
                    while ($crow = mysqli_fetch_assoc($currencyList)):
                        $sel = ($curSel == $crow['name']) ? 'selected' : '';
                    ?>
                    <option value="<?php echo htmlspecialchars($crow['name']); ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($crow['name']); ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="fl narrow">
                <span class="lbl">Rate of Exchange</span>
                <input type="number" step="any" name="roe" id="roe" class="finp form text-right" oninput="recalc()" value="<?php echo fvn($get,'roe') ?: '1'; ?>">
            </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>

        <div class="fr-grid">
            <div class="fl">
                <span class="lbl" style="margin-top:8px;">Container No.</span>
                <input type="text" name="container_no" id="container_no" class="finp form" maxlength="30" style="width:280px;max-width:280px;" value="<?php echo fv($get,'container_no'); ?>">
            </div>
        </div>

        <!-- Detail grid (godown is NOT here — it's a single header-level field above, applied to every line) -->
        <div class="grid-wrap">
        <table class="dgrid" id="dgrid">
            <thead>
                <tr>
                    <th style="width:2%;">Sr</th>
                    <th style="width:2%;"></th>
                    <th style="width:10%;text-align:left;">Brand</th>
                    <th style="width:18%;text-align:left;">Product</th>
                    <th class="num" style="width:7%;">Stock Qty</th>
                    <th class="num" style="width:6%;">Ctn Qty</th>
                    <th class="num" style="width:7%;">Per Carton</th>
                    <th class="num" style="width:7%;">Tot Qty</th>
                    <th class="num" style="width:7%;">CBM</th>
                    <th class="num" style="width:7%;">Weight</th>
                    <th style="width:8%;">Calc By</th>
                    <th class="num" style="width:8%;">Cost</th>
                    <th class="num" style="width:11%;">Amount</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-percarton="<?php echo htmlspecialchars($p['unitpercarton']); ?>" <?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="ctnqty[]" class="numfld form ctnqty-fld" value="<?php echo fvn($ln,'ctnqty'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="percarton[]" class="numfld form percarton-fld" value="<?php echo fvn($ln,'percarton'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="qty[]" class="numfld form qty-fld" value="<?php echo fvn($ln,'qty'); ?>" readonly tabindex="-1"></td>
                    <td><input type="number" step="any" name="cbm[]" class="numfld form cbm-fld" value="<?php echo fvn($ln,'cbm'); ?>" oninput="recalc()"></td>
                    <td><input type="number" step="any" name="weight[]" class="numfld form weight-fld" value="<?php echo fvn($ln,'weight'); ?>" oninput="recalc()"></td>
                    <td>
                        <select name="calby[]" class="form calby-fld" onchange="recalc()">
                            <option value="QTY"    <?php echo (fv($ln,'calby','QTY')=='QTY')    ? 'selected' : ''; ?>>Qty</option>
                            <option value="CBM"    <?php echo (fv($ln,'calby','QTY')=='CBM')    ? 'selected' : ''; ?>>CBM</option>
                            <option value="WEIGHT" <?php echo (fv($ln,'calby','QTY')=='WEIGHT') ? 'selected' : ''; ?>>Weight</option>
                        </select>
                    </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,'amount'); ?>" readonly tabindex="-1"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="12" style="text-align:right;font-size:11px;color:#64748b;">Total</td>
                    <td id="t_amt"></td>
                </tr>
            </tfoot>
        </table>
        </div>

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

        <!-- Subtotal — shown as its own single-line row above the Freight block. -->
        <div class="sum-line">
            <label>Subtotal</label>
            <input type="text" id="sum_subtotal" readonly tabindex="-1">
        </div>

        <!-- Freight A/C: select label as "Freight A/C" before the freight input —
             lists Shipper (grpcode 030) + Supplier (grpcode 009) accounts. This is
             the Cr leg in actran; Dr leg is the fixed Freight A/C (accode=8,
             grpcode=012). Currency + ROE + Freight Amount follow, in that order —
             one compact, right-aligned line, same treatment as Subtotal etc. -->
        <div class="sum-line">
            <label>Freight A/C</label>
            <select name="fr_accode" id="fr_accode" class="form select2">
                <option value="">-- Select Freight A/C --</option>
                <?php foreach ($freightAcList as $row): ?>
                <option value="<?php echo (int)$row['accode']; ?>" <?php echo (fv($get,'fr_accode')==$row['accode'])?'selected':''; ?>><?php echo htmlspecialchars($row['name']); ?></option>
                <?php endforeach; ?>
            </select>
            <label>Currency</label>
            <select name="fr_currency" id="fr_currency" class="form">
                <?php
                $frCurSel = fv($get,'fr_currency','INR');
                mysqli_data_seek($currencyList, 0);
                while ($crow = mysqli_fetch_assoc($currencyList)):
                    $frSel = ($frCurSel == $crow['name']) ? 'selected' : '';
                ?>
                <option value="<?php echo htmlspecialchars($crow['name']); ?>" <?php echo $frSel; ?>><?php echo htmlspecialchars($crow['name']); ?></option>
                <?php endwhile; ?>
            </select>
            <label>ROE</label>
            <input type="number" step="any" name="fr_roe" id="fr_roe" class="editable form" value="<?php echo fvn($get,'fr_roe') ?: '1'; ?>">
            <label>Freight Amount</label>
            <input type="number" step="any" name="freight_charges" id="freight_charges" class="editable form" value="<?php echo fvn($get,'freight_charges'); ?>" oninput="recalc()">
        </div>


        <!-- Charges: pick any number of accounts from the Purchase Expense master
             (Packing, Customs Duty, Insurance, etc.). Freight is a separate fixed
             field next to Subtotal below since it's on every bill.
             Title, table and Add Charge button share one right-aligned column
             (chg-section) so they all line up on the same right edge. -->
        <div class="chg-section">
            <div class="sec-title" style="justify-content:flex-end;"><i class="fa fa-coins" style="margin-right:5px;color:#7c3aed;"></i> Purchase Expenses</div>
            <div class="chg-grid-wrap">
            <table class="chggrid" id="chggrid">
                <thead>
                    <tr>
                        <th style="width:30px;">Sr</th>
                        <th style="width:24px;"></th>
                        <th style="text-align:left;">Charge</th>
                        <th class="num" style="width:130px;">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($charges as $i => $chg): ?>
                    <tr>
                        <td class="chgsrno" style="text-align:center;color:#94a3b8;font-weight:600;font-size:11px;"></td>
                        <td><button type="button" class="row-del form" onclick="chgDelRow(this)"><i class="fa fa-times"></i></button></td>
                        <td>
                            <select name="chgexp[]" class="form chgexp-sel">
                                <option value="">-- Select Expense --</option>
                                <?php foreach ($purchExpenseList as $pe): ?>
                                <option value="<?php echo (int)$pe['accode']; ?>" <?php echo ((int)($chg['expense']??0)==$pe['accode'])?'selected':''; ?>><?php echo htmlspecialchars($pe['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><input type="number" step="any" name="chgamt[]" class="numfld form" value="<?php echo fvn($chg,'amount'); ?>" oninput="recalc()"></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <div class="chg-add-wrap">
                <button type="button" class="add-row-btn chg-add form" onclick="chgAddRow()"><i class="fa fa-plus"></i> Add Charge</button>
            </div>
        </div>

        <!-- CHA — single party selected once per voucher; each Other Charges row
             above Drs its own Purchase Expense account and Crs this CHA account.
             Kept on the same line as Charges Total. -->
        <div class="sum-line">
            <label>CHA</label>
            <select name="cha_accode" id="cha_accode" class="form select2">
                <option value="">-- Select CHA --</option>
                <?php foreach ($chaList as $row): ?>
                <option value="<?php echo (int)$row['accode']; ?>" <?php echo (fv($get,'cha_accode')==$row['accode'])?'selected':''; ?>><?php echo htmlspecialchars($row['name']); ?></option>
                <?php endforeach; ?>
            </select>
            <label>Charges Total</label>
            <input type="text" id="sum_charges" readonly tabindex="-1">
        </div>

        <!-- Provision for Bad Debts / DO / Net Amount — each its own single-line
             row (Subtotal sits above the Freight block). Net Amount is the one
             place ROE conversion to INR happens (Subtotal + Freight + Charges
             Total + Bad Debts + DO) x ROE. -->
        <div class="sum-line">
            <label>Provision For Bad Debts</label>
            <input type="number" step="any" name="baddebts" id="baddebts" class="editable form" value="<?php echo fvn($get,'baddebts'); ?>" oninput="recalc()">
            <label>DO</label>
            <input type="number" step="any" name="doamt" id="doamt" class="editable form" value="<?php echo fvn($get,'doamt'); ?>" oninput="recalc()">
        </div>
        <div class="sum-line net">
            <label>Net Amount</label>
            <input type="text" id="sum_netamount" readonly tabindex="-1">
        </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="Supplier / 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;">Supplier</th>
                    <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;font-size:11.5px;">Net 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>

<!-- Row template (product line) -->
<table style="display:none;"><tbody id="rowTemplate">
<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 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-percarton="<?php echo htmlspecialchars($p['unitpercarton']); ?>"><?php echo htmlspecialchars($p['name']); ?></option>
            <?php endforeach; ?>
        </select>
    </td>
    <td><input type="text" class="stockqty-fld form" readonly tabindex="-1"></td>
    <td><input type="number" step="any" name="ctnqty[]" class="numfld form ctnqty-fld" oninput="recalc()"></td>
    <td><input type="number" step="any" name="percarton[]" class="numfld form percarton-fld" oninput="recalc()"></td>
    <td><input type="number" step="any" name="qty[]" class="numfld form qty-fld" readonly tabindex="-1"></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>
</tr>
</tbody></table>

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

<script>
// Server-rendered bootstrap data for purchaseexport.js — kept minimal on purpose;
// all interactive behaviour (add/remove rows, recalculation, product filtering,
// stock lookup, search modal) lives in the external purchaseexport.js file.
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'], 'percarton'=>$p['unitpercarton']];
}, $productList)); ?>;

// Purchase Expense master (accmast grpcode 007) — powers the Charge dropdown
// in the Charges grid below.
var ALL_PURCHEXPENSE = <?php echo json_encode(array_map(function($pe){
    return ['code'=>(int)$pe['accode'], 'name'=>$pe['name']];
}, $purchExpenseList)); ?>;

var PEX_SEARCH_URL = 'includes/purchaseexport_search.php';
</script>
<script src="purchaseexport.js?a=<?= mt_rand(); ?>"></script>
</body>
</html>
