<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$supplier_id = '';
$purchase_reference_code = '';
$account_no = '';
$hide = '';
$bank_name = '';
$bank_id = '';
$description = '';
$deposit_amount = '';
$deposit_bank = '';
$current_date = date('d-m-Y');

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker, #cheque_date, #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">
            <h3>Supplier Payment</h3>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC' && 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 = SupplierPayment::GetSupplierPaymentSetupById($id);
                    $purchase_payment_id = $getPayment->purchase_payment_id;
                    $desposit_date = date('d-m-Y', strtotime($getPayment->desposit_date));
                    $deposit_slip_no = $getPayment->deposit_slip_no;
                    $deposit_amount = $getPayment->deposit_amount;
                    $bank_id = $getPayment->bank_id;
                }
            }
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $purchasesCode = PurchaseSetup::GetPurchaseSetupById($purchase_reference_code);

                $data = [
                    'purchase_payment_id' => $purchase_supplier_name,
                    'desposit_date' => date('Y-m-d', strtotime($desposit_date)),
                    'deposit_slip_no' => $deposit_slip_no,
                    'deposit_amount' => $deposit_amount,
                    'bank_id' => $bank_id,
                    'description' => $description,
                    'create_date' => 'NOW()',
                    'status' => 'active',
                ];

                $errors = [];

                if ((strlen($deposit_slip_no) == 0) || (strlen($deposit_slip_no) > 255))
                    array_push($errors, "Please enter Deposit Slip Number");

                if ((strlen($desposit_date) == 0))
                    array_push($errors, "Please enter deposit date");

                if ((strlen($bank_account_number) == 0 || $bank_account_number == 0))
                    array_push($errors, "Please enter bank account number");

                if (count($errors) == 0) {
                    if (isset($_GET['add']) || isset($_GET['ref'])) {
                        $q = SupplierPayment::AddSupplierPaymentSetup($data);
                    } else {
                        $q = SupplierPayment::UpdateSupplierPaymentSetup($id, $data);
                    }
                    if ($q) {
                        echo "<script>window.location.href = 'supplier_payment.php?view&success'</script>";
                    } 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>";
                    }
                } else {
                    foreach ($errors as $val) {
                        echo "<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']; ?>'/>
                            </div>
                            <div class="col m3 s12">
                                <label class="control-label">Select Supplier *</label>
                                <?php
                                $suppliers = SupplierSetup::GetSupplierSetupList();
                                ?>
                                <select class="form-control" required id="supplier_id" name="supplier_id">
                                    <option>Select Supplier</option>
                                    <?php
                                    if ($suppliers) {
                                        foreach ($suppliers as $supplier) {
                                            echo '<option ';
                                            if ($supplier->id == $supplier_id) {
                                                echo 'selected';
                                            }
                                            echo ' value="' . $supplier->id . '" >' . $supplier->name . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </div>

                            <div class="col m3 s12">
                                <label class="control-label">Deposit Date *</label>
                                <input class="form-control" required type="text" id="datepicker"
                                       name="desposit_date" placeholder="<?= date('01-01-Y') ?>"
                                       value='<?= !empty($desposit_date) ? $payment_date : $current_date; ?>'/>
                            </div>
                            <div class="col m3 s12">
                                <label class="control-label">Deposit Slip No.</label>
                                <input class="form-control" type="text" id="deposit_slip_no" name="deposit_slip_no" value="<?= $deposit_slip_no ?>"/>
                            </div>
                            <div class="col m3 s12">
                                <label class="control-label">Deposit Amount</label>
                                <input class="form-control" type="number" id="deposit_amount" name="deposit_amount" value="<?= $deposit_amount ?>"/>
                            </div>
                        </div>

                        <div class="clearfix"></div>
                        <div class="row">
                            <div class="col m3 s12">
                                <label for="cheque_bank" class="control-label">Select Cheque Bank *</label>
                                <?php
                                $bankfilter = " WHERE status = 'active' ORDER BY bank_name";
                                $banks = BankSetup::GetBankSetupList($bankfilter);
                                ?>
                                <select class="form-control" required id="cheque_bank" name="cheque_bank">
                                    <?php
                                    if ($banks) {
                                        foreach ($banks as $bank) {
                                            echo '<option ';
                                            if (isset($bank_id) && $bank->id == $bank_id) {
                                                echo 'selected';
                                            }
                                            echo ' value="' . htmlspecialchars($bank->id) . '">' . htmlspecialchars($bank->bank_name) . ' | ' . htmlspecialchars($bank->bank_account_number) . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </div>

                            <div class="col m3 s12">
                                <label class="">Deposit Bank *</label>
                                <select class="form-control" id="deposit_bank" name="deposit_bank" required>
                                    <option value="">Select Deposit Bank</option>
                                </select>
                            </div>

                            <div class="col m3 s12">
                                <label class="control-label">Account Number</label>
                                <input class="form-control" type="text" id="bank_account_number" name="bank_account_number" readonly/>
                            </div>

                            <div class="col m3 s12">
                                <label class="control-label">Description</label>
                                <input class="form-control" type="text" id="description" name="description" value="<?= $description ?>"/>
                            </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='supplier_payment.php?view'">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<footer></footer>
</div>

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

<script type="application/javascript">
$(document).ready(function () {
    // Function to fetch banks based on selected supplier
function fetchDepositBanks(supplierId) {
    $.ajax({
        url: "getSupplierBanks_new.php",
        type: "GET",
        data: { supplier_id: supplierId },
        success: function(response) {
            console.log(response);  // Log the response to the console
            const banks = JSON.parse(response);
            const depositBankDropdown = $('#deposit_bank');
            const accountNumberInput = $('#bank_account_number');
            
            // Handle empty or error responses
            if (banks.error) {
                alert(banks.error);
                return;
            }

            depositBankDropdown.empty();
            depositBankDropdown.append('<option value="">Select Deposit Bank</option>');
            accountNumberInput.val(''); // Clear the account number field

            // Populate the dropdown with available bank options
            if (banks.length > 0) {
                banks.forEach(bank => {
                    depositBankDropdown.append(
                        `<option value="${bank.id}" data-account-number="${bank.bank_account_number}">${bank.bank_name}</option>`
                    );
                });
            } else {
                alert('No deposit banks found for this supplier.');
            }
        },
        error: function() {
            alert('Failed to fetch deposit banks.');
        }
    });
}

// Event listener for supplier dropdown change
$('#supplier_id').on('change', function() {
    const supplierId = $(this).val();
    if (supplierId) {
        fetchDepositBanks(supplierId); // Fetch banks for the selected supplier
    } else {
        // Clear the dropdown and account number field if no supplier is selected
        $('#deposit_bank').empty();
        $('#deposit_bank').append('<option value="">Select Deposit Bank</option>');
        $('#bank_account_number').val('');
    }
});

// Event listener for deposit bank change
$('#deposit_bank').on('change', function() {
    const selectedBank = $(this).find('option:selected');
    const accountNumber = selectedBank.data('account-number');
    $('#bank_account_number').val(accountNumber); // Auto-fill the account number field
});

</script>
</body>
</html>


