<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}

$searchTerm = isset($_POST['search']) ? $_POST['search'] : '';

$sql_purchase_lines = "
    SELECT pl.supplier_id, pl.quantity, pl.purchase_price, pl.ref_no, pl.shipping_charges
    FROM purchase_lines pl
    WHERE pl.ref_no IS NOT NULL 
      AND pl.ref_no != '' 
      AND pl.ref_no != '0'
";
$stmt_purchase_lines = $conn->query($sql_purchase_lines);
$purchase_lines = $stmt_purchase_lines->fetchAll(PDO::FETCH_ASSOC);

$sql_bank_debit_amount = "
    SELECT bd.supplier_id, SUM(bd.amount) AS total_amount
    FROM bank_debit_amount bd
    GROUP BY bd.supplier_id
";
$stmt_bank_debit_amount = $conn->query($sql_bank_debit_amount);
$bank_debit_amounts = $stmt_bank_debit_amount->fetchAll(PDO::FETCH_ASSOC);

$sql_supplier_purchase_manual = "
    SELECT spm.supplier_id, SUM(spm.amount) AS total_amount
    FROM supplier_purchase_manual spm
    GROUP BY spm.supplier_id
";
$stmt_supplier_purchase_manual = $conn->query($sql_supplier_purchase_manual);
$supplier_purchase_manuals = $stmt_supplier_purchase_manual->fetchAll(PDO::FETCH_ASSOC);

$sql_contacts = "
    SELECT c.id, c.type, c.name, c.opening_balance
    FROM contacts c
    WHERE c.type = 'supplier'
";
$stmt_contacts = $conn->query($sql_contacts);
$contacts = $stmt_contacts->fetchAll(PDO::FETCH_ASSOC);

$purchase_totals = [];
$debit_totals = [];
$supplier_purchase_totals = [];

$seen_refs = []; 
foreach ($purchase_lines as $purchase) {
    $supplier_id = $purchase['supplier_id'];
    $quantity = $purchase['quantity'];
    $purchase_price = $purchase['purchase_price'];
    $ref_no = $purchase['ref_no'];
    $shipping_charges = $purchase['shipping_charges'];

    $line_total = $quantity * $purchase_price;

    if (!isset($purchase_totals[$supplier_id])) {
        $purchase_totals[$supplier_id] = 0;
    }

    $purchase_totals[$supplier_id] += $line_total;

    if (!isset($seen_refs[$supplier_id][$ref_no])) {
        $purchase_totals[$supplier_id] += $shipping_charges;
        $seen_refs[$supplier_id][$ref_no] = true;
    }
}

foreach ($bank_debit_amounts as $bank_debit) {
    $supplier_id = $bank_debit['supplier_id'];
    $total_debit = $bank_debit['total_amount'];

    if (!isset($debit_totals[$supplier_id])) {
        $debit_totals[$supplier_id] = 0;
    }

    $debit_totals[$supplier_id] += $total_debit;
}

foreach ($supplier_purchase_manuals as $manual_purchase) {
    $supplier_id = $manual_purchase['supplier_id'];
    $total_manual_purchase = $manual_purchase['total_amount'];

    if (!isset($supplier_purchase_totals[$supplier_id])) {
        $supplier_purchase_totals[$supplier_id] = 0;
    }

    $supplier_purchase_totals[$supplier_id] += $total_manual_purchase;
}

$final_results = [];

foreach ($contacts as $contact) {
    $supplier_id = $contact['id'];
    $supplier_name = $contact['name'];
    $supplier_type = $contact['type'];
    $opening_balance = $contact['opening_balance'];

    $total_purchase = isset($purchase_totals[$supplier_id]) ? $purchase_totals[$supplier_id] : 0;
    $total_debit_amount = isset($debit_totals[$supplier_id]) ? $debit_totals[$supplier_id] : 0;
    $manual_purchase_total = isset($supplier_purchase_totals[$supplier_id]) ? $supplier_purchase_totals[$supplier_id] : 0;

    $adjusted_total_purchase = $total_purchase + $opening_balance + $manual_purchase_total;

    $remaining_amount = $adjusted_total_purchase - $total_debit_amount;

    $status = ($remaining_amount > 0) ? 'Pending' : 'Paid';

    $final_results[] = [
        'supplier_name' => $supplier_name,
        'supplier_type' => $supplier_type,
        'total_purchase' => $total_purchase,
        'opening_balance' => $opening_balance,
        'manual_purchase_total' => $manual_purchase_total,
        'adjusted_total_purchase' => $adjusted_total_purchase,
        'total_debit_amount' => $total_debit_amount,
        'remaining_amount' => $remaining_amount,
        'status' => $status,
        'supplier_id' => $supplier_id
    ];
}

if ($searchTerm) {
    $filtered_results = [];
    foreach ($final_results as $result) {
        if (
            stripos($result['supplier_name'], $searchTerm) !== false ||
            stripos((string)$result['remaining_amount'], $searchTerm) !== false ||
            stripos($result['status'], $searchTerm) !== false
        ) {
            $filtered_results[] = $result;
        }
    }
    $final_results = $filtered_results;
}
?>



<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>List Banks</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.29/jspdf.plugin.autotable.min.js"></script>
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .search-container {
            margin-bottom: 20px;
            text-align: center;
        }

        .search-input {
            width: 50%;
            padding: 10px;
            font-size: 16px;
            border: 2px solid #ddd;
            border-radius: 4px;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            border-color: #007bff;
        }

        .amount-in {
            color: green;
        }

        .amount-out {
            color: red;
        }

        table {
            margin-top: 20px;
        }

        .custom-select-supplier-container {
            position: relative;
            width: 100%;
        }

        .custom-select-supplier-container input {
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
            text-align: center;
            /* Center the text */
        }

        .custom-select-supplier-container .dropdown {
            position: absolute;
            width: 100%;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: #fff;
            z-index: 1000;
            display: none;
        }

        .custom-select-supplier-container .dropdown div {
            padding: 10px;
            cursor: pointer;
        }

        .custom-select-supplier-container .dropdown div:hover {
            background-color: #f1f1f1;
        }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_expense_category.php">Bank & Cash Accounts</a> > Supplier Ledger
                                    </h4>
                                </div>
                                <!-- <div class="col-lg-6">
                                    <button type="button" class="btn btn-primary" data-toggle="modal"
                                        data-target="#exampleModalCenter" style="float:inline-end;">
                                        <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px;color:white">
                                        </ion-icon>New Income Add
                                    </button>
                                </div> -->
                                <!-- add variation -->
                                <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
                                    aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="exampleModalCenterTitle">Add New Account</h5>
                                                <button type="button" class="close" data-dismiss="modal"
                                                    aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                </button>
                                            </div>
                                            <form method="POST" action="">

                                                <div class="modal-body">
                                                    <div class="form-group">
                                                        <label for="" class="control-label">Date *</label>
                                                        <input type="date" name="date_deposit" class="form-control" placeholder="Bank Name" required>
                                                    </div>
                                                    <div class="form-group">
                                                        <label for="" class="control-label">Account *</label>
                                                        <?php

                                                        $query = "SELECT `id`, `bank_name` FROM `banks`";
                                                        $stmt = $conn->prepare($query);
                                                        $stmt->execute();

                                                        // Fetch all the results
                                                        $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                                        ?>
                                                        <select class="form-control" name="bank_id" id="bank_id">
                                                            <option selected disabled>Select an account</option>

                                                            <?php foreach ($banks as $bank): ?>
                                                                <option value="<?php echo $bank['id']; ?>"><?php echo $bank['bank_name']; ?></option>
                                                            <?php endforeach; ?>

                                                        </select>
                                                    </div>
                                                    <div class="form-group">
                                                        <label for="" class="control-label">Amount *</label>
                                                        <input type="number" name="amount" class="form-control" placeholder="Enter Amount" id="">
                                                    </div>
                                                    <div class="form-group">
                                                        <label for="" class="control-label">Note *</label>
                                                        <input type="text" name="payment_status" class="form-control" placeholder="Enter Note" required>
                                                    </div>

                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary"
                                                        data-dismiss="modal">Close</button>
                                                    <button type="submit" class="btn btn-primary">Save</button>
                                                </div>
                                        </div>
                                        </form>
                                    </div>
                                </div>
                                <!-- add variation end -->
                            </div>

                            <!----------Updated model---------->
                            <!-- Modal for Editing Bank Details -->
                            <div class="modal" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
                                <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="editModalLabel">Edit Bank Details</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="closeEditModal()">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body">
                                            <!-- Edit Form -->
                                            <form action="update_bank.php" method="POST">
                                                <input type="hidden" id="edit-bank_id" name="id">
                                                <div class="form-group">
                                                    <label for="edit-bank_name">Bank Name</label>
                                                    <input type="text" class="form-control" id="edit-bank_name" name="bank_name" required>
                                                </div>
                                                <div class="form-group">
                                                    <label for="edit-opening_date">Opening Date</label>
                                                    <input type="date" class="form-control" id="edit-opening_date" name="opening_date" required>
                                                </div>
                                                <div class="form-group">
                                                    <label for="edit-account_number">Account Number</label>
                                                    <input type="text" class="form-control" id="edit-account_number" name="account_number" required>
                                                </div>
                                                <div class="form-group">
                                                    <label for="edit-opening_balance">Opening Balance</label>
                                                    <input type="text" class="form-control" id="edit-opening_balance" name="opening_balance">
                                                </div>
                                                <div class="form-group">
                                                    <label for="edit-description">Description</label>
                                                    <textarea class="form-control" id="edit-description" name="description"></textarea>
                                                </div>
                                                <button type="submit" class="btn btn-primary">Update</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <script>
                                function openEditModal(id, bankName, openingDate, accountNumber, openingBalance, description) {
                                    document.getElementById('edit-bank_id').value = id;
                                    document.getElementById('edit-bank_name').value = bankName;
                                    document.getElementById('edit-opening_date').value = openingDate;
                                    document.getElementById('edit-account_number').value = accountNumber;
                                    document.getElementById('edit-opening_balance').value = openingBalance;
                                    document.getElementById('edit-description').value = description;

                                    $('#editModal').modal('show');
                                }

                                function closeEditModal() {
                                    $('#editModal').modal('hide');
                                }
                            </script>

                            <!-----End Update model---------->
                            <!-- search bar -->
                            <!-- <form action="">
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-5">
                                        <input type="search" name="" placeholder="Search" class="form-control" id="">
                                    </div>
                          
                                    <div class="col-lg-2">
                                        <button style="width:100%;" class="btn btn-primary p-2">Search</button>
                                    </div>
                                </div>
                            </form> -->
                            <!-- searchbar end -->
                            <!-- buttons for export -->
                            <div class="row mt-5">
                                <div class="col-lg-2"></div>
                                <!-- <div class="col-lg-8">
                                    <button class="btn btn-primary">
                                        <ion-icon name="document-outline"></ion-icon>Export to CSV
                                    </button>
                                    <button class="btn btn-info">
                                        <ion-icon name="document-outline"></ion-icon>Export to Excel
                                    </button>
                                    <button class="btn btn-warning">
                                        <ion-icon name="print-outline"></ion-icon>Print
                                    </button>
                                    <button class="btn btn-danger">
                                        <ion-icon name="stop-outline"></ion-icon>Column Visibility
                                    </button>
                                    <button class="btn btn-dark">
                                        <ion-icon name="document-outline"></ion-icon>Export to PDF
                                    </button>
                                </div> -->
                            </div>
                            <!-- buttons for export end -->
                            <div class="iq-card-body" style="overflow:auto;">
                                <!-- Search Form -->
                                <form method="POST" action="">
                                    <div class="input-group mb-3">
                                        <input type="text" name="search" class="form-control" placeholder="Search by supplier name, or status" value="<?php echo htmlspecialchars($searchTerm); ?>">
                                        <button class="btn btn-primary" type="submit">Search</button>
                                        <a href="list_supplier_ledger.php" class="btn btn-secondary">Clear Filter</a> <!-- Clear Filter Button -->
                                    </div>
                                </form><!-- Bootstrap CSS (CDN) -->
                                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">

                                <!-- Bootstrap JS and Popper.js (CDN) -->
                                <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
                                <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>

<?php

$sql_suppliers = "SELECT id, name, opening_balance FROM contacts WHERE type = 'supplier'";
$stmt_suppliers = $conn->query($sql_suppliers);
$suppliers = $stmt_suppliers->fetchAll(PDO::FETCH_ASSOC);

$sql_banks = "SELECT id, bank_name FROM banks";
$stmt_banks = $conn->query($sql_banks);
$banks = $stmt_banks->fetchAll(PDO::FETCH_ASSOC);

if (isset($_POST['submit_pay'])) {
    $supplier_id = $_POST['supplier_id'];
    $bank_id = $_POST['bank_id'];
    $amount = $_POST['amount'];
    $note = $_POST['note'];
    $purchase_date = $_POST['purchase_date'] . ' ' . date('H:i:s');

    $sql_insert_payment = "INSERT INTO bank_debit_amount (bank_id, supplier_id, amount, note, date)
    VALUES (:bank_id, :supplier_id, :amount, :note, :purchase_date)
    ";

    $stmt = $conn->prepare($sql_insert_payment);
    $stmt->bindParam(':bank_id', $bank_id);
    $stmt->bindParam(':supplier_id', $supplier_id);
    $stmt->bindParam(':amount', $amount);
    $stmt->bindParam(':note', $note);
    $stmt->bindParam(':purchase_date', $purchase_date);
    $stmt->execute();

    $last_inserted_id = $conn->lastInsertId();

    $sql_supplier_name = "SELECT name FROM contacts WHERE id = :supplier_id";
    $stmt_supplier_name = $conn->prepare($sql_supplier_name);
    $stmt_supplier_name->bindParam(':supplier_id', $supplier_id);
    $stmt_supplier_name->execute();
    $supplier_data = $stmt_supplier_name->fetch(PDO::FETCH_ASSOC);
    $supplier_name = $supplier_data['name'];

    echo "<script>
        alert('Payment recorded successfully! Supplier: " . $supplier_name . "');
        window.location.href = 'supplier_print_pay_amount.php?bill_id=" . $last_inserted_id . "';  
    </script>";
    exit; 
}

?>

                               
                                <!-- Button to trigger popup -->
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#paymentModal">Pay Amount</button>
                                
                                <!-- <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBillModal">Add Bill</button> -->
                                <!-- Modal for adding bill -->
                                <!-- Modal for adding bill -->
                                <div class="modal fade" id="addBillModal" tabindex="-1" aria-labelledby="addBillModalLabel" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="addBillModalLabel">Add Bill</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <!-- Form for adding a bill -->
                                                <form method="POST" action="submit_purchase_data.php" id="purchase_form">
                                                    <!-- Supplier Select Box -->
                                                    <div class="mb-3">
                                                        <label for="supplier_id" class="form-label">Select Supplier</label>
                                                        <!-- Custom CSS for styling the dropdown -->

                                                        <!-- HTML Form with the Custom Select Dropdown for Suppliers -->
                                                        <div class="custom-select-supplier-container">
                                                            <input type="text" id="searchSupplierInput" placeholder="Search Supplier" autocomplete="off" class="form-control" onkeyup="filterSuppliers()">
                                                            <select id="supplier_id_data" name="supplier_id" class="form-select" required style="display:none;">
                                                                <option value="">Select Supplier</option>
                                                                <?php foreach ($purchse_suppliers as $purchse_supplier): ?>
                                                                    <option value="<?= $purchse_supplier['id'] ?>"><?= htmlspecialchars($purchse_supplier['name']) ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <div class="dropdown" id="supplierDropdown"></div>
                                                        </div>

                                                        <!-- JavaScript to filter the dropdown options for Suppliers -->
                                                        <script>
                                                            function filterSuppliers() {
                                                                var input, filter, select, options, dropdown, i;
                                                                input = document.getElementById("searchSupplierInput");
                                                                filter = input.value.toLowerCase();
                                                                select = document.getElementById("supplier_id_data");
                                                                options = select.getElementsByTagName("option");
                                                                dropdown = document.getElementById("supplierDropdown");
                                                                dropdown.innerHTML = "";

                                                                for (i = 1; i < options.length; i++) {
                                                                    txtValue = options[i].textContent || options[i].innerText;
                                                                    if (txtValue.toLowerCase().indexOf(filter) > -1) {
                                                                        var div = document.createElement("div");
                                                                        div.textContent = txtValue;
                                                                        div.setAttribute("data-value", options[i].value);
                                                                        div.onclick = function() {
                                                                            select.value = this.getAttribute("data-value");
                                                                            input.value = this.textContent;
                                                                            dropdown.style.display = "none";
                                                                            select.dispatchEvent(new Event('change'));
                                                                        };
                                                                        dropdown.appendChild(div);
                                                                    }
                                                                }

                                                                dropdown.style.display = dropdown.childElementCount > 0 ? "block" : "none";
                                                            }

                                                            document.getElementById("searchSupplierInput").addEventListener("focus", function() {
                                                                document.getElementById("supplierDropdown").style.display = "block";
                                                            });

                                                            document.addEventListener("click", function(event) {
                                                                if (!event.target.closest(".custom-select-supplier-container")) {
                                                                    document.getElementById("supplierDropdown").style.display = "none";
                                                                }
                                                            });

                                                            document.getElementById("searchSupplierInput").addEventListener("input", function() {
                                                                if (this.value === "") {
                                                                    document.getElementById("supplier_id_data").value = "";
                                                                    filterSuppliers();
                                                                }
                                                            });
                                                        </script>
                                                    </div>

                                                    <!-- Date Field -->
                                                    <div class="mb-3">
                                                        <label for="purchase_date" class="form-label">Purchase Date</label>
                                                        <input type="date" id="purchase_date" name="purchase_date" class="form-control" required />
                                                    </div>

                                                    <!-- Amount Field -->
                                                    <div class="mb-3">
                                                        <label for="amount" class="form-label">Amount</label>
                                                        <input type="number" id="amount" name="amount" class="form-control" required />
                                                    </div>

                                                    <!-- Note Field -->
                                                    <div class="mb-3">
                                                        <label for="note" class="form-label">Note</label>
                                                        <textarea id="note" name="note" class="form-control"></textarea>
                                                    </div>

                                                    <!-- Submit Button -->
                                                    <button type="submit" name="submit_purchase" class="btn btn-success" id="submit_button">Submit Bill</button>
                                                    </form>
                                                    <div id="loading_message" style="display:none;">Please wait, your data is being inserted...</div>

                                                <script>
        function disableButton() {
            // Disable the submit button
            document.getElementById("submit_button").disabled = true;

            // Show the "Please wait" message
            document.getElementById("loading_message").style.display = "block";
        }
    </script>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Payment Modal -->
                                <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="paymentModalLabel">Pay Amount</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <!-- Form to make a payment -->
                                                <form id="payment_form" method="POST" onsubmit="disableButton()">
                                                <!-- Supplier Select Box -->
                                                    <div class="mb-3">
                                                        <label for="supplier_id" class="form-label">Select Supplier</label>
                                                        <div class="custom-select-supplier-container">
                                                            <input type="text" id="searchSupplierInputModal" placeholder="Search Supplier" autocomplete="off" class="form-control" onkeyup="filterSuppliersModal()">
                                                            <select id="supplier_id" name="supplier_id" class="form-select" required style="display:none;" onchange="updateRemainingAmount()">
                                                                <option value="">Select Supplier</option>
                                                                <?php foreach ($suppliers as $supplier): ?>
                                                                    <option value="<?= $supplier['id'] ?>"><?= htmlspecialchars($supplier['name']) ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <div class="dropdown" id="supplierDropdownModal"></div>
                                                        </div>

                                                        <!-- JavaScript to filter the dropdown options for Suppliers in Modal -->
                                                        <script>
                                                            function filterSuppliersModal() {
                                                                var input, filter, select, options, dropdown, i;
                                                                input = document.getElementById("searchSupplierInputModal");
                                                                filter = input.value.toLowerCase();
                                                                select = document.getElementById("supplier_id");
                                                                options = select.getElementsByTagName("option");
                                                                dropdown = document.getElementById("supplierDropdownModal");
                                                                dropdown.innerHTML = "";

                                                                for (i = 1; i < options.length; i++) {
                                                                    txtValue = options[i].textContent || options[i].innerText;
                                                                    if (txtValue.toLowerCase().indexOf(filter) > -1) {
                                                                        var div = document.createElement("div");
                                                                        div.textContent = txtValue;
                                                                        div.setAttribute("data-value", options[i].value);
                                                                        div.onclick = function() {
                                                                            select.value = this.getAttribute("data-value");
                                                                            input.value = this.textContent;
                                                                            dropdown.style.display = "none";
                                                                            select.dispatchEvent(new Event('change'));
                                                                        };
                                                                        dropdown.appendChild(div);
                                                                    }
                                                                }

                                                                dropdown.style.display = dropdown.childElementCount > 0 ? "block" : "none";
                                                            }

                                                            document.getElementById("searchSupplierInputModal").addEventListener("focus", function() {
                                                                document.getElementById("supplierDropdownModal").style.display = "block";
                                                            });

                                                            document.addEventListener("click", function(event) {
                                                                if (!event.target.closest(".custom-select-supplier-container")) {
                                                                    document.getElementById("supplierDropdownModal").style.display = "none";
                                                                }
                                                            });

                                                            document.getElementById("searchSupplierInputModal").addEventListener("input", function() {
                                                                if (this.value === "") {
                                                                    document.getElementById("supplier_id").value = "";
                                                                    filterSuppliersModal();
                                                                }
                                                            });
                                                        </script>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label for="purchase_date" class="form-label">Date</label>
                                                        <input type="date" id="purchase_date" name="purchase_date" class="form-control" required />
                                                    </div>
                                                    <!-- Remaining Amount Display -->
                                                    <div class="mb-3">
                                                        <label for="remaining_amount" class="form-label">Remaining Amount</label>
                                                        <input type="text" id="remaining_amount" class="form-control" readonly />
                                                    </div>

                                                    <!-- Amount to Pay -->
                                                    <div class="mb-3">
                                                        <label for="amount" class="form-label">Amount to Pay</label>
                                                        <input type="number" id="amount" name="amount" class="form-control" required />
                                                    </div>

                                                    <!-- Bank Select Box -->
                                                    <div class="mb-3">
                                                        <label for="bank_id" class="form-label">Select Bank</label>
                                                        <select id="bank_id" name="bank_id" class="form-select" required>
                                                            <option value="">Select Bank</option>
                                                            <?php foreach ($banks as $bank): ?>
                                                                <option value="<?= $bank['id'] ?>"><?= htmlspecialchars($bank['bank_name']) ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>

                                                    <!-- Note Field -->
                                                    <div class="mb-3">
                                                        <label for="note" class="form-label">Note</label>
                                                        <textarea id="note" name="note" class="form-control"></textarea>
                                                    </div>

                                                    <!-- Purchase Date -->


                                                    <!-- Submit Button -->
                                                    <button type="submit" name="submit_pay" class="btn btn-success">Submit Payment</button>
                                                </form>
                                                <div id="loading_message_pay" style="display:none;">Please wait, your payment is being processed...</div>

                                                <script>
        function disableButton() {
            document.getElementById("submit_button_pay").disabled = true;

            document.getElementById("loading_message_pay").style.display = "block";
        }
    </script>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- JavaScript to update the remaining amount dynamically -->
                                <script>
                                    function updateRemainingAmount() {
                                        var supplier_id = document.getElementById("supplier_id").value;

                                        if (supplier_id) {
                                            // Make an AJAX request to fetch remaining amount for the selected supplier
                                            var xhr = new XMLHttpRequest();
                                            xhr.open("GET", "fetch_remaining_amount_supplier.php?supplier_id=" + supplier_id, true);
                                            xhr.onload = function() {
                                                if (xhr.status === 200) {
                                                    var response = JSON.parse(xhr.responseText);
                                                    document.getElementById("remaining_amount").value = response.remaining_amount;
                                                }
                                            };
                                            xhr.send();
                                        }
                                    }
                                </script>
                                <button id="downloadPdf" class="btn btn-primary">Download PDF</button>
                                <table class="table table-hover table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Supplier Name</th>
                                            <th>Supplier Type</th>
                                            <!-- <th>Total Purchase Amount</th>
                    <th>Total Debit Amount</th> -->
                                            <!-- <th>Remaining Amount</th> -->
                                            <th>Status</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($final_results as $result): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($result['supplier_name']) ?></td>
                                                <td><?= htmlspecialchars($result['supplier_type']) ?></td>
                                                <!-- <td><?= number_format($result['total_purchase'], 2) ?></td>
                        <td><?= number_format($result['total_debit_amount'], 2) ?></td> -->
                                                <!-- <td><?= number_format($result['remaining_amount'], 2) ?></td> -->
                                                <td>
                                                    <?php if ($result['status'] == 'Pending'): ?>
                                                        <span class="badge bg-warning"><?= $result['status']; ?></span>
                                                    <?php else: ?>
                                                        <span class="badge bg-success"><?= $result['status']; ?></span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <a href="supplier_ledger_detail.php?supplier_id=<?= $result['supplier_id']; ?>" class="btn btn-info">View Details</a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <script>
                                    document.getElementById('downloadPdf').addEventListener('click', function() {
                                        const {
                                            jsPDF
                                        } = window.jspdf;

                                        const doc = new jsPDF();

                                        const originalTable = document.querySelector('.table');
                                        const tempTable = originalTable.cloneNode(true);

                                        tempTable.querySelectorAll('thead tr th:last-child').forEach(el => el.remove());
                                        tempTable.querySelectorAll('tbody tr').forEach(row => {
                                            row.querySelector('td:last-child').remove();
                                        });

                                        doc.autoTable({
                                            html: tempTable,
                                            startY: 10,
                                            theme: 'grid',
                                        });

                                        // Save the PDF
                                        doc.save('Supplier Due amount Report.pdf');
                                    });
                                </script>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
    <script>
        function filterTable() {
            var input = document.getElementById("searchInput");
            var filter = input.value.toLowerCase();

            // Get the table and rows
            var table = document.getElementById("bankTable");
            var rows = table.getElementsByTagName("tr");

            for (var i = 1; i < rows.length; i++) {
                var cells = rows[i].getElementsByTagName("td");
                var matchFound = false;

                for (var j = 0; j < cells.length; j++) {
                    var cell = cells[j];
                    if (cell) {
                        if (cell.textContent.toLowerCase().indexOf(filter) > -1) {
                            matchFound = true;
                            break;
                        }
                    }
                }

                if (matchFound) {
                    rows[i].style.display = "";
                } else {
                    rows[i].style.display = "none";
                }
            }
        }
    </script>

    <!-- Wrapper END -->
    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>