<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$supplier_id = '';
$purchase_reference_code = '';
$amount = '';
$payment_type = '';
$from_bank_name = '';
$account_no = '';
$cheque_no = '';
$cheque_bank_name = '';
$cheque_date = '';
$cheque_payee = '';
$hide = '';
$party_name = '';
$bank_name = '';
$description = '';
$payment_date = '';
$paymentmode = ''; // NEW: to control purchase status (partial / paid)

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

$current_date = date('d-m-Y');

// ===== HANDLE ADD / EDIT / REF =====
if (isset($_GET['add']) || isset($_GET['edit'])) {

    if (isset($_GET['edit'])) {
        // ---------- EDIT MODE ----------
        extract($_REQUEST);
        $getPayment = Purpayment::GetPurpaymentSetupById($id);

        if ($getPayment) {
            $supplier_id             = $getPayment->supplier_id;
            $purchase_reference_code = $getPayment->purchase_reference_code;
            $payment_type            = $getPayment->payment_type;
            $amount                  = $getPayment->amount;
            $party_name              = $getPayment->party_name;
            $from_bank_name          = $getPayment->from_bank_name;
            $cheque_no               = $getPayment->cheque_number;
            $cheque_bank_name        = $getPayment->cheque_bank_name;
            $cheque_payee            = $getPayment->cheque_payee_name;
            $cheque_date             = !empty($getPayment->cheque_date) && $getPayment->cheque_date != '0000-00-00 00:00:00'
                                        ? date('d-m-Y', strtotime($getPayment->cheque_date))
                                        : '';
            $bank_name               = $getPayment->bank_name;
            $account_no              = $getPayment->bank_account_number;
            $payment_date            = !empty($getPayment->create_date)
                                        ? date('d-m-Y', strtotime($getPayment->create_date))
                                        : $current_date;
            $paymentNumber           = $getPayment->code;
            $description             = $getPayment->description;

            // Fetch purchase status to pre-fill Payment Mode
            if (!empty($purchase_reference_code)) {
                $pRows = PurchaseSetup::GetPurchaseList(" WHERE id = '".intval($purchase_reference_code)."' ");
                if ($pRows) {
                    $paymentmode = $pRows[0]->status; // 'posted' or 'Paid'
                }
            }
        }

    } else if (isset($_GET['add']) || isset($_GET['ref'])) {
        // ---------- ADD MODE ----------
        // Get next payment number
        $paymentfilter = " ORDER BY id DESC LIMIT 1 ";
        $payments = Purpayment::GetPurpaymentList($paymentfilter);
        if (!empty($payments[0]->code)) {
            $paymentNumber = intval($payments[0]->code) + 1;
        } else {
            $paymentNumber = __PURPAYMENT__;
        }

        // If coming from purchase page: ?add&ref=PURCHASE_ID
        if (isset($_GET['ref']) && ctype_digit($_GET['ref'])) {
            $purchaseId = (int)$_GET['ref'];

            // fetch that purchase
            $purchaseRows = PurchaseSetup::GetPurchaseList(" WHERE id = '".$purchaseId."' ");
            if ($purchaseRows) {
                $pRow = $purchaseRows[0];

                $purchase_reference_code = $pRow->id;
                $supplier_id             = $pRow->supplier_id;
                $payment_date            = $current_date;

                // prefill payment mode from current purchase status
                $paymentmode = $pRow->status; // 'posted' or maybe 'Paid'

                // calculate remaining balance:
                $totalPurchase = (float)$pRow->total_amount;

                $paidSoFar = 0;
                $payFilter = " WHERE purchase_reference_code = '".$purchase_reference_code."' AND status <> 'Cancel' ";
                $existingPays = Purpayment::GetPurpaymentList($payFilter);
                if ($existingPays) {
                    foreach ($existingPays as $payRow) {
                        $paidSoFar += (float)$payRow->amount;
                    }
                }

                $remaining = $totalPurchase - $paidSoFar;
                if ($remaining < 0) {
                    $remaining = 0;
                }
                $amount = $remaining;
            } else {
                // fallback if purchase not found
                $payment_date = $current_date;
            }
        } else {
            // normal add without ref
            $payment_date = $current_date;
        }
    }
}

// ===== Build display label for Purchase Reference (for both add/edit) =====
$purchaseDisplay = '';
if (!empty($purchase_reference_code)) {
    $purchaseRowsForDisplay = PurchaseSetup::GetPurchaseList(" WHERE id = '".intval($purchase_reference_code)."' ");
    if ($purchaseRowsForDisplay) {
        $pDisp = $purchaseRowsForDisplay[0];
        $purchaseDisplay = $pDisp->po_number . ' (' . $pDisp->date . ')';
    }
}

// ===== HANDLE POST (SAVE) =====
if (isset($_POST) && !empty($_POST)) {
    extract($_REQUEST);

    $paymentmode = isset($_POST['paymentmode']) ? $_POST['paymentmode'] : ''; // NEW

    $data['supplier_id']             = $supplier_name;
    $data['purchase_reference_code'] = $purchase_reference_code;
    $data['code']                    = $payment_number;
    $data['payment_type']            = $payment_type;
    $data['amount']                  = $amount;
    $data['party_name']              = $party_name;
    $data['from_bank_name']          = $from_bank_name;
    $data['cheque_number']           = $cheque_no;
    $data['cheque_bank_name']        = $cheque_bank_name;
    $data['cheque_payee_name']       = $cheque_payee;
    $data['cheque_date']             = !empty($cheque_date)
                                        ? date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($cheque_date)))
                                        : '0000-00-00 00:00:00';
    $data['bank_name']               = $bank_name;
    $data['bank_account_number']     = $account_no;
    $data['description']             = $description;
    $data['create_date']             = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($payment_date)));
    $data['datetime']                = 'NOW()';

    $errors = array();

    // Validate duplicate cheque number (for bank payments)
    $filterPayments = " WHERE cheque_number = '$cheque_no'";
    $checkPayments  = Purpayment::GetPurpaymentList($filterPayments);

    if (isset($_GET['add']) || isset($_GET['ref'])) {
        if (!empty($checkPayments) && $payment_type == 'bank') {
            array_push($errors, "Cheque No Already Exists");
        }
    }

    // Basic validation
    if ((strlen($supplier_name) == 0) || (strlen($supplier_name) > 255))
        array_push($errors, "Please enter supplier name");
    if ((strlen($payment_date) == 0))
        array_push($errors, "Please enter payment date");
    if ((strlen($payment_type) == 0))
        array_push($errors, "Please enter payment type");
    if ((strlen($amount) == 0 || $amount == 0))
        array_push($errors, "Please enter payment amount");
    if ($payment_type == 'bank' || $payment_type == 'cash' || $payment_type == 'online') {
        if ((strlen($bank_name) == 0))
            array_push($errors, "Please select Payment From (Cash / Bank)");
    }

    // Only if linked to a purchase, require a paymentmode
    if (!empty($purchase_reference_code) && (strlen($paymentmode) == 0)) {
        array_push($errors, "Please select Payment Mode (Partial / Paid) for this purchase.");
    }

    // ===== NEW: Check available balance in selected Cash / Bank account =====
    if (($payment_type == 'cash' || $payment_type == 'bank' || $payment_type == 'online') && !empty($bank_name)) {

        // Current available balance from tables: payment, purpayment, expense
        $availableBalance = BankSetup::GetBankBalance($bank_name);

        // If editing an existing payment on the same bank, add its own amount back
        if (isset($_GET['edit']) && isset($_GET['id'])) {
            $oldPayment = Purpayment::GetPurpaymentSetupById($_GET['id']);
            if ($oldPayment
                && (int)$oldPayment->bank_name == (int)$bank_name
                && in_array($oldPayment->payment_type, ['cash','bank','online'])
            ) {
                $availableBalance += (float)$oldPayment->amount;
            }
        }

        if ((float)$amount > $availableBalance) {
            $errors[] = "Insufficient balance in selected account. "
                . "Available: " . number_format($availableBalance, 2)
                . " | Trying to pay: " . number_format((float)$amount, 2);
        }
    }
    // ===== END NEW BALANCE CHECK =====

    if (count($errors) == 0) {
        if (isset($_GET['add']) || isset($_GET['ref'])) {
            $q = Purpayment::AddPurpayment($data);
        } else {
            $q = Purpayment::UpdatePurpaymentSetup($id, $data);
        }

        if ($q) {
            // NEW: update Purchase status based on paymentmode (if purchase linked)
            if (!empty($purchase_reference_code) && !empty($paymentmode)) {
                $purchaseUpdateData = [
                    'status' => $paymentmode   // 'posted' (partial) or 'Paid' (full)
                ];
                PurchaseSetup::UpdatePurchase($purchase_reference_code, $purchaseUpdateData);
            }

            $output = '';
            ?>
            <script>window.location.href = 'purchase_setup.php?view&sucess'</script>
            <?php
            echo "<div class='alert alert-success fade in'>
              <button type='button' class='close' data-dismiss='alert'>&times;</button>
              <strong>Attention!</strong> Submitted! </div>";
        } else {
            $output = '';
            echo "<div class='alert alert-error fade in'>
              <button type='button' class='close' data-dismiss='alert'>&times;</button>
              <strong>Attention!</strong> Some error occured! </div>";
        }
    } else {
        //Prepare errors for output
        foreach ($errors as $val) {
            $output .= "<div class='alert alert-warning fade in'>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                <strong>Attention! </strong>$val</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: true,
            });
            $('#cheque_date').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: true,
            });
        });
    </script>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Purchase Payment</h3>
            </div>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <form action="" method="post" id="purpayment_create_form" novalidate="novalidate">
                <div class="row">
                    <div class="col s12 form-group">
                        <?php echo $output; ?>
                        <div class="row">
                            <div class="col m6 s12">
                                <label class="control-label">Sales Person *</label>
                                <input class="form-control" type="text" id="sales_person"
                                       name="sales_person" readonly
                                       value='<?php echo $_SESSION['sess_username']; ?>'/>
                                <input class="form-control" type="hidden" id="sales_person_id"
                                       name="sales_person_id"
                                       value='<?php echo $_SESSION['sess_userid']; ?>'/><br/>
                            </div>
                            <div class="col m6 s12">
                                <label class="control-label">Payment No. *</label>
                                <input class="form-control" type="text" id="payment_number"
                                       name="payment_number" readonly
                                       value='<?php echo $paymentNumber; ?>'/><br/>
                            </div>
                        </div>



                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m6 s12">
                                <label class="control-label">Supplier *</label>
                                <?php
                                $suppliers = SupplierSetup::GetSupplierSetupList();
                                ?>
                                <select class="form-control" required id="supplier_name"
                                        name="supplier_name">
                                    <option></option>
                                    <?php
                                    if ($suppliers) {
                                        foreach ($suppliers AS $suppliersRow) {
                                            echo '<option ';
                                            if ($suppliersRow->id == $supplier_id) {
                                                echo 'selected';
                                            }
                                            echo ' value="' . $suppliersRow->id . '" >' . $suppliersRow->name . '</option>';
                                        }
                                    }
                                    ?>
                                </select><br/>
                            </div>
                            <div class="col m6 s12">
                                <label class="control-label">Payment Date *</label>
                                <input class="form-control" required type="text" id="datepicker"
                                       name="payment_date"
                                       placeholder="<?= date('01-01-Y') ?>"
                                       value='<?= !empty($payment_date) ? $payment_date : $current_date; ?>'/>

                            </div>
                        </div>

                        <!-- Hidden purchase_reference_code + visible display -->
                        <input type="hidden" name="purchase_reference_code"
                               value="<?php echo htmlspecialchars($purchase_reference_code); ?>"/>

                        <?php if (!empty($purchase_reference_code) && !empty($purchaseDisplay)) { ?>
                            <div class="row">
                                <div class="col m6 s12">
                                    <label class="control-label">Purchase Reference</label>
                                    <input class="form-control" type="text"
                                           value="<?php echo htmlspecialchars($purchaseDisplay); ?>"
                                           readonly /><br/>
                                </div>

                        <?php } ?>

                        <!-- NEW: Payment Mode (Partial / Paid) -->
                        <?php if (!empty($purchase_reference_code)) { ?>

                            <div class="col m6 s12">
                                <label class="control-label">Payment Mode</label>
                                <select class="form-control" id="paymentmode" name="paymentmode">
                                    <!-- 'posted' means partially paid -->
                                    <option value="posted" <?= $paymentmode === 'posted' ? 'selected' : '' ?>>
                                        Partial Payment
                                    </option>
                                    <!-- 'Paid' is fully paid -->
                                    <option value="Paid" <?= $paymentmode === 'Paid' ? 'selected' : '' ?>>
                                        Full Payment
                                    </option>
                                </select><br/>
                            </div>
                       </div>
                        <?php } ?>



                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m6 s12">
                                <label class="control-label">Payment Type *</label>
                                <select class="form-control" id="payment_type" required
                                        name="payment_type">
                                    <option></option>
                                    <option <?= $payment_type == 'cash' ? 'selected' : '' ?>
                                        value="cash">Cash
                                    </option>
                                    <option <?= $payment_type == 'bank' ? 'selected' : '' ?>
                                        value="bank">Bank
                                    </option>
                                    <option <?= $payment_type == 'party' ? 'selected' : '' ?>
                                        value="party">Party
                                    </option>
                                    <option <?= $payment_type == 'online' ? 'selected' : '' ?>
                                        value="online">Online
                                    </option>
                                </select><br/>
                            </div>
                            <div class="col m6 s12">
                                <label class="control-label">Amount *</label>
                                <input class="form-control" placeholder="00000.00"
                                       onkeypress="return isDoubleNumberKey(event)" required type="text"
                                       id="amount"
                                       value="<?= $amount ?>"
                                       name="amount"/><br/>

                            </div>
                        </div>

                        <div class="row">
                            <div id="bankDetails">
                                <div <?= $payment_type != 'party' ? 'style="display:none;"' : '' ?>
                                    class="col m6 s12" id="party_name_detail">
                                    <label class="control-label">Party Name</label>
                                    <input class="form-control" type="text" id="party_name"
                                        <?php if ($payment_type != 'party') {
                                            echo 'disabled';
                                        } ?> name="party_name" value="<?= $party_name ?>"/><br/>
                                </div>
                                <div <?= $payment_type != 'online' ? 'style="display:none;"' : '' ?>
                                    class="col m6 s12" id="from_bank_name_detail">
                                    <label class="control-label">To Bank Name</label>
                                    <input class="form-control" type="text" id="from_bank_name"
                                        <?php if ($payment_type != 'online') {
                                            echo 'disabled';
                                        } ?> name="from_bank_name" value="<?= $from_bank_name ?>"/><br/>
                                </div>
                                <div class="clearfix"></div>
                                <br>

                                <div class="col m6 s12">
                                    <label class="control-label">Payment From (Cash / Bank) *</label>
                                    <?php
                                    $bankfilter = " WHERE status = 'active' ORDER BY bank_name";
                                    $banks = BankSetup::GetBankSetupList($bankfilter);
                                    ?>
                                    <select class="form-control" id="bank_name" required
                                            name="bank_name">
                                        <option></option>
                                        <?php
                                        if ($banks) {
                                            foreach ($banks AS $banksRow) {
                                                echo '<option ';
                                                if ($banksRow->id == $bank_name) {
                                                    echo 'selected';
                                                }
                                                echo ' value="' . $banksRow->id . '" >' . $banksRow->bank_name . '</option>';
                                            }
                                        }
                                        ?>
                                    </select><br/>
                                    <small><em>Select Cash Amount, Faysal Bank, Upaisa, etc.</em></small><br/>
                                    <!-- NEW: show current balance -->
                                    <small>
                                        <strong>Available Balance: </strong>
                                        <span id="bank_balance_display">0.00</span>
                                    </small>
                                    <input type="hidden" id="bank_balance" value="0">
                                </div>
                                <div class="col m6 s12">
                                    <label class="control-label">Account No.</label>
                                    <input class="form-control" readonly type="text" id="account_no"
                                           name="account_no" value="<?= $account_no ?>"/><br/>
                                </div>
                            </div>
                        </div>
                        <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                            $hide = 'style="display:none;"';
                        } ?>
                        <div <?= $hide ?> class="row" id="chequeDetails">
                            <div class="col m6 s12">
                                <label class="control-label">Cheque No.</label>
                                <input class="form-control" type="text" id="cheque_no"
                                    <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                                        echo 'disabled';
                                    } ?> name="cheque_no" value="<?= $cheque_no ?>"/><br/>
                            </div>
                            <div class="col m6 s12">
                                <label class="control-label">Cheque Bank</label>
                                <input class="form-control" type="text" id="cheque_bank_name"
                                    <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                                        echo 'disabled';
                                    } ?> name="cheque_bank_name" value="<?= $cheque_bank_name ?>"/><br/>
                            </div>
                            <div class="clearfix"></div>
                            <br>

                            <div class="col m6 s12">
                                <label class="control-label">Cheque Date</label>
                                <input class="form-control" type="text" id="cheque_date"
                                    <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                                        echo 'disabled';
                                    } ?> name="cheque_date" value="<?= $cheque_date ?>"/><br/>
                            </div>
                            <div class="col m6 s12">
                                <label class="control-label">Cheque Payee</label>
                                <input class="form-control" type="text" id="cheque_payee"
                                    <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                                        echo 'disabled';
                                    } ?> name="cheque_payee" value="<?= $cheque_payee ?>"/><br/>
                            </div>
                            <div class="clearfix"></div>
                            <br>
                        </div>
                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m12 s12">
                                <label class="control-label">Description</label>
                                <input class="form-control" type="text" id="description"
                                       name="description" value="<?= $description ?>"/><br/>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <br><br>
                    </div>
                </div>

                <div class="clearfix"></div>
                <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit</button>
                <button type="button" class="btn waves-effect waves-light"
                        onclick="location.href='purpayment.php?view'">Cancel
                </button>
            </form>
            <?php
            // close view
            ?>
        </div>
    </div>
</div>
<footer>
    <?php include('includes/inc_footer.php'); ?>
</footer>
</div>
</section>

<?php include('includes/inc_js.php'); ?>

<script type="application/javascript">
    <?php if(isset($_GET['edit']) && $payment_type == 'bank'){?>
    $(document).ready(function () {
        $('#bankDetails').show();
        $('#bank_name').attr('required', true);
        $('#bank_name').attr('disabled', false);
        $('#party_name').attr('required', true);
        $('#party_name').attr('disabled', false);
        $('#cheque_no').attr('disabled', false);
        $('#cheque_bank_name').attr('disabled', false);
        $('#cheque_payee').attr('disabled', false);
        $('#cheque_date').attr('disabled', false);
        $('#account_no').attr('disabled', false);
        $('#bank_name').rules('add', {
            required: true,
            messages: {
                required: "<span class='label label-warning val_mes'>Please select bank name</span>"
            }
        });
    });
    <?php }?>
    $('#payment_type').on('change', function () {
        if ($(this).val() == 'bank') {
            $('#chequeDetails').show();
            $('#party_name_detail').hide();
            $('#from_bank_name_detail').hide();

            $('#bank_name').attr('required', true);
            $('#bank_name').attr('disabled', false);
            $('#bank_name').rules('add', {
                required: true,
            });

            $('#account_no').attr('required', true);
            $('#account_no').attr('disabled', false);
            $('#account_no').rules('add', {
                required: true,
            });

            $('#from_bank_name').attr('required', false);
            $('#from_bank_name').attr('disabled', true);
            $('#from_bank_name').rules('add', {
                required: false,
            });

            $('#party_name').attr('required', false);
            $('#party_name').attr('disabled', true);
            $('#party_name').rules('add', {
                required: false,
            });

            $('#cheque_no').attr('required', true);
            $('#cheque_no').attr('disabled', false);
            $('#cheque_no').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque number</span>"
                }
            });

            $('#cheque_bank_name').attr('required', true);
            $('#cheque_bank_name').attr('disabled', false);
            $('#cheque_bank_name').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque bank name</span>"
                }
            });

            $('#cheque_payee').attr('required', true);
            $('#cheque_payee').attr('disabled', false);
            $('#cheque_payee').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque payee name</span>"
                }
            });

            $('#cheque_date').attr('required', true);
            $('#cheque_date').attr('disabled', false);
            $('#cheque_date').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque date</span>"
                }
            });
        } else if ($(this).val() == 'cash') {
            $('#chequeDetails').hide();
            $('#party_name_detail').hide();
            $('#from_bank_name_detail').hide();

            $('#bank_name').attr('required', true);
            $('#bank_name').attr('disabled', false);
            $('#bank_name').rules('add', {
                required: true,
            });

            $('#account_no').attr('required', true);
            $('#account_no').attr('disabled', false);
            $('#account_no').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter account number</span>"
                }
            });

            $('#from_bank_name').attr('required', false);
            $('#from_bank_name').attr('disabled', true);
            $('#from_bank_name').rules('add', {
                required: false,
            });

            $('#party_name').attr('required', false);
            $('#party_name').attr('disabled', true);
            $('#party_name').rules('add', {
                required: false,
            });

            $('#cheque_no').attr('required', false);
            $('#cheque_no').attr('disabled', true);
            $('#cheque_no').rules('add', {
                required: false,
            });

            $('#cheque_bank_name').attr('required', false);
            $('#cheque_bank_name').attr('disabled', true);
            $('#cheque_bank_name').rules('add', {
                required: false,
            });

            $('#cheque_payee').attr('required', false);
            $('#cheque_payee').attr('disabled', true);
            $('#cheque_payee').rules('add', {
                required: false,
            });

            $('#cheque_date').attr('required', false);
            $('#cheque_date').attr('disabled', true);
            $('#cheque_date').rules('add', {
                required: false,
            });
        } else if ($(this).val() == 'party') {
            $('#chequeDetails').show();
            $('#party_name_detail').show();
            $('#from_bank_name_detail').hide();

            $('#bank_name').attr('required', false);
            $('#bank_name').attr('disabled', true);
            $('#bank_name').rules('add', {
                required: false,
            });

            $('#account_no').attr('required', false);
            $('#account_no').attr('disabled', true);
            $('#account_no').rules('add', {
                required: false,
            });

            $('#from_bank_name').attr('required', false);
            $('#from_bank_name').attr('disabled', true);
            $('#from_bank_name').rules('add', {
                required: false,
            });

            $('#party_name').attr('required', true);
            $('#party_name').attr('disabled', false);
            $('#party_name').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter party name</span>"
                }
            });

            $('#cheque_no').attr('required', true);
            $('#cheque_no').attr('disabled', false);
            $('#cheque_no').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque number</span>"
                }
            });

            $('#cheque_bank_name').attr('required', true);
            $('#cheque_bank_name').attr('disabled', false);
            $('#cheque_bank_name').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque bank name</span>"
                }
            });

            $('#cheque_payee').attr('required', true);
            $('#cheque_payee').attr('disabled', false);
            $('#cheque_payee').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque payee name</span>"
                }
            });

            $('#cheque_date').attr('required', true);
            $('#cheque_date').attr('disabled', false);
            $('#cheque_date').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque date</span>"
                }
            });
        } else if ($(this).val() == 'online') {
            $('#chequeDetails').hide();
            $('#party_name_detail').hide();
            $('#from_bank_name_detail').show();

            $('#bank_name').attr('required', true);
            $('#bank_name').attr('disabled', false);
            $('#bank_name').rules('add', {
                required: true,
            });

            $('#account_no').attr('required', true);
            $('#account_no').attr('disabled', false);
            $('#account_no').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter account number</span>"
                }
            });

            $('#from_bank_name').attr('disabled', false);

            $('#party_name').attr('required', false);
            $('#party_name').attr('disabled', true);
            $('#party_name').rules('add', {
                required: false,
            });

            $('#cheque_no').attr('required', false);
            $('#cheque_no').attr('disabled', true);
            $('#cheque_no').rules('add', {
                required: false,
            });

            $('#cheque_bank_name').attr('required', false);
            $('#cheque_bank_name').attr('disabled', true);
            $('#cheque_bank_name').rules('add', {
                required: false,
            });

            $('#cheque_payee').attr('required', false);
            $('#cheque_payee').attr('disabled', true);
            $('#cheque_payee').rules('add', {
                required: false,
            });

            $('#cheque_date').attr('required', false);
            $('#cheque_date').attr('disabled', true);
            $('#cheque_date').rules('add', {
                required: false,
            });
        }
    });

    // UPDATED: also fetch bank balance
    $('#bank_name').on('change', function () {
        var bankId = $(this).val();

        $('body.container').block({message: 'Loading...'});
        $.get('transaction/getBankDetails.php?id=' + bankId, function (data) {
            $("#account_no").val(data);
            $('body.container').unblock();
        });

        $('#cheque_bank_name').val($('#bank_name :selected').text());

        if (bankId) {
            $.getJSON('getBankBalance.php', { bank_id: bankId }, function (res) {
                if (res && res.success) {
                    var bal = parseFloat(res.balance) || 0;
                    $('#bank_balance').val(bal.toFixed(2));
                    $('#bank_balance_display').text(bal.toFixed(2));
                } else {
                    $('#bank_balance').val('0');
                    $('#bank_balance_display').text('0.00');
                }
            }).fail(function () {
                $('#bank_balance').val('0');
                $('#bank_balance_display').text('0.00');
            });
        } else {
            $('#bank_balance').val('0');
            $('#bank_balance_display').text('0.00');
        }
    });

    function isDoubleNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });

        // If bank already selected (edit mode), load its balance
        if ($('#bank_name').val() !== '') {
            $('#bank_name').trigger('change');
        }

        // NEW: live check when typing amount
        $('#amount').on('input blur', function () {
            var pt  = $('#payment_type').val();
            var bankId = $('#bank_name').val();
            var bal = parseFloat($('#bank_balance').val()) || 0;
            var amt = parseFloat($(this).val()) || 0;

            // Only enforce for cash/bank/online with a selected bank account
            if ((pt === 'cash' || pt === 'bank' || pt === 'online') && bankId) {
                if (amt > bal) {
                    alert("Insufficient balance in selected account.\n" +
                          "Available: " + bal.toFixed(2));
                    // Optional: clamp down to max balance or clear
                    $(this).val(bal > 0 ? bal.toFixed(2) : '');
                }
            }
        });

        // NEW: hard stop on submit
        $('#purpayment_create_form').on('submit', function (e) {
            var pt  = $('#payment_type').val();
            var bankId = $('#bank_name').val();
            var bal = parseFloat($('#bank_balance').val()) || 0;
            var amt = parseFloat($('#amount').val()) || 0;

            if ((pt === 'cash' || pt === 'bank' || pt === 'online') && bankId && amt > bal) {
                e.preventDefault();
                alert("You cannot pay more than the available balance in this account.\n" +
                      "Available: " + bal.toFixed(2) +
                      " | Trying to pay: " + amt.toFixed(2));
                return false;
            }
        });
    });
</script>
</body>
</html>
