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

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

$customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
if (empty($customer_id)) {
    echo "<p>Error: Customer ID is required.</p>";
    exit;
}

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

try {
    // Fetch customer details
    $queryCustomer = "SELECT name, opening_balance, created_at FROM contacts WHERE id = :customer_id";
    $stmtCustomer = $conn->prepare($queryCustomer);
    $stmtCustomer->execute(['customer_id' => $customer_id]);
    $customer = $stmtCustomer->fetch(PDO::FETCH_ASSOC);

    if (!$customer) {
        echo "<p>Customer not found.</p>";
        exit;
    }

    $opening_balance = floatval($customer['opening_balance']);
    $created_at = $customer['created_at'];

    // Fetch sales details
    $querySale = "
        SELECT 
            invoice, customer_id, SUM(total_amount - discount) AS total_amount, MIN(date_sale) AS date_sale
        FROM 
            stock_sale
        WHERE 
            customer_id = :customer_id";

    if (!empty($start_date) && !empty($end_date)) {
        $querySale .= " AND date_sale BETWEEN :start_date AND :end_date";
    }

    $querySale .= " GROUP BY invoice";

    $stmtSale = $conn->prepare($querySale);
    $stmtSale->bindParam(':customer_id', $customer_id);

    if (!empty($start_date) && !empty($end_date)) {
        $stmtSale->bindParam(':start_date', $start_date);
        $stmtSale->bindParam(':end_date', $end_date);
    }

    $stmtSale->execute();
    $saleDetails = $stmtSale->fetchAll(PDO::FETCH_ASSOC);

    // Fetch deposit details
    $queryDeposit = "
        SELECT 
          id AS cash_deposit_id, invoice, bank_id, amount, date_deposit, payment_status 
        FROM 
            cash_deposit
        WHERE 
            user_id = :customer_id";

    if (!empty($start_date) && !empty($end_date)) {
        $queryDeposit .= " AND date_deposit BETWEEN :start_date AND :end_date";
    }

    $stmtDeposit = $conn->prepare($queryDeposit);
    $stmtDeposit->bindParam(':customer_id', $customer_id);

    if (!empty($start_date) && !empty($end_date)) {
        $stmtDeposit->bindParam(':start_date', $start_date);
        $stmtDeposit->bindParam(':end_date', $end_date);
    }

    $stmtDeposit->execute();
    $depositDetails = $stmtDeposit->fetchAll(PDO::FETCH_ASSOC);

    // Fetch customer bills from customer_bill_manual
    $queryBillManual = "SELECT id AS customer_bill_id,
            amount, note, bill_date 
        FROM 
            customer_bill_manual
        WHERE 
            user_id = :customer_id";

    $stmtBillManual = $conn->prepare($queryBillManual);
    $stmtBillManual->bindParam(':customer_id', $customer_id);
    $stmtBillManual->execute();
    $billManualDetails = $stmtBillManual->fetchAll(PDO::FETCH_ASSOC);

    // Fetch banks for deposit info
    $queryBanks = "SELECT id, bank_name FROM banks";
    $stmtBanks = $conn->prepare($queryBanks);
    $stmtBanks->execute();
    $banks = $stmtBanks->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {
    echo "<p>Database error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}

$transactions = [];

// Add sales transactions
foreach ($saleDetails as $sale) {
    // $transactions[] = [
    //     'id' => $sale['invoice'],
    //     'date' => $sale['date_sale'],
    //     'particular' => "Invoice Payment #" . intval($sale['invoice']),
    //     'debit' => $sale['total_amount'],
    //     'credit' => '',
    //     'type' => 'Debit',
    //     'amount' => $sale['total_amount'],
    // ];
    $invoiceRaw = $sale['invoice']; 

$transactions[] = [
    'id' => $invoiceRaw,
    'date' => $sale['date_sale'],
    'particular' => '<a href="print/customer_bill_reprint.php?invoice_no=' . $invoiceRaw . '" target="_blank">Invoice Payment #' . intval($invoiceRaw) . '</a>',
    'debit' => $sale['total_amount'],
    'credit' => '',
    'type' => 'Debit',
    'amount' => $sale['total_amount'],
];

}

// Add deposit transactions
foreach ($depositDetails as $deposit) {
    $bankName = isset($banks[$deposit['bank_id']]) ? $banks[$deposit['bank_id']] : 'Payment Receive';
    $transactions[] = [
        'id' => $deposit['invoice'],
        'date' => $deposit['date_deposit'],
        'particular' => $bankName . ' / ' . $deposit['payment_status'] . '  # ' . (intval($deposit['invoice'])),
        'debit' => '',
        'credit' => $deposit['amount'],
        'type' => 'Credit',
        'amount' => $deposit['amount'],
        'cash_deposit_id' => $deposit['cash_deposit_id'],
    ];
}

// Add bill manual transactions
foreach ($billManualDetails as $bill) {
    $transactions[] = [
        'customer_bill_id' => $bill['customer_bill_id'],
        'id' => $bill['amount'],
        'date' => $bill['bill_date'],
        'particular' => 'Customer Bill #' . ': ' . $bill['note'], // Bill number and note
        'debit' => $bill['amount'],
        'credit' => '',
        'type' => 'Debit',
        'amount' => $bill['amount'],
    ];
}

usort($transactions, function ($a, $b) {
    return strtotime($a['date']) <=> strtotime($b['date']);
});

if ($opening_balance > 0) {
    array_unshift($transactions, [
        'id' => 0,
        'date' => $created_at,
        'particular' => 'Opening Balance',
        'debit' => '',
        'credit' => '',
        'type' => 'Opening',
        'amount' => $opening_balance,
        'balance' => $opening_balance,
    ]);
}

// Calculate balance
function calculateBalance($transactions)
{
    $balance = 0;
    foreach ($transactions as &$transaction) {
        if ($transaction['type'] === 'Debit') {
            $balance += $transaction['amount']; // Debit increases the balance
        } elseif ($transaction['type'] === 'Credit') {
            $balance -= $transaction['amount']; // Credit decreases the balance
        } elseif ($transaction['type'] === 'Opening') {
            $balance = $transaction['amount']; // Opening balance is directly set
        }
        $transaction['balance'] = $balance;
    }
    return $transactions;
}

$transactions = calculateBalance($transactions);
?>




<!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.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/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;
        }

        .filter-form {
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            margin: auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            font-weight: bold;
            display: block;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }

        .form-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .btn-submit,
        .btn-clear {
            padding: 10px 15px;
            font-size: 16px;
            border-radius: 4px;
            text-decoration: none;
            text-align: center;
        }

        .btn-submit {
            background-color: #007bff;
            color: white;
            border: none;
        }

        .btn-submit:hover {
            background-color: #0056b3;
        }

        .btn-clear {
            background-color: #6c757d;
            color: white;
        }

        .btn-clear:hover {
            background-color: #5a6268;
        }

        /* Three dots icon */
        .dropbtn {
            font-size: 18px;
            padding: 5px;
            color: #333;
        }

        /* Dropdown container */
        .dropdown-content {
            display: none;
            position: absolute;
            right: 0;
            background-color: #fff;
            border-radius: 4px;
            min-width: 120px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            z-index: 10;
            overflow: hidden;
        }

        /* Dropdown links */
        .dropdown-content a {
            text-decoration: none;
            color: #333;
            display: block;
            padding: 8px 10px;
            font-size: 14px;
        }

        .dropdown-content a:hover {
            background-color: #f1f1f1;
            color: #000;
        }

        /* Dropdown visibility on hover */
        .dropdown:hover .dropdown-content {
            display: block;
        }
    </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;">
                                <form action="customer_ledger_detail.php" method="get" class="filter-form">
                                    <div class="form-group">
                                        <label for="start_date">Start Date:</label>
                                        <input type="date" name="start_date" value="<?php echo $start_date; ?>" class="form-input">
                                    </div>
                                    <div class="form-group">
                                        <label for="end_date">End Date:</label>
                                        <input type="date" name="end_date" value="<?php echo $end_date; ?>" class="form-input">
                                    </div>
                                    <input type="hidden" name="customer_id" value="<?php echo $customer_id; ?>">
                                    <!-- <input type="hidden" name="invoice" value="<?php echo $invoice; ?>"> -->

                                    <div class="form-actions">
                                        <button type="submit" class="btn-submit">Filter</button>
                                        <a href="customer_ledger_detail.php?customer_id=<?php echo $customer_id; ?>" class="btn-clear">Clear Filter</a>
                                    </div>
                                </form>

                                <div class="container">
                                    <h1>Customer Ledger - <?php echo htmlspecialchars($customer['name']); ?></h1>
                                    <!-- <p><strong>Customer ID:</strong> <?php echo htmlspecialchars($customer_id); ?></p> -->



                                    <button id="download-pdf" class="btn btn-success" style="margin-top: 20px;">Download PDF</button>


                                    <table class="table table-hover table-bordered" id="ledgerTable">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Particular</th>
                                                <th>Debit</th>
                                                <th>Credit</th>
                                                <th>Balance</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $totalDebit = 0;
                                            $totalCredit = 0;
                                            ?>
                                            <?php foreach ($transactions as $transaction):
                                                $totalDebit += $transaction['debit'] ? $transaction['debit'] : 0;
                                                $totalCredit += $transaction['credit'] ? $transaction['credit'] : 0;
                                            ?>
                                                <tr>
                                                    <td><?php echo date("d M Y", strtotime($transaction['date'])); ?></td>
                                                    <!--<td><?php echo htmlspecialchars($transaction['particular']); ?></td>-->
                                                    <td><?php echo $transaction['particular']; ?></td>

                                                    <td>
    <?php if ($transaction['debit']): ?>
        <span class="text-danger"><?php echo number_format($transaction['debit'], 2); ?></span>
        <?php if ($transaction['particular'] && str_contains($transaction['particular'], 'Customer Bill')): ?>
            <div class="dropdown" style="position: relative; display: inline-block;">
                <!-- Three dots button -->
                <button class="dropbtn" style="border: none; background: none; cursor: pointer;">
                    <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                </button>

                <!-- Dropdown content -->
                <div class="dropdown-content" style="display: none; position: absolute; background-color: #f9f9f9; min-width: 100px; box-shadow: 0px 8px 16px rgba(0,0,0,0.2); padding: 5px; z-index: 1;">
                    <a href="#" class="edit-debit-transaction"
                        data-id="<?php echo htmlspecialchars($transaction['customer_bill_id']); ?>"
                        data-amount="<?php echo htmlspecialchars($transaction['debit']); ?>"
                        data-type="debit">Edit</a>
                    <a href="#" class="delete-debit-transaction"
                        data-id="<?php echo htmlspecialchars($transaction['customer_bill_id']); ?>"
                        data-type="debit">Delete</a>
                </div>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</td>

                                                    <td>
                                                        <?php if ($transaction['credit']): ?>
                                                            <span class="text-success"><?php echo number_format($transaction['credit'], 2); ?></span>
                                                            <div class="dropdown" style="position: relative; display: inline-block;">
                                                                <!-- Three dots button -->
                                                                <button class="dropbtn" style="border: none; background: none; cursor: pointer;">
                                                                    <i class="fa fa-ellipsis-v" aria-hidden="true"></i>
                                                                </button>

                                                                <!-- Dropdown content -->
                                                                <div class="dropdown-content" style="display: none; position: absolute; background-color: #f9f9f9; min-width: 100px; box-shadow: 0px 8px 16px rgba(0,0,0,0.2); padding: 5px; z-index: 1;">
                                                                    <a href="#" class="edit-transaction"
                                                                        data-id="<?php echo htmlspecialchars($transaction['cash_deposit_id']); ?>"
                                                                        data-amount="<?php echo htmlspecialchars($transaction['credit']); ?>"
                                                                        data-type="credit">Edit</a>
                                                                    <a href="#" class="delete-transaction"
                                                                        data-id="<?php echo htmlspecialchars($transaction['cash_deposit_id']); ?>"
                                                                        data-type="credit">Delete</a>
                                                                </div>
                                                            </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo number_format($transaction['balance'], 2); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr style="background-color:#ddd;">
                                                <th colspan="1" class="text-end" style="font-weight: bold;">Total:</th>
                                                <th></th>
                                                <th class="text-danger" style="font-weight: bold;"><?php echo number_format($totalDebit, 2); ?></th>
                                                <th class="text-success" style="font-weight: bold;"><?php echo number_format($totalCredit, 2); ?></th>
                                                <th style="font-weight: bold;"><?php echo number_format(end($transactions)['balance'], 2); ?></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                    <script>
                                        document.addEventListener("DOMContentLoaded", function() {
                                            // Edit transaction
                                            document.querySelectorAll('.edit-transaction').forEach(btn => {
                                                btn.addEventListener('click', function(e) {
                                                    e.preventDefault();
                                                    const id = this.getAttribute('data-id');
                                                    const amount = this.getAttribute('data-amount');

                                                    const newAmount = prompt("Enter new amount for this credit transaction:", amount);
                                                    if (newAmount !== null) {
                                                        fetch('update_transaction_customer.php', {
                                                                method: 'POST',
                                                                headers: {
                                                                    'Content-Type': 'application/json'
                                                                },
                                                                body: JSON.stringify({
                                                                    id,
                                                                    amount: newAmount
                                                                })
                                                            })
                                                            .then(response => response.json())
                                                            .then(data => {
                                                                if (data.success) {
                                                                    alert('Transaction updated successfully!');
                                                                    location.reload();
                                                                } else {
                                                                    alert('Error updating transaction: ' + data.error);
                                                                }
                                                            })
                                                            .catch(error => console.error('Error:', error));
                                                    }
                                                });
                                            });

                                            // Delete transaction
                                            document.querySelectorAll('.delete-transaction').forEach(btn => {
                                                btn.addEventListener('click', function(e) {
                                                    e.preventDefault();
                                                    const id = this.getAttribute('data-id');

                                                    if (confirm('Are you sure you want to delete this transaction?')) {
                                                        fetch('action/delete_transaction_customer.php', {
                                                                method: 'POST',
                                                                headers: {
                                                                    'Content-Type': 'application/json'
                                                                },
                                                                body: JSON.stringify({
                                                                    id
                                                                })
                                                            })
                                                            .then(response => response.json())
                                                            .then(data => {
                                                                if (data.success) {
                                                                    alert('Transaction deleted successfully!');
                                                                    location.reload();
                                                                } else {
                                                                    alert('Error deleting transaction: ' + data.error);
                                                                }
                                                            })
                                                            .catch(error => console.error('Error:', error));
                                                    }
                                                });
                                            });
                                        });
                                        document.addEventListener('DOMContentLoaded', function() {
                                            document.querySelectorAll('.dropbtn').forEach(button => {
                                                button.addEventListener('click', function(e) {
                                                    e.stopPropagation();
                                                    document.querySelectorAll('.dropdown-content').forEach(menu => {
                                                        if (menu !== this.nextElementSibling) {
                                                            menu.style.display = 'none';
                                                        }
                                                    });
                                                    const dropdownMenu = this.nextElementSibling;
                                                    dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';
                                                });
                                            });

                                            document.addEventListener('click', function() {
                                                document.querySelectorAll('.dropdown-content').forEach(menu => {
                                                    menu.style.display = 'none';
                                                });
                                            });
                                        });
                                        document.addEventListener("DOMContentLoaded", function() {
    // Edit debit transaction
    document.querySelectorAll('.edit-debit-transaction').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const id = this.getAttribute('data-id');
            const amount = this.getAttribute('data-amount');

            const newAmount = prompt("Enter new amount for this debit transaction:", amount);
            if (newAmount !== null) {
                fetch('update_transaction_customer_bill.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            id,
                            amount: newAmount
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('Transaction updated successfully!');
                            location.reload();
                        } else {
                            alert('Error updating transaction: ' + data.error);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
        });
    });

    // Delete debit transaction
    document.querySelectorAll('.delete-debit-transaction').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const id = this.getAttribute('data-id');

            if (confirm('Are you sure you want to delete this transaction?')) {
                fetch('action/delete_transaction_customer_bill.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            id
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('Transaction deleted successfully!');
                            location.reload();
                        } else {
                            alert('Error deleting transaction: ' + data.error);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
        });
    });
});

                                    </script>


                                    <a href="list_customer_ledger.php" class="btn btn-secondary">Back to Transactions</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
    <script>
    document.getElementById('download-pdf').addEventListener('click', function() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();

        const dropdowns = document.querySelectorAll('.dropdown, .dropbtn, .dropdown-content');
        dropdowns.forEach(function(dropdown) {
            dropdown.remove();
        });

        doc.autoTable({
            html: '#ledgerTable',
            startY: 20,
            margin: {
                horizontal: 10
            },
            tableWidth: 'auto',
            theme: 'grid',
            headStyles: {
                fillColor: [22, 160, 133]
            },
            styles: {
                cellPadding: 5,
                fontSize: 10,
            }
        });

        // Calculate the position for the total row
        const finalY = doc.lastAutoTable.finalY || 20;
        if (doc.internal.pageSize.height - finalY < 30) {
            doc.addPage();
        }

        // Add the total row at the end of the document
        doc.autoTable({
            body: [
                [
                    'Total', '',
                    '<?php echo number_format($totalDebit, 2); ?>',
                    '<?php echo number_format($totalCredit, 2); ?>',
                    '<?php echo number_format(end($transactions)['balance'], 2); ?>'
                ]
            ],
            startY: doc.internal.pageSize.height - 30,
            theme: 'grid',
            styles: {
                fontSize: 10,
                cellPadding: 5
            }
        });

        // Save the PDF as a file
        doc.save('<?php echo htmlspecialchars($customer['name']); ?> Ledger.pdf');
    });
</script> 

    <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>