<?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_status = 'paid';

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 Tax 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;
                  	$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;
                   	$psid = $getPayment->psid;
                   	$cpr = $getPayment->cpr;
                  	
                  	$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__;
                    }
                   // Set last PSID and CPR from the latest entry
    $psid = isset($payments[0]->psid) ? $payments[0]->psid : '';
    $cpr  = isset($payments[0]->cpr)  ? $payments[0]->cpr : '';
    $cheque_no   = isset($payments[0]->cheque_number) ? $payments[0]->cheque_number : '';
    $cheque_date = (!empty($payments[0]->cheque_date) && $payments[0]->cheque_date != '0000-00-00')
        ? date('d-m-Y', strtotime($payments[0]->cheque_date))
        : '';

                }
            }
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
           //    error_log("Submitted Data: " . json_encode($_POST));
                //print_r($_REQUEST);
                //exit;
                $isAddMode = isset($_GET['add']) || isset($_GET['ref']);
    $isEditMode = isset($_GET['edit']);

    // Handle purchase_reference_code differently for add and edit modes
    if ($isAddMode) {
        // Fetch the purchase reference code for "add" mode
        $purchasesCode = Purpayment::GetPurpaymentSetupById($purchase_reference_code);
        $data['purchase_reference_code'] = $purchasesCode->purchase_reference_code;
    } elseif ($isEditMode) {
        // Use the submitted value directly for "edit" mode
        $data['purchase_reference_code'] = $purchase_reference_code;
    }

                
                $data['supplier_id'] = $supplier_name;
                $data['code'] = $payment_number;
                $data['payment_type'] = $payment_type;
             // 	$data['purchase_reference_code'] = $purchasesCode->purchase_reference_code;              
              	$data['advance_payment'] = '0';
              	$data['amount'] = $amount;
              	$data['withholding_tax'] = $withholding_tax;
          	    $data['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'] = $psid;
              	$data['cpr'] = $cpr;
              	$data['supplier_payment_type'] = 'tax';
              	$data['payment_status'] = 'paid';
              
           



                $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) {
                                // Update the payment_status of the selected payment reference to 'paid'
                                $updateData = ['payment_status' => 'paid'];
                                Purpayment::UpdatePurpaymentSetup($purchase_reference_code, $updateData);

                                $output = '';
                                echo "<script>window.location.href = 'purpayment.php?view&success'</script>";
                            } 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 occurred! </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>";
                    }
                }
            }
            ?>
            <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 m4 s12" hidden>
                                <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">PSID</label>
                                <input class="form-control" type="text" id="psid"
                                       name="psid" value="<?= $psid ?>"/><br/>
                            </div>
                          
                           <div class="col m3 s12">
                                <label class="control-label">CPR</label>
                                <input class="form-control" type="text" id="cpr"
                                       name="cpr" value="<?= $cpr ?>"/><br/>
                            </div>
                          
                          
                          <div class="col m3 s12" hidden>
                                <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
    // Fetch payments for the supplier
    if (isset($_GET['edit'])) {
        $filterPayments = " WHERE supplier_id = '$supplier_id' AND supplier_payment_type = 'supplier'";
        $payments = Purpayment::GetPurpaymentList($filterPayments);
    }
    ?>
    <select class="form-control" id="purchase_reference_code" name="purchase_reference_code">
        <option value="">Select Payment Reference</option>
        <?php
        if ($payments) {
            foreach ($payments as $paymentsRow) {
                // Fetch purchase reference details
                $purchaseFilter = " WHERE id = '{$paymentsRow->purchase_reference_code}'";
                $purchaseReferenceList = PurchaseSetup::GetPurchaseSetupList($purchaseFilter);
                $purchaseReference = is_array($purchaseReferenceList) && count($purchaseReferenceList) > 0
                    ? $purchaseReferenceList[0]
                    : null;

                // Build the option
                echo '<option value="' . htmlspecialchars($paymentsRow->purchase_reference_code) . '"';
                if ($paymentsRow->purchase_reference_code == $purchase_reference_code) {
                    echo ' selected'; // Mark as selected if it matches the database value
                }
                echo '>';
                echo htmlspecialchars($purchaseReference ? $purchaseReference->purchase_invoice_no : 'N/A') . ' | ';
                echo htmlspecialchars($paymentsRow->amount) . ' | ';
                echo htmlspecialchars($paymentsRow->withholding_tax_amount);
                echo '</option>';
            }
        }
        ?>
    </select>
    <label for="purchase_reference_code" class="control-label">Payment 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 m4 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 m4 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" hidden>
                                  <label class="control-label">Amount Payable</label>
                                  <input class="form-control" type="number" id="amount_payable"
                                         name="withholding_tax_amount" value="<?= $withholding_tax_amount ?>"/><br/>
                             </div>
                            <div class="col m4 s12">
                                  <label class="control-label">WHT Amount</label>
                                  <input class="form-control" type="number" id="withholding_tax_amount"
                                         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 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>
    
</footer>
</div>
</section>

<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
  
  $(document).ready(function () {
    // Event listener for the supplier dropdown
    $('#supplier_name').on('change', function () {
        var supplierId = $(this).val(); // Get the selected supplier ID

        if (supplierId) {
            // Show a loading message or spinner if required
            $('body.container').block({ message: 'Loading...' });

            // AJAX request to fetch payment data for the selected supplier
            $.ajax({
                url: 'getFilterPurPayments.php', // Helper file to fetch payment data
                type: 'GET',
                data: { id: supplierId }, // Pass the selected supplier ID
                success: function (response) {
                    // Clear the Payment Ref dropdown
                    $('#purchase_reference_code').empty();

                    // Append the returned options to the dropdown
                    $('#purchase_reference_code').append(response);

                    // Trigger any necessary events for re-initializing the dropdown UI
                    $('#purchase_reference_code').trigger('contentChanged');

                    // Unblock the UI after data is loaded
                    $('body.container').unblock();
                },
                error: function (xhr, status, error) {
                    console.error('Error fetching payment data:', error);

                    // Unblock the UI even in case of an error
                    $('body.container').unblock();
                }
            });
        } else {
            // Clear the Payment Ref dropdown if no supplier is selected
            $('#purchase_reference_code').empty();
        }
    });

    // Reinitialize the dropdown if using a UI library like Materialize
    $('#purchase_reference_code').on('contentChanged', function () {
        $(this).material_select(); // Replace this with your dropdown reinitialization logic
    });

   // Event listener for the Payment Ref dropdown
    $('#purchase_reference_code').on('change', function () {
        var paymentRefId = $(this).val(); // Get the selected payment reference ID

        if (paymentRefId) {
            $('body.container').block({ message: 'Loading...' });

            // Fetch payment details for the selected reference
            $.ajax({
                url: 'getPurchaseTotalAmountTax.php',
                type: 'GET',
                data: { id: paymentRefId },
                success: function (response) {
                    var data = JSON.parse(response);

                    // Populate the fields with fetched data
                    $('#amount').val(data.amount || '');
                    $('#withholding_tax').val(data.withholding_tax || '');
                    $('#withholding_tax_amount').val(data.withholding_tax_amount || '');

                    $('body.container').unblock();
                },
                error: function (xhr, status, error) {
                    console.error('Error fetching payment details:', error);
                    $('body.container').unblock();
                }
            });
        } else {
            $('#amount').val('');
            $('#withholding_tax').val('');
            $('#withholding_tax_amount').val('');
        }
    });
});
  
  
   $('#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();
        //}
    });

  
    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>