<?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  = 'Bank Receipt';
$maindb    = 'bankrecp';
$printfile = 'bankrecp_print.php';
$file      = 'bankrecp.php';
$keyfld    = 'vouchno';
$keycond   = '';
$bcgrp     = '001';      // accmast grpcode for Bank accounts
$bccol     = 'bankac';   // column storing the bank ledger account
$source    = 'BR';       // actran source code
$haschq    = true;       // bank vouchers carry cheque details

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

mysqli_select_db($conn, $zdb);

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

// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $vouchdtIn = trim($_POST["vouchdt"]);
    $bankac    = isset($_POST["bankac"]) ? (int)$_POST["bankac"] : 0;
    $accode    = isset($_POST["accode"]) ? (int)$_POST["accode"] : 0;
    $chqno     = mysqli_real_escape_string($conn, trim($_POST["chqno"] ?? ''));
    $chqdtIn   = trim($_POST["chqdt"] ?? '');
    $currency  = mysqli_real_escape_string($conn, trim($_POST["currency"]));
    $feamt     = isset($_POST["feamt"]) ? (float)$_POST["feamt"] : 0;
    $roe       = isset($_POST["roe"])   ? (float)$_POST["roe"]   : 1;
    $amount    = isset($_POST["amount"]) ? (float)$_POST["amount"] : 0;
    $narr      = mysqli_real_escape_string($conn, trim($_POST["narr"]));

    $billA     = isset($_POST['billno'])    ? $_POST['billno']    : [];
    $settleA   = isset($_POST['settleamt']) ? $_POST['settleamt'] : [];

    $a = 1;

    // Convert date dd-mm-yyyy -> yyyy-mm-dd
    $vd = '';
    if (preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $vouchdtIn, $m)) {
        $vd = $m[3] . '-' . $m[2] . '-' . $m[1];
    } else {
        $vd = $vouchdtIn;
    }

    $chqdt = null;
    if (preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $chqdtIn, $m)) {
        $chqdt = $m[3] . '-' . $m[2] . '-' . $m[1];
    }

    if ($vouchdtIn == '' || $vd == '') {
        $a = 0;
        browse("Date Cannot Be Empty");
        header("refresh:1; url=$file?mode=last");
    }

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

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

    if ($a == 1 && $amount <= 0) {
        $a = 0;
        browse("Amount Cannot Be Empty");
        header("refresh:1; url=$file?mode=last");
    }

    // ── Build clean bill-settlement rows (skip empty rows) ───────────────────
    $settleLines = [];
    $totsettle = 0;
    if ($a == 1) {
        $bcnt = count($billA);
        for ($i = 0; $i < $bcnt; $i++) {
            $bno = isset($billA[$i]) ? (int)$billA[$i] : 0;
            $bamt = isset($settleA[$i]) && $settleA[$i] !== '' ? (float)$settleA[$i] : 0;
            if ($bno <= 0 || $bamt <= 0) continue;
            $settleLines[] = ['saleinvno' => $bno, 'settleamt' => $bamt];
            $totsettle += $bamt;
        }
    }

    if ($a == 1 && $totsettle > $amount + 0.005) {
        $a = 0;
        browse("Total Bill Settlement Cannot Exceed Receipt Amount");
        header("refresh:1; url=$file?mode=last");
    }

    if ($a == 1) {
        $audituser = mysqli_real_escape_string($conn, audituser());
        $chqdtSql  = $chqdt ? "'$chqdt'" : "NULL";

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`
                (`vouchno`,`vouchdt`,`accode`,`$bccol`,`chqno`,`chqdt`,`currency`,`feamt`,`roe`,`amount`,`narr`)
                VALUES
                ('$qvouch','$vd','$accode','$bankac','$chqno',$chqdtSql,'$currency','$feamt','$roe','$amount','$narr')")
            or die(mysqli_error($conn));
        } else {
            mysqli_query($conn, "UPDATE `$maindb` SET
                `vouchdt`='$vd', `accode`='$accode', `$bccol`='$bankac',
                `chqno`='$chqno', `chqdt`=$chqdtSql,
                `currency`='$currency', `feamt`='$feamt', `roe`='$roe', `amount`='$amount', `narr`='$narr'
                WHERE `$keyfld`='$qvouch'")
            or die(mysqli_error($conn));
        }

        mysqli_query($conn, "DELETE FROM `billsettle` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
        foreach ($settleLines as $sl) {
            mysqli_query($conn, "INSERT INTO `billsettle` (`vouchno`,`source`,`vouchdt`,`saleinvno`,`settleamt`)
                VALUES ('$qvouch','$source','$vd','{$sl['saleinvno']}','{$sl['settleamt']}')")
            or die(mysqli_error($conn));
        }

        // ── Posting to actran (ledger pattern) ───────────────────────────────
        mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));

        // Party account's group code
        $pgrpRes = mysqli_query($conn, "SELECT `grpcode` FROM `accmast` WHERE `accode`='$accode'") or die(mysqli_error($conn));
        $pgrpRow = mysqli_fetch_assoc($pgrpRes);
        $pgrp    = $pgrpRow ? $pgrpRow['grpcode'] : '';

        $binit     = '';
        $minus_amt = ($amount * -1);

        // cash/bank part
        mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,vouchno, source, trnno, accode, bankinit, grpcode,
                                          amount, feamt, currency, roe, actamt, narr)
                                  VALUES ('$vd','$vd','$qvouch', '$source', '001', '$bankac', '$binit',
                                          '001', '$minus_amt','$feamt','$currency','$roe','$minus_amt','$narr')")
        or die(mysqli_error($conn));

        // party part
        mysqli_query($conn, "INSERT INTO `actran`(`vouchdt`,`date`,vouchno, source, trnno, accode, bankinit, grpcode,
                                          amount, feamt, currency, roe, actamt, narr)
                                 VALUES ('$vd','$vd','$qvouch', '$source', '002', '$accode', '$binit', '$pgrp',
                                          '$amount','$feamt','$currency','$roe','$amount','$narr')")
        or die(mysqli_error($conn));

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

// ── Fetch record ─────────────────────────────────────────────────────────────
$get = [];
$existingSettle = [];   // saleinvno => settleamt
if ($addflag != 1 && $qvouch > 0) {
    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    $get    = mysqli_fetch_array($result);
    if (!$get) $get = [];

    $sres = mysqli_query($conn, "SELECT `saleinvno`,`settleamt` FROM `billsettle` WHERE `vouchno`='$qvouch' AND `source`='$source'") or die(mysqli_error($conn));
    while ($srow = mysqli_fetch_assoc($sres)) {
        $existingSettle[(int)$srow['saleinvno']] = (float)$srow['settleamt'];
    }
}

// Account list for the "Account" select2 dropdown
$acclist = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` ORDER BY `name`") or die(mysqli_error($conn));

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    if ($usertype != 1) { header("refresh:1; url=$file?mode=last"); exit; } // admin-only delete guard
    mysqli_query($conn, "DELETE FROM `actran` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `billsettle` WHERE `source`='$source' AND `vouchno`='$qvouch'") or die(mysqli_error($conn));
    mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch'") or die(mysqli_error($conn));
    delmess("$file?mode=last");
    exit;
}

// Helper: get value safely
function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}
function fvn($get, $key, $default = '') {
    if (!isset($get[$key]) || $get[$key] === '' || $get[$key] === null) return $default;
    $v = (float)$get[$key];
    return ($v == (int)$v) ? (string)(int)$v : (string)$v;
}

if (isset($get['vouchdt']) && $get['vouchdt'] != '' && $get['vouchdt'] != '0000-00-00') {
    $vouchdt_disp = date('d-m-Y', strtotime($get['vouchdt']));
} else {
    $vouchdt_disp = date('d-m-Y');
}
if (isset($get['chqdt']) && $get['chqdt'] != '' && $get['chqdt'] != '0000-00-00') {
    $chqdt_disp = date('d-m-Y', strtotime($get['chqdt']));
} else {
    $chqdt_disp = '';
}

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

include("includes/linkshead.php");
?>
<style>
    body { background:#f0f2f5; margin:0; padding:10px 14px; }

    .sim-card {
        background:#fff;
        border-radius:10px;
        box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06);
        overflow:hidden;
        max-width:720px;
        margin:0 auto;
    }

    .sim-card-header {
        background:#fff;
        border-bottom:2px solid #f1f5f9;
        padding:12px 20px;
        display:flex;
        align-items:center;
        justify-content:space-between;
    }
    .sim-card-header h2 {
        font-size:15px;
        font-weight:700;
        color:#1e293b;
        margin:0;
        letter-spacing:.01em;
    }
    .sim-badge {
        font-size:11px;
        background:#f1f5f9;
        color:#64748b;
        border-radius:20px;
        padding:3px 10px;
        font-weight:600;
    }

    .sim-body { padding:22px 26px; }

    .fr {
        display:flex;
        align-items:center;
        gap:0;
        margin-bottom:12px;
    }
    .fr-pair {
        display:flex;
        gap:24px;
        margin-bottom:12px;
    }
    .fr-pair > .fr {
        flex:1;
        margin-bottom:0;
    }

    .lbl {
        width:140px;
        flex-shrink:0;
        text-align:right;
        padding-right:12px;
        font-size:12.5px;
        font-weight:500;
        color:#64748b;
        white-space:nowrap;
    }

    .finp {
        flex:1;
        padding:7px 11px;
        background:#f8fafc;
        border:1px solid #e2e8f0;
        border-radius:6px;
        font-size:12.5px;
        color:#1e293b;
        outline:none;
        transition:border-color .15s, background .15s, box-shadow .15s;
        width:100%;
        box-sizing:border-box;
        font-family:inherit;
    }
    .finp:focus {
        background:#fff;
        border-color:#3b82f6;
        box-shadow:0 0 0 3px rgba(59,130,246,.12);
    }
    .finp:disabled, .finp[readonly] {
        background:#f1f5f9;
        color:#64748b;
        border-color:#e2e8f0;
    }
    .finp.required-star { border-left:3px solid #3b82f6; }
    .finp.text-right { text-align:right; }

    .btn-bar {
        display:flex;
        justify-content:center;
        align-items:center;
        flex-wrap:wrap;
        gap:8px;
        padding:16px 20px;
        border-top:1px solid #f1f5f9;
        background:#fafafa;
    }
    .abtn {
        width:46px;
        height:46px;
        border-radius:10px;
        border:none;
        cursor:pointer;
        font-size:15px;
        color:#fff;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        text-decoration:none;
        transition:transform .12s, box-shadow .12s, filter .12s;
        position:relative;
    }
    .abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); filter:brightness(1.06); }
    .abtn:active { transform:translateY(0); box-shadow:none; filter:brightness(.95); }
    .abtn[disabled] { opacity:.4; pointer-events:none; }

    .abtn-prev   { background:#2563eb; }
    .abtn-next   { background:#38bdf8; }
    .abtn-search { background:#db2777; }
    .abtn-print  { background:#7c3aed; }
    .abtn-add    { background:#16a34a; }
    .abtn-edit   { background:#ea580c; }
    .abtn-del    { background:#dc2626; }
    .abtn-exit   { background:#e2e8f0; color:#64748b; }

    .abtn::after {
        content: attr(data-tip);
        position:absolute;
        bottom:calc(100% + 6px);
        left:50%;
        transform:translateX(-50%);
        background:#1e293b;
        color:#fff;
        font-size:10px;
        font-weight:600;
        padding:3px 8px;
        border-radius:4px;
        white-space:nowrap;
        opacity:0;
        pointer-events:none;
        transition:opacity .15s;
    }
    .abtn:hover::after { opacity:1; }

    .abtn-save   { width:auto; padding:0 18px; background:#16a34a; gap:6px; font-size:12.5px; font-weight:600; }
    .abtn-cancel { width:auto; padding:0 16px; background:#64748b; gap:6px; font-size:12.5px; font-weight:600; }

    .audit-info {
        margin-top:14px;
        padding-top:10px;
        border-top:1px dashed #e2e8f0;
        display:flex;
        flex-wrap:wrap;
        gap:16px;
        font-size:11px;
        color:#94a3b8;
    }
    .audit-info i { margin-right:4px; }
    .audit-info b { color:#64748b; }

    /* ── Bill settlement grid ─────────────────────────────────────────── */
    .grid-wrap { margin-top:6px; border:1px solid #e2e8f0; border-radius:8px; overflow-x:auto; }
    table.dgrid { width:100%; border-collapse:collapse; font-size:12px; }
    table.dgrid th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em;
        padding:8px 6px; border-bottom:2px solid #e2e8f0; text-align:center; white-space:nowrap;
    }
    table.dgrid td { padding:5px 6px; border-bottom:1px solid #f1f5f9; }
    table.dgrid td.num { text-align:right; }
    table.dgrid input.numfld {
        width:100%; box-sizing:border-box; padding:6px 8px; font-size:12px;
        border:1px solid #e2e8f0; border-radius:5px; background:#f8fafc; outline:none;
        text-align:right; font-family:inherit;
    }
    table.dgrid input.numfld:focus { background:#fff; border-color:#3b82f6; }
    table.dgrid input.numfld:disabled { background:#f1f5f9; color:#cbd5e1; }
    table.dgrid tfoot td {
        background:#f8fafc; font-weight:700; color:#1e293b; padding:8px 6px;
        border-top:2px solid #e2e8f0;
    }

    /* ── Responsive: tablet / mobile ──────────────────────────────────── */
    @media (max-width: 768px) {
        body { padding:6px 8px; }
        .sim-card { max-width:100%; border-radius:8px; }
        .sim-card-header { padding:10px 14px; }
        .sim-card-header h2 { font-size:13.5px; }
        .sim-body { padding:16px; }

        .fr, .fr-pair {
            flex-direction:column;
            align-items:stretch;
            gap:4px;
            margin-bottom:10px;
        }
        .fr-pair > .fr { margin-bottom:0; }

        .lbl {
            width:100%;
            text-align:left;
            padding-right:0;
            margin-bottom:2px;
        }
        .finp { font-size:13px; padding:8px 10px; }

        table.dgrid { font-size:11px; min-width:480px; }
        table.dgrid th, table.dgrid td { padding:5px 4px; }
        table.dgrid input.numfld { font-size:11px; padding:5px 4px; }

        .btn-bar { gap:6px; padding:12px 10px; }
        .abtn { width:42px; height:42px; font-size:13px; }
        .abtn::after { display:none; }
        .abtn-save, .abtn-cancel { font-size:12px; }
    }
</style>

<body>
<form action="" method="POST">

<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-circle-arrow-down" style="color:#3b82f6;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-pair">
            <div class="fr">
                <span class="lbl">Voucher No</span>
                <input type="text" class="finp" disabled value="<?php echo $qvouch > 0 ? $qvouch : 'New'; ?>">
            </div>
            <div class="fr">
                <span class="lbl">Date <span style="color:#ef4444;">*</span></span>
                <input type="text" name="vouchdt" id="vouchdt" class="finp form focusfield required-star datepick" required
                    placeholder="dd-mm-yyyy"
                    value="<?php echo htmlspecialchars($vouchdt_disp); ?>">
            </div>
        </div>

        <div class="fr-pair">
            <div class="fr">
                <span class="lbl"><?php echo ($bcgrp == '001') ? 'Bank Account' : 'Cash Account'; ?> <span style="color:#ef4444;">*</span></span>
                <select name="bankac" class="finp form required-star" required>
                    <option value="">-- Select --</option>
                    <?php
                    $mown = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `grpcode`='$bcgrp' ORDER BY `name`") or die(mysqli_error($conn));
                    while ($trow = mysqli_fetch_array($mown)) {
                        $sel = (isset($get[$bccol]) && $get[$bccol] == $trow['accode']) ? 'selected' : '';
                        echo '<option value="' . $trow['accode'] . '" ' . $sel . '>' . htmlspecialchars($trow['name']) . '</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="fr">
                <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>

        <?php if ($haschq): ?>
        <div class="fr-pair">
            <div class="fr">
                <span class="lbl">Cheque No.</span>
                <input type="text" name="chqno" class="finp form" maxlength="20"
                    value="<?php echo fv($get,'chqno'); ?>">
            </div>
            <div class="fr">
                <span class="lbl">Cheque Date</span>
                <input type="text" name="chqdt" class="finp form datepick" placeholder="dd-mm-yyyy"
                    value="<?php echo htmlspecialchars($chqdt_disp); ?>">
            </div>
        </div>
        <?php endif; ?>

        <div class="fr">
            <span class="lbl">Account <span style="color:#ef4444;">*</span></span>
            <select name="accode" id="accode" class="finp form select2 required-star" required style="flex:1;">
                <option value="">-- Select Account --</option>
                <?php
                mysqli_data_seek($acclist, 0);
                while ($arow = mysqli_fetch_array($acclist)) {
                    $sel = (isset($get['accode']) && $get['accode'] == $arow['accode']) ? 'selected' : '';
                    echo '<option value="' . $arow['accode'] . '" ' . $sel . '>' . htmlspecialchars($arow['name']) . '</option>';
                }
                ?>
            </select>
        </div>

        <div class="fr-pair">
            <div class="fr">
                <span class="lbl">FE Amount</span>
                <input type="number" step="any" name="feamt" id="feamt" class="finp form text-right" oninput="recalcAmt()"
                    value="<?php echo fvn($get,'feamt'); ?>">
            </div>
            <div class="fr">
                <span class="lbl">Rate of Exchange</span>
                <input type="number" step="any" name="roe" id="roe" class="finp form text-right" oninput="recalcAmt()"
                    value="<?php echo fvn($get,'roe','1'); ?>">
            </div>
        </div>

        <div class="fr">
            <span class="lbl">Amount <span style="color:#ef4444;">*</span></span>
            <input type="number" step="any" name="amount" id="amount" class="finp form text-right required-star" required readonly
                value="<?php echo fvn($get,'amount'); ?>">
        </div>

        <div id="billSettleBlock" style="display:none;margin-top:18px;padding-top:14px;border-top:1px dashed #e2e8f0;">
            <div style="font-size:12.5px;font-weight:700;color:#374151;margin-bottom:10px;">
                <i class="fa fa-file-invoice-dollar" style="color:#16a34a;margin-right:6px;"></i>Bill Settlement
                <span style="font-size:11px;color:#94a3b8;font-weight:500;">(outstanding Sale invoices for this customer)</span>
            </div>
            <div class="grid-wrap">
                <table class="dgrid" id="billSettleGrid">
                    <thead>
                        <tr>
                            <th style="width:30px;"></th>
                            <th style="text-align:left;">Invoice No</th>
                            <th style="text-align:left;">Date</th>
                            <th style="width:110px;">Bill Amount</th>
                            <th style="width:110px;">Outstanding</th>
                            <th style="width:130px;">Settle Amount</th>
                        </tr>
                    </thead>
                    <tbody id="billSettleBody">
                        <tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:14px;">Select a customer to view outstanding bills.</td></tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5" style="text-align:right;">Total Settled</td>
                            <td id="t_settleamt" style="text-align:right;">0.00</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="fr">
            <span class="lbl">Narration</span>
            <input type="text" name="narr" class="finp form" maxlength="100"
                value="<?php echo fv($get,'narr'); ?>">
        </div>

    </div><!-- /sim-body -->

    <div class="btn-bar">

        <button id="hprevious" type="button" class="abtn abtn-prev buttonform"
            style="display:<?php echo $pdisabled; ?>;"
            data-tip="Previous"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $prevvouch; ?>'"
            <?php echo $pdisabled1; ?>>
            <i class="fa fa-chevron-left"></i>
        </button>

        <button id="hnext" type="button" class="abtn abtn-next buttonform"
            style="display:<?php echo $ndisabled; ?>;"
            data-tip="Next"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $nextvouch; ?>'"
            <?php echo $ndisabled1; ?>>
            <i class="fa fa-chevron-right"></i>
        </button>

        <button id="hsearch" type="button" class="abtn abtn-search buttonform"
            style="display:<?php echo $searchdisabled; ?>;"
            data-tip="Search"
            onclick="document.getElementById('searchModal').style.display='flex'">
            <i class="fa fa-search"></i>
        </button>

        <button id="hprint" type="button" class="abtn abtn-print buttonform"
            style="display:<?php echo $printdisabled; ?>;"
            data-tip="Print"
            onclick="window.open('<?php echo $printfile . '?' . $keyfld . '=' . $qvouch; ?>','_blank')">
            <i class="fa fa-print"></i>
        </button>

        <button id="hadd" type="button" class="abtn abtn-add buttonform"
            style="display:<?php echo $adddisabled; ?>;"
            data-tip="Add New"
            onclick="window.location.href='<?php echo $file . '?mode=true'; ?>'">
            <i class="fa fa-plus"></i>
        </button>

        <button id="hedit" type="button" class="abtn abtn-edit buttonform"
            style="display:<?php echo $editdisabled; ?>;"
            data-tip="Edit">
            <i class="fa fa-pencil"></i>
        </button>

        <a id="hdelete" class="abtn abtn-del buttonform"
            style="display:<?php echo $deletedisabled; ?>;"
            data-tip="Delete"
            href="javascript:void(0)"
            onclick="confirmDelete('?delete&<?php echo $keyfld . '=' . $qvouch; ?>')">
            <i class="fa fa-trash"></i>
        </a>

        <button id="hexit" type="button" class="abtn abtn-exit buttonform"
            style="display:<?php echo $exitdisabled; ?>;"
            data-tip="Exit"
            onclick="window.location.href='default.php'">
            <i class="fa fa-power-off"></i>
        </button>

        <button id="ssubmit" type="submit" name="submit"
            value="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            class="abtn abtn-save buttonform"
            data-tip="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            style="display:<?php echo $savedisabled; ?>;">
            <i class="fa fa-check"></i>
            <?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>
        </button>

        <button id="scancel" type="button"
            class="abtn abtn-cancel buttonform"
            data-tip="Cancel"
            style="display:<?php echo $canceldisabled; ?>;"
            onclick="window.location.href='<?php echo $file . '?mode=last'; ?>'">
            <i class="fa fa-times"></i> Cancel
        </button>

    </div>

</div><!-- /sim-card -->
</form>


<!-- ── 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:900px;overflow:hidden;
                box-shadow:0 24px 64px rgba(0,0,0,.3);max-height:85vh;display:flex;flex-direction:column;">

        <div style="padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f1f5f9;">
            <span style="font-size:14px;font-weight:700;color:#1e293b;">
                <i class="fa fa-search" style="color:#db2777;margin-right:8px;"></i>Search <?php echo $formname; ?>
            </span>
            <button type="button"
                style="background:#f1f5f9;border:none;color:#64748b;width:30px;height:30px;border-radius:6px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;"
                onclick="document.getElementById('searchModal').style.display='none'">&times;</button>
        </div>

        <div style="padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;flex-wrap:wrap;gap:8px;align-items:end;background:#fafbfc;">
            <div style="flex:1;min-width:160px;">
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Account Name / Voucher No</label>
                <input type="text" id="srchInput" placeholder="Type to search..."
                    style="width:100%;padding:7px 11px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;box-sizing:border-box;">
            </div>
            <div>
                <button type="button" id="srchGoBtn"
                    style="padding:8px 18px;border-radius:6px;border:none;background:#2563eb;color:#fff;font-size:12.5px;font-weight:600;cursor:pointer;">
                    <i class="fa fa-search"></i> Search
                </button>
            </div>
        </div>

        <div style="overflow:auto;flex:1;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="position:sticky;top:0;background:#f8fafc;">
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Voucher No</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Date</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;"><?php echo ($bcgrp == '001') ? 'Bank' : 'Cash'; ?></th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Account</th>
                        <th style="padding:9px 14px;text-align:right;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Amount</th>
                    </tr>
                </thead>
                <tbody id="srchBody"></tbody>
            </table>
        </div>

        <div style="display:flex;border-top:1px solid #f1f5f9;">
            <button type="button" id="srchPrevBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-right:1px solid #f1f5f9;">
                <i class="fa fa-chevron-left"></i> Previous
            </button>
            <span id="srchPageInfo" style="padding:10px 16px;font-size:12px;color:#64748b;white-space:nowrap;align-self:center;"></span>
            <button type="button" id="srchNextBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-left:1px solid #f1f5f9;">
                Next <i class="fa fa-chevron-right"></i>
            </button>
        </div>

    </div>
</div>

<script>
function recalcAmt() {
    var fe  = parseFloat(document.getElementById('feamt').value) || 0;
    var roe = parseFloat(document.getElementById('roe').value) || 0;
    var amt = fe * roe;
    document.getElementById('amount').value = amt ? amt.toFixed(2) : '';
}

// Default ROE to 1 for INR
$('#currency').on('change', function () {
    if ($(this).val() === 'INR' && (!$('#roe').val() || $('#roe').val() == '0')) {
        $('#roe').val('1');
        recalcAmt();
    }
});

// ── Bill Settlement ───────────────────────────────────────────────────────────
var existingSettle = <?php echo json_encode($existingSettle); ?>;
var currentVouchNo  = <?php echo (int)$qvouch; ?>;

function isFormEditable() {
    // Mirrors linkshead.php's disable mechanism: fields are editable only in
    // Add mode (addflag==1) or after #hedit has been clicked (which removes
    // the disabled attribute from .form elements).
    var probe = document.getElementById('vouchdt');
    return probe ? !probe.disabled : true;
}

function loadOutstandingBills() {
    var accode = $('#accode').val();
    if (!accode) {
        $('#billSettleBlock').hide();
        $('#billSettleBody').html('<tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:14px;">Select a customer to view outstanding bills.</td></tr>');
        recalcSettle();
        return;
    }
    $.post('includes/outstanding_bills.php', {
        accode: accode,
        exclvouch: currentVouchNo,
        exclsource: '<?php echo $source; ?>'
    }, function (data) {
        if (!data.ok) return;
        if (data.bills.length === 0) {
            $('#billSettleBlock').hide();
            $('#billSettleBody').html('');
            recalcSettle();
            return;
        }
        $('#billSettleBlock').show();
        var editable = isFormEditable();
        var chkDisabled = editable ? '' : 'disabled';
        var html = '';
        data.bills.forEach(function (b) {
            var presetAmt = existingSettle[b.vouchno] ? existingSettle[b.vouchno] : '';
            var checked = presetAmt ? 'checked' : '';
            var amtDisabled = (checked && editable) ? '' : 'disabled';
            html += '<tr>'
                + '<td style="text-align:center;"><input type="checkbox" class="billChk form" onchange="toggleBillRow(this)"' + checked + ' ' + chkDisabled + '></td>'
                + '<td style="font-weight:600;color:#2563eb;">' + b.vouchno + '</td>'
                + '<td>' + b.vouchdt + '</td>'
                + '<td class="num">' + b.totamt.toFixed(2) + '</td>'
                + '<td class="num">' + b.outstanding.toFixed(2) + '</td>'
                + '<td><input type="hidden" name="billno[]" value="' + b.vouchno + '">'
                + '<input type="number" step="any" class="numfld form billAmt" name="settleamt[]" '
                + 'max="' + b.outstanding + '" value="' + presetAmt + '" '
                + amtDisabled + ' oninput="recalcSettle()"></td>'
                + '</tr>';
        });
        $('#billSettleBody').html(html);
        recalcSettle();
    }, 'json');
}

function toggleBillRow(chk) {
    var tr = chk.closest('tr');
    var inp = tr.querySelector('.billAmt');
    var outstandingTd = tr.querySelectorAll('td.num')[1];
    if (chk.checked) {
        inp.disabled = false;
        if (!inp.value) inp.value = outstandingTd.textContent;
    } else {
        inp.disabled = true;
        inp.value = '';
    }
    recalcSettle();
}

function recalcSettle() {
    var total = 0;
    document.querySelectorAll('#billSettleGrid .billAmt').forEach(function (inp) {
        if (!inp.disabled && inp.value !== '') {
            var v = parseFloat(inp.value);
            if (!isNaN(v)) total += v;
        }
    });
    document.getElementById('t_settleamt').textContent = total.toFixed(2);
    var amount = parseFloat(document.getElementById('amount').value) || 0;
    var cell = document.getElementById('t_settleamt');
    cell.style.color = (amount > 0 && total > amount + 0.005) ? '#dc2626' : '';
}

$('#accode').on('change', loadOutstandingBills);
$('#amount').on('input', recalcSettle);
if ($('#accode').val()) {
    loadOutstandingBills();
}

// When Edit is clicked, linkshead.php's global handler re-enables all .form
// elements that exist at that moment. The bill-settlement rows just need to
// also have their checkbox re-enabled (already covered since it now carries
// the .form class), but re-run a pass here too in case the rows were loaded
// before #hedit fires (defensive, matches linkshead.php's own behavior).
$('#hedit').on('click', function () {
    setTimeout(function () {
        document.querySelectorAll('#billSettleGrid .billChk').forEach(function (chk) {
            chk.disabled = false;
        });
    }, 0);
});

var srchPage = 1;
var srchPages = 1;

function srchLoad(page) {
    srchPage = page;
    $.post('includes/bankcashtxn_search.php', {
        table: '<?php echo $maindb; ?>',
        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);
});
</script>

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