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

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

?>


<!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>
    <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-container {
        position: relative;
        width: 100%;
    }

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

    .custom-select-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-container .dropdown div {
        padding: 10px;
        cursor: pointer;
    }

    .custom-select-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> > Customer 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;">


                            <?php

// Check if form is submitted to insert the bill into the database
if (isset($_POST['submit_bill'])) {
    // Prevent double submission using session flag
    
        try {
            $user_id = $_POST['customer_id'];
            $amount = $_POST['bill_amount'];
            $note = $_POST['note'];
            $bill_date = $_POST['bill_date'];

            // Prepare the insert statement for the customer_bill_manual table
            $insertQuery = "INSERT INTO customer_bill_manual (user_id, amount, note, bill_date) 
                            VALUES (:user_id, :amount, :note, :bill_date)";
            $stmt = $conn->prepare($insertQuery);
            $stmt->bindParam(':user_id', $user_id);
            $stmt->bindParam(':amount', $amount);
            $stmt->bindParam(':note', $note);
            $stmt->bindParam(':bill_date', $bill_date);
            $stmt->execute();

            $bill_id = $conn->lastInsertId();
    
            // Redirect to the receipt page with bill_id
            echo "<script>
                    alert('Payment recorded successfully!');
                    window.location.href = 'customer_receipt.php?bill_id=" . $bill_id . "';
                  </script>";
        } catch (PDOException $e) {
            $message = "Error: " . htmlspecialchars($e->getMessage());
        }
}

// Fetch customer data
try {
    $query = "
    SELECT 
        c.id AS customer_id, 
        c.name AS customer_name,
        COALESCE(s.total_sales_amount, 0) AS total_sales_amount,
        c.opening_balance,
        COALESCE(cd.total_deposit, 0) AS total_deposit,
        COALESCE(cb.total_billed_amount, 0) AS total_billed_amount
    FROM 
        contacts c
    LEFT JOIN 
        (SELECT customer_id, SUM(total_amount) AS total_sales_amount 
         FROM stock_sale 
         GROUP BY customer_id) s ON c.id = s.customer_id
    LEFT JOIN 
        (SELECT user_id, SUM(amount) AS total_deposit 
         FROM cash_deposit 
         GROUP BY user_id) cd ON c.id = cd.user_id
    LEFT JOIN 
        (SELECT user_id, SUM(amount) AS total_billed_amount 
         FROM customer_bill_manual 
         GROUP BY user_id) cb ON c.id = cb.user_id
    WHERE 
        c.type = 'customer'
    GROUP BY 
        c.id, c.name, c.opening_balance, s.total_sales_amount, cd.total_deposit, cb.total_billed_amount
    HAVING 
        total_sales_amount > 0 OR c.opening_balance > 0 OR total_billed_amount > 0
    ORDER BY 
        c.name ASC";


    $stmt = $conn->prepare($query);
    $stmt->execute();
    $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // If no data found
    if (empty($customers)) {
        $message = "No sales, opening balance, or manual bill data available.";
    }
} catch (PDOException $e) {
    echo "<p>Database error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}

// Check if a search term is provided
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
if ($searchTerm) {
    $customers = array_filter($customers, function($customer) use ($searchTerm) {
        return stripos($customer['customer_name'], $searchTerm) !== false;
    });
}
?>

<!-- Search Bar and Buttons -->
<form method="GET" action="" class="mb-3">
    <div class="form-group d-flex">
        <!-- Search Input Field -->
        <input type="text" name="search" class="form-control" placeholder="Search Customer..." value="<?php echo htmlspecialchars($searchTerm); ?>" style="width: 70%;">
        
        <!-- Submit Button -->
        <button type="submit" class="btn btn-primary ml-2">Submit</button>
        
        <!-- Clear Filter Button -->
        <a href="list_customer_ledger.php" class="btn btn-secondary ml-2">Clear Filter</a>
    </div>
</form>
<!-- Button to Trigger Modal -->
<!-- <button type="button" class="btn btn-success" data-toggle="modal" data-target="#addBillModal">Add Bill</button> -->

<!-- --------------------------------------------Add bill Modal Start--------------------------------------------------------------->
<div class="modal fade" id="addBillModal" tabindex="-1" role="dialog" aria-labelledby="addBillModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addBillModalLabel">Add Customer Bill</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Bill Form -->
                <form method="POST" action="">
                    <div class="form-group">
                        <label for="customer_id">Select Customer</label>
                        <?php
// Fetch contacts from the database using PDO
$query = "SELECT id, type, name FROM contacts WHERE type = 'customer' ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();

// Fetch all contacts
$contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>



<!-- HTML Form with the Custom Select Dropdown -->
<div class="custom-select-container">
    <input type="text" id="searchInput" placeholder="Search Contact" class="form-control" onkeyup="filterContacts()">
    <select name="customer_id" id="customer_id" class="form-control" required style="display:none;">
        <option value="">Select Contact</option>
        <?php foreach ($contacts as $contact): ?>
            <option value="<?php echo $contact['id']; ?>">
                <?php echo htmlspecialchars($contact['name']) . " (" . htmlspecialchars($contact['type']) . ")"; ?>
            </option>
        <?php endforeach; ?>
    </select>
    <div class="dropdown" id="dropdown"></div>
</div>

<!-- JavaScript to filter the dropdown options -->
<script>
    function filterContacts() {
        var input, filter, select, options, dropdown, i;
        input = document.getElementById("searchInput");
        filter = input.value.toLowerCase();
        select = document.getElementById("customer_id");
        options = select.getElementsByTagName("option");
        dropdown = document.getElementById("dropdown");
        dropdown.innerHTML = "";

        for (i = 1; i < options.length; i++) { // Start from 1 to skip the "Select Contact" option
            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')); // Trigger change event
                };
                dropdown.appendChild(div);
            }
        }

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

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

    document.addEventListener("click", function(event) {
        if (!event.target.closest(".custom-select-container")) {
            document.getElementById("dropdown").style.display = "none";
        }
    });
</script>

<script> 
document.getElementById('customer_id').addEventListener('change', function() {
    const customerId = this.value;
    const remainingBalanceInput = document.getElementById('remaining_balance');

    let found = false; // Flag to track if a matching customer is found
    if (customerId) {
        <?php foreach ($customers as $customer): ?>
            if (customerId == "<?php echo $customer['customer_id']; ?>") {
                const remainingBalance = <?php echo ($customer['total_sales_amount'] - $customer['total_deposit']) + $customer['opening_balance']; ?>;
                const totalBilledAmount = <?php echo $customer['total_billed_amount']; ?>;
                remainingBalanceInput.value = (remainingBalance + totalBilledAmount).toFixed(2);
                found = true; // Mark as found
            }
        <?php endforeach; ?>
    }

    // Reset the balance if no match is found
    if (!found) {
        remainingBalanceInput.value = '0'; // Or you can set it to an empty string ('') if preferred
    }
});

</script>


                    </div>

                    <!-- Remaining Balance Display -->
                    <div id="remaining_balance_div" class="form-group">
                        <label for="remaining_balance">Remaining Balance</label>
                        <input type="text" id="remaining_balance" class="form-control" readonly>
                    </div>

                    <div class="form-group">
                        <label for="bill_amount">Bill Amount</label>
                        <input type="number" name="bill_amount" id="bill_amount" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label for="bill_date">Bill Date</label>
                        <input type="date" name="bill_date" id="bill_date" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label for="note">Note</label>
                        <textarea name="note" id="note" class="form-control" rows="3"></textarea>
                    </div>

                    <button type="submit" name="submit_bill" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!---------------------------------------------------------------End add bill model------------------------------------------>
<!-- Button to Trigger Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#receiveAmountModal">Receive Amount</button>

<!-- Modal for Receive Amount -->
<div class="modal fade" id="receiveAmountModal" tabindex="-1" role="dialog" aria-labelledby="receiveAmountModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="receiveAmountModalLabel">Receive Amount</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <!-- Form to Receive Amount -->
        <form id="receiveForm" method="POST">
          <input type="hidden" name="submit_receive" value="1" /> <!-- Add this hidden input -->

          <div class="form-group">
            <label for="customer_id">Customer</label>
            <div class="custom-select-container">
              <input type="text" id="searchCustomerInput" placeholder="Search Customer" class="form-control" autocomplete="off" onkeyup="filterCustomers()">
              <select id="customer_id_data" name="customer_id" class="form-control" required style="display:none;">
                <option value="">Select Customer</option>
                <?php foreach ($customers as $customer): ?>
                  <option value="<?php echo $customer['customer_id']; ?>">
                    <?php echo htmlspecialchars($customer['customer_name']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="dropdown" id="customerDropdown"></div>
            </div>
          </div>

          <div class="form-group">
            <label for="remaining_balance">Remaining Balance</label>
            <input type="text" id="remaining_balance_data" class="form-control" readonly>
          </div>

          <div class="form-group">
            <label for="receive_amount">Receive Amount</label>
            <input type="number" id="receive_amount" name="receive_amount" class="form-control" required>
          </div>

          <div class="form-group">
            <label for="date_deposit">Deposit Date</label>
            <input type="date" id="date_deposit" name="date_deposit" class="form-control" required>
          </div>

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

          <button type="submit" id="submitReceiveBtn" class="btn btn-primary">
            <span class="btn-text">Submit</span>
            <span class="btn-loading" style="display:none;">
              <div class="spinner-border spinner-border-sm text-light" role="status">
                <span class="sr-only">Loading...</span>
              </div> Processing...
            </span>
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  // Customer dropdown filtering
  function filterCustomers() {
    var input = document.getElementById("searchCustomerInput");
    var filter = input.value.toLowerCase();
    var select = document.getElementById("customer_id_data");
    var options = select.getElementsByTagName("option");
    var dropdown = document.getElementById("customerDropdown");
    dropdown.innerHTML = "";

    for (var i = 1; i < options.length; i++) { // skip first "Select Customer"
      var 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')); // trigger change event
        };
        dropdown.appendChild(div);
      }
    }

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

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

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

  // Submit handler for AJAX form submission
  document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('receiveForm');
    if (!form) return;

    form.addEventListener('submit', function(e) {
      e.preventDefault();

      const btn = document.getElementById('submitReceiveBtn');
      if (!btn) {
        console.error('Submit button not found!');
        return;
      }
      const btnText = btn.querySelector('.btn-text');
      const btnLoading = btn.querySelector('.btn-loading');

      btn.disabled = true;
      btnText.style.display = 'none';
      btnLoading.style.display = 'inline-flex';

      const formData = new FormData(form);

      fetch('ajax_receive_payment.php', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
      .then(response => response.json())
      .then(data => {
        btn.disabled = false;
        btnText.style.display = 'inline';
        btnLoading.style.display = 'none';

        if (data.success) {
          alert('Payment recorded successfully!');
          window.location.href = `customer_receive_receipt.php?user_id=${data.user_id}&payment_amount=${data.amount}&final_balance=${data.final_balance}`;
        } else {
          alert('Error: ' + (data.message || 'Unknown error'));
        }
      })
      .catch(error => {
        btn.disabled = false;
        btnText.style.display = 'inline';
        btnLoading.style.display = 'none';
        alert('AJAX error: ' + error.message);
      });
    });
  });
</script>


<!-- Include necessary JS files for Bootstrap and jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>

<script>
    // Script to dynamically update the remaining balance when customer is selected
    document.getElementById('customer_id_data').addEventListener('change', function() {
        const customerId = this.value;
        const remainingBalanceInput = document.getElementById('remaining_balance_data');
        
        if (customerId) {
            // Fetch the remaining balance for the selected customer
            <?php foreach ($customers as $customer): ?>
                if (customerId == "<?php echo $customer['customer_id']; ?>") {
                    const remainingBalance = <?php echo ($customer['total_sales_amount'] + $customer['total_billed_amount'] - $customer['total_deposit']) + $customer['opening_balance']; ?>;
                    remainingBalanceInput.value = remainingBalance.toFixed(2);
                }
            <?php endforeach; ?>
        } else {
            remainingBalanceInput.value = '';
        }
    });
</script>
<!-- Customer Table -->
<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>
<button id="downloadPdf" class="btn btn-primary">Download PDF</button>
<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('Customer_Due_Report.pdf');
        });
    </script>
<table class="table table-hover table-bordered">
    <thead>
        <tr>
            <th>Sr#</th>
            <th>Customer Name</th>
            <!--<th>Total Due Amount</th>-->
            <th>Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $sr = 1;
        foreach ($customers as $customer):
            // Calculate the remaining balance (Sales - Deposit + Opening Balance)
            $remaining_balance = ($customer['total_sales_amount'] - $customer['total_deposit']) + $customer['opening_balance'];

            // Add the total billed amount to the remaining balance
            $final_balance = $remaining_balance + $customer['total_billed_amount'];

            // Determine the status based on the final amount
            $status = $final_balance > 0 ? 'Pending' : 'Paid';
        ?>
            <tr>
                <td><?php echo $sr++; ?></td>
                <td><?php echo htmlspecialchars($customer['customer_name']); ?></td>
                 <!--<td><?php echo number_format($final_balance, 2); ?></td>-->
                <td><?php echo $status; ?></td>
                <td>
                    <a href="customer_ledger_detail.php?customer_id=<?php echo $customer['customer_id']; ?>" class="btn btn-info">
                        View Ledger
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- Include necessary JS files for Bootstrap and jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></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>