<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$supplier_id = '';
$amount = '';
$amount_payable = '';
$payment_type = '';
$purchase_reference_code = '';
$withholding_tax_amount = '';
$withholding_tax = '';
$advance_payment = 'No';
$from_bank_name = '';
$account_no = '';
$cheque_no = '';
$cheque_bank_name = '';
$cheque_date = '';
$cheque_payee = '';
$hide = '';
$party_name = '';
$bank_name = '';
$description = '';
$tax_category_id = '';
$psid = '';
$cpr = '';
$supplier_payment_type = '';
$payment_staus = 'pending';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
$current_date = date('d-m-Y');
?>
<!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,
            });
          $('#deposit_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/>
            <?php
            if (isset($_GET['add']) || isset($_GET['edit'])) {
                if (isset($_GET['edit'])) {
                    extract($_REQUEST);
                  	
                    $getPayment = Purpayment::GetPurpaymentSetupById($id);
                    $supplier_id = $getPayment->supplier_id;
                    $payment_type = $getPayment->payment_type;
                  	$purchase_reference_code = $getPayment->purchase_reference_code;
                  	$purchaseDetails = PurchaseSetup::GetPurchaseSetupById($purchase_reference_code);
					$purchase_status = $purchaseDetails->status;
                  	$amount = $getPayment->amount;
                  	$withholding_tax = $getPayment->withholding_tax;
                  	$withholding_tax_amount = $getPayment->withholding_tax_amount;
                  	$advance_payment = $getPayment->advance_payment;
                    $amount_payable = $getPayment->amount_payable;
                    $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 = date('d-m-Y', strtotime($getPayment->cheque_date));
                    $bank_name = $getPayment->bank_name;
                    $account_no = $getPayment->bank_account_number;
                    $payment_date = date('d-m-Y', strtotime($getPayment->create_date));
                    $paymentNumber = $getPayment->code;
                    $description = $getPayment->description;
                  	
                  	$tax_category_id =  $getPayment->tax_category_id;
                } else if (isset($_GET['add']) || isset($_GET['ref'])) {
                    $paymentfilter = " ORDER BY id DESC limit 1 ";
                    $payments = Purpayment::GetPurpaymentList($paymentfilter);
                    if (!empty($payments[0]->code)) {
                        $paymentNumber = intval($payments[0]->code);
                        $paymentNumber = $paymentNumber + 1;
                    } else {
                        $paymentNumber = __PURPAYMENT__;
                    }
                }
              // >>> Prefill with the last transaction values <<<
    $last = Purpayment::GetPurpaymentList(" ORDER BY id DESC LIMIT 1 ");
    if ($last && isset($last[0])) {
        $lastRow = $last[0];

        // Payment Date
        $payment_date = !empty($lastRow->create_date)
            ? date('d-m-Y', strtotime($lastRow->create_date))
            : $current_date;

        // Cheque Date
        $cheque_date = !empty($lastRow->cheque_date)
            ? date('d-m-Y', strtotime($lastRow->cheque_date))
            : '';

        // Cheque No
        $cheque_no = !empty($lastRow->cheque_number) ? $lastRow->cheque_number : '';

        // Account No (readonly field in your form)
        $account_no = !empty($lastRow->bank_account_number) ? $lastRow->bank_account_number : '';

        // Bank (dropdown expects the Bank ID; if your column name is bank_id, change this line)
        $bank_name = !empty($lastRow->bank_name) ? $lastRow->bank_name : '';

        // (Optional) If you also want to show the last cheque bank name text field:
        $cheque_bank_name = !empty($lastRow->cheque_bank_name) ? $lastRow->cheque_bank_name : '';
    }
  }
      //  echo $getPayment->withholding_tax;
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                //print_r($_REQUEST);
                //exit;
                $purchasesCode = PurchaseSetup::GetPurchaseSetupById($purchase_reference_code);
                
                $data['supplier_id'] = $supplier_name;
                $data['code'] = $payment_number;
                $data['payment_type'] = $payment_type;
              	$data['purchase_reference_code'] = $purchasesCode->id;              
              	$data['advance_payment'] = $advance_payment;
              	$data['amount'] = $amount;
              	$data['withholding_tax'] = $withholding_tax;
          	    $data['withholding_tax_amount'] = $withholding_tax_amount;
                $data['amount_payable'] = $amount_payable;
                $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'] = date('Y-m-d', strtotime($cheque_date));
                $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()';
              	$data['tax_category_id'] = $tax_category_id;
              	$data['status'] = 'active';
              	$data['psid'] = '';
              	$data['cpr'] = '';
              	$data['supplier_payment_type'] = 'supplier';
              	$data['payment_status'] = 'pending';
              
              

                $errors = array();
                // Validate the input
                $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");
                    }
                }


                if ((strlen($supplier_name) == 0) || (strlen($supplier_name) > 255))
                    array_push($errors, "Please enter supplier name");
              // Validate purchase_reference_code based on advance_payment
              if ($advance_payment == 0 && strlen($purchase_reference_code) == 0) {
                array_push($errors, "Purchase reference code cannot be empty when payment is not advance.");
              }
                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_payable) == 0 || $amount_payable == 0))
                    array_push($errors, "Please enter payment amount");
                if ($payment_type == 'bank') {
                    if ((strlen($bank_name) == 0))
                        array_push($errors, "Please enter bank name");
                }

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

                    } else {
                        $q = Purpayment::UpdatePurpaymentSetup($id, $data);
                    }
                    if ($q) {
                            // If the payment query was successful
                            if ($advance_payment == '0' && !empty($purchase_reference_code)) {
                                // Prepare the data for updating the purchase table
                                $paymentMode = isset($_POST['paymentmode']) ? $_POST['paymentmode'] : '';
                                if (!empty($paymentMode)) {
                                    // Data to update in the purchase table
                                    $purchaseUpdateData = [
                                        'status' => $paymentMode, // Update status with the payment mode
                                    ];

                                    // Call the PurchaseSetup::UpdatePurchaseSetup method
                                    $updateResult = PurchaseSetup::UpdatePurchaseSetup($purchase_reference_code, $purchaseUpdateData);

                                    // Check if the update was successful
                                    if ($updateResult) {
                                        // Optionally, log success or display a success message
                                        echo "<div class='alert alert-success fade in'>
                                                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                                                <strong>Attention!</strong> Purchase status updated successfully. </div>";
                                    } else {
                                        // Optionally, display an error message
                                        echo "<div class='alert alert-warning fade in'>
                                                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                                                <strong>Attention!</strong> Failed to update purchase status. </div>";
                                    }
                                }
                            }

                            // Redirect or display a success message
                            echo "<script>window.location.href = 'purpayment.php?view&success'</script>";
                            echo "<div class='alert alert-success fade in'>
                                    <button type='button' class='close' data-dismiss='alert'>&times;</button>
                                    <strong>Attention!</strong> Payment submitted successfully! </div>";
                        } else {
                            echo "<div class='alert alert-error fade in'>
                                    <button type='button' class='close' data-dismiss='alert'>&times;</button>
                                    <strong>Attention!</strong> Some error occurred! </div>";
                        }

                }
            }
            ?>
            <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 m3 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 m3 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 class="col m3 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 class="col m3 s12">
                                <label class="control-label">Advance Payment*</label>
                              <select class="form-control" id="advance_payment" required name="advance_payment">
        <option value="" disabled <?= !isset($advance_payment) ? 'selected' : '' ?>>Select an option</option>
        <option value="0" <?= (isset($advance_payment) && $advance_payment == '0') ? 'selected' : '' ?>>No</option>
        <option value="1" <?= (isset($advance_payment) && $advance_payment == '1') || !isset($advance_payment) ? 'selected' : '' ?>>Yes</option>
    </select><br/>
                            </div>
                        </div>
                      
                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m4 s12">
                                <label class="control-label">Supplier *</label>
                                <?php
                                $suppliersfilter = " WHERE status = 'active'";
                                $suppliers = SupplierSetup::GetSupplierSetupList($suppliersfilter);
                                ?>
                                <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="row">
                            <div class="col m4 s12">
                              
                                    <div class="input-field col s12">
                                        <?php
                                        if (isset($_GET)) {
                                           $filterPurchases = " WHERE id = '$purchase_reference_code' AND status != 'paid'";
                                        }
                                        $purchases = PurchaseSetup::GetPurchaseSetupList($filterPurchases);
                                        ?>
                                        <select class="form-control" id="purchase_reference_code"
                                                name="purchase_reference_code">
                                           
                                            <?php
                                            //echo $invoice_reference_code;
                                            if ($purchases) {
                                                foreach ($purchases AS $purchasesRow) {
                                                    echo '<option ';
                                                    if ($purchasesRow->code == $purchase_reference_code) {
                                                        echo 'selected';
                                                    }
                                                     echo ' value="' . htmlspecialchars($purchasesRow->id) . '">' . htmlspecialchars($purchasesRow->purchase_invoice_no) . ' | ' . htmlspecialchars(date('d-m-Y', strtotime($purchasesRow->purchase_invoice_date))) . ' | ' .  htmlspecialchars($purchasesRow->total_amount) .'</option>'; // Use code as value
                                                }
                                            }
                                            ?>
                                        </select>
                                        <label for="invoice_reference_code" class="control-label">Purchase Ref.</label>
                                    </div>
                                 </div>
                             <div class="col m3 s12" hidden>
                                <label class="control-label">Tax Category *</label>
                                <input class="form-control" type="text" id="tax_category_id"
                                       name="tax_category_id" readonly
                                       value='<?php echo $getPayment->tax_category_id; ?>'/><br/>
                            </div>
                          
                            <div class="col m4 s12">
                                <label class="control-label">Payment Type *</label>
                                <select class="form-control" id="payment_type" required name="payment_type">
                                    <option value="">Select Payment Type</option>

                                    <!-- Bank option, selected by default if no payment type is chosen -->
                                    <option <?= empty($payment_type) || $payment_type == 'bank' ? 'selected' : '' ?> value="bank">Bank</option>

                                    <!-- Online option, selected if $payment_type is 'online' -->
                                    <option <?= $payment_type == 'online' ? 'selected' : '' ?> value="online">Online</option>
                                </select><br/>
                            </div>

                          </div>
                       
                        <div class="clearfix"></div>
                        <div class="row">
                            
                              <div class="col m3 s12">
                                  <label class="control-label">Invoice 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 class="col m3 s12">
                                  <label class="control-label">WHT%</label>
                                  <input class="form-control" type="number" id="withholding_tax"
                                         name="withholding_tax" value="<?= $withholding_tax ?>" readonly /><br/>
                              </div>
                          
                          <div class="col m3 s12">
                                  <label class="control-label">WHT Amount</label>
                                  <input class="form-control" type="number" id="withholding_tax_amount"
                                         name="withholding_tax_amount" value="<?= $withholding_tax_amount ?>"/><br/>
                             </div>
                            <div class="col m3 s12">
                                  <label class="control-label">Amount Payable</label>
                                  <input class="form-control" type="number" id="amount_payable"
                                         name="amount_payable" value="<?= $amount_payable ?>"/><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 m3 s12">
                                    <label class="control-label">Bank Name *</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/>
                                </div>
                                <div class="col m3 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>
                      
                        <?php if ($payment_type == 'cash' || $payment_type == 'online') {
                            $hide = 'style="display:none;"';
                        } ?>
                        
                            <div class="col m3 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 m3 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>
                          
                          
                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m6 s12">
                                <label class="control-label">Description</label>
                                <input class="form-control" type="text" id="description"
                                       name="description" value="<?= $description ?>"/><br/>
                            </div>
                          <div class="col m6 s12">
                              <label class="control-label">Payment Mode</label>
                              <select class="form-control" id="paymentmode" name="paymentmode">
                                  <option value="paid" <?= (isset($purchase_status) && $purchase_status === 'paid') ? 'selected' : '' ?>>Full Payment</option>
                                  <option value="partial paid" <?= (isset($purchase_status) && $purchase_status === 'partial paid') ? 'selected' : '' ?>>Partial Payment</option>
                              </select>

                              <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>
    
</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,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter party name</span>"
                }
            });

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

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

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

            $('#cheque_date').attr('required', false);
            $('#cheque_date').attr('disabled', true);
            $('#cheque_date').rules('add', {
                required: false,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter cheque date</span>"
                }
            });
        }
    });
    $('#bank_name').on('change', function () {
        //if ($(this).val() != 'bank') {
        $('body.container').block({message: 'Loading...'});
        $.get('transaction/getBankDetails.php?id=' + $(this).val(), function (data) {
            $("#account_no").val(data);
            $('body.container').unblock();
        });
        $('#cheque_bank_name').val($('#bank_name :selected').text());
        //console.log();
        //}
    });
   // initialize
    $('#purchase_reference_code').material_select();

    // setup listener for custom event to re-initialize on change
    $('#purchase_reference_code').on('contentChanged', function () {
        $(this).material_select();
    });

    $('#supplier_name').on('change', function () {
    var supplierId = $(this).val();
    var selectedId = $('#purchase_reference_code').val(); // Current selected value

    $('body.container').block({message: 'Loading...'});
    $.get('getFilterPurchases.php', { id: supplierId, selected_id: selectedId }, function (data) {
        $("#purchase_reference_code").empty();
        $("#purchase_reference_code").append(data);
        $('body.container').unblock();
        $('#purchase_reference_code').trigger('contentChanged');
    });
});

  $(document).ready(function() {
    // When a purchase reference is selected, trigger an AJAX request to get the total amount
    $('#purchase_reference_code').on('change', function() {
        var purchaseId = $(this).val(); // Get the selected purchase ID
        if (purchaseId) {
            // Send AJAX request to get the total amount for the selected purchase reference
            $.ajax({
                url: 'getPurchaseTotalAmount.php', // Create a PHP file to handle this
                type: 'GET',
                data: { id: purchaseId }, // Pass the purchase ID to the server
                success: function(response) {
                    // Parse the response (assuming it's in JSON format)
                    var data = JSON.parse(response);
                    // Set the amount field with the total amount
                    $('#amount').val(data.total_amount);
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching amount: ' + error);
                }
            });
        }
    });
});
  
$(document).ready(function () {
    // Cache the WHT value to avoid recalculating unnecessarily
    let cachedWHT = 0;

    // On supplier selection
   $('#supplier_name').on('change', function () {
    var supplierId = $(this).val(); // Get the selected supplier ID
    if (supplierId) {
        // Fetch WHT value for the selected supplier
        $.ajax({
            url: 'getSupplierWHT.php', // API endpoint to fetch WHT
            type: 'GET',
            data: { id: supplierId },
            success: function (response) {
                var data = JSON.parse(response);
                var exemptionDate = data.exemption_date ? new Date(data.exemption_date) : null;
                var currentDate = new Date(); // Get today's date
                cachedWHT = data.wht ? parseFloat(data.wht) : 0; // Default WHT to 0 if not set
                var taxCategoryId = data.category_id || ''; // Default category_id to empty if not set

                $('#withholding_tax').val(cachedWHT); // Update WHT field
                // Update tax_category_id field
                $('#tax_category_id').val(taxCategoryId);

                // Check if exemption date has expired and ensure it's not 01-01-1970
                if (exemptionDate && exemptionDate.getTime() !== 0 && exemptionDate < currentDate) {
                    alert("The exemption date has expired. Please update the WHT accordingly.");
                }

                // Fetch related purchases for the supplier
                $.get('getFilterPurchases.php?id=' + supplierId, function (data) {
                    $("#purchase_reference_code").empty();
                    $("#purchase_reference_code").append(data);
                    $("#purchase_reference_code").trigger('contentChanged');
                });
            },
            error: function (xhr, status, error) {
                console.log('Error fetching WHT: ' + error);
            }
        });
    } else {
        // Clear WHT, amount payable, WHT amount, and purchase reference if no supplier is selected
        cachedWHT = 0;
        $('#withholding_tax').val('');
        $('#amount_payable').val('');
        $('#withholding_tax_amount').val('');
        $('#tax_category_id').val('');
        $("#purchase_reference_code").empty();
    }
});


    // On purchase reference selection
    $('#purchase_reference_code').on('change', function () {
        var purchaseId = $(this).val(); // Get the selected purchase ID
        if (purchaseId) {
            // Fetch invoice amount for the selected purchase reference
            $.ajax({
                url: 'getPurchaseTotalAmount.php', // API endpoint to fetch invoice amount
                type: 'GET',
                data: { id: purchaseId },
                success: function (response) {
                    var data = JSON.parse(response);
                    var invoiceAmount = parseFloat(data.remaining_amount) || 0;

                    $('#amount').val(invoiceAmount); // Set invoice amount field

                    // Calculate WHT amount and amount payable
                    if (cachedWHT > 0) {
                        var whtAmount = (cachedWHT / 100) * invoiceAmount;
                        var amountPayable = invoiceAmount - whtAmount;

                        // Update calculated fields
                        $('#withholding_tax_amount').val(whtAmount.toFixed(2));
                        $('#amount_payable').val(amountPayable.toFixed(2));
                    } else {
                        // If no WHT, set amount payable to invoice amount
                        $('#withholding_tax_amount').val('0.00');
                        $('#amount_payable').val(invoiceAmount.toFixed(2));
                    }
                },
                error: function (xhr, status, error) {
                    console.log('Error fetching invoice amount: ' + error);
                }
            });
        } else {
            // Clear invoice amount and related fields if no purchase reference is selected
            $('#amount').val('');
            $('#withholding_tax_amount').val('');
            $('#amount_payable').val('');
        }
    });

    // Recalculate when invoice amount changes manually
    $('#amount').on('input', function () {
        var invoiceAmount = parseFloat($(this).val()) || 0;
        if (cachedWHT > 0 && invoiceAmount > 0) {
            var whtAmount = (cachedWHT / 100) * invoiceAmount;
            var amountPayable = invoiceAmount - whtAmount;

            $('#withholding_tax_amount').val(whtAmount.toFixed(2));
            $('#amount_payable').val(amountPayable.toFixed(2));
        } else {
            $('#withholding_tax_amount').val('0.00');
            $('#amount_payable').val(invoiceAmount.toFixed(2));
        }
    });
});
   // Recalculate when withholding tax value changes manually
    $('#withholding_tax').on('input', function () {
        var manualWHT = parseFloat($(this).val()) || 0; // Get manually entered WHT value
        var invoiceAmount = parseFloat($('#amount').val()) || 0; // Get the invoice amount

        if (invoiceAmount > 0) {
            var whtAmount = (manualWHT / 100) * invoiceAmount; // Calculate WHT amount
            var amountPayable = invoiceAmount - whtAmount; // Calculate payable amount

            $('#withholding_tax_amount').val(whtAmount.toFixed(2)); // Update WHT amount field
            $('#amount_payable').val(amountPayable.toFixed(2)); // Update payable amount field
        } else {
            // Clear related fields if invoice amount is not valid
            $('#withholding_tax_amount').val('');
            $('#amount_payable').val('');
        }
    });

  $(document).ready(function () {
    // Function to handle enabling/disabling of purchase reference field
    function togglePurchaseReference() {
        var advancePayment = $('#advance_payment').val(); // Get selected advance payment value
        if (advancePayment == '1') { // If "YES" is selected (value is 1)
            $('#purchase_reference_code').prop('disabled', true).val(''); // Disable and clear the field
        } else {
            $('#purchase_reference_code').prop('disabled', false); // Enable the field
        }
    }

    // Trigger toggle on advance payment selection change
    $('#advance_payment').on('change', function () {
        togglePurchaseReference();
    });

    // Trigger toggle on page load to ensure correct initial state
    togglePurchaseReference();
});
  
 $(document).ready(function () {
    // Function to toggle visibility of Payment Mode field
    function togglePaymentMode() {
        var advancePayment = $('#advance_payment').val(); // Get selected advance payment value
        if (advancePayment == '1') { // If "YES" is selected (value is 1)
            $('#paymentmode').closest('.col.m6.s12').hide(); // Hide the Payment Mode container
        } else {
            $('#paymentmode').closest('.col.m6.s12').show(); // Show the Payment Mode container
        }
    }

    // Trigger toggle on Advance Payment selection change
    $('#advance_payment').on('change', function () {
        togglePaymentMode();
    });

    // Trigger toggle on page load to ensure correct initial state
    togglePaymentMode();
});



  
  



  
    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 () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });
 
</script>
</body>
</html>