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

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Initialize variables for date filter
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';

try {
    // Base queries for incoming and outgoing transactions
    $queryIn = "
        SELECT 
            cd.invoice,
            cd.bank_id,
            cd.amount,
            cd.date_deposit AS date,
            cd.payment_status,
            b.bank_name
        FROM 
            cash_deposit cd
        JOIN 
            banks b ON cd.bank_id = b.id
        WHERE 
            (:start_date IS NULL OR cd.date_deposit >= :start_date) AND
            (:end_date IS NULL OR cd.date_deposit <= :end_date)";

    $queryOut = "
        SELECT 
            bda.bank_id,
            bda.ref_no,
            bda.amount,
            bda.date,
            bda.note,
            b.bank_name
        FROM 
            bank_debit_amount bda
        JOIN 
            banks b ON bda.bank_id = b.id
        WHERE 
            (:start_date IS NULL OR bda.date >= :start_date) AND
            (:end_date IS NULL OR bda.date <= :end_date)";

    // Prepare and execute incoming transactions query
    $stmtIn = $conn->prepare($queryIn);
    $stmtIn->execute([
        'start_date' => $startDate ?: null,
        'end_date' => $endDate ?: null
    ]);
    $resultsIn = $stmtIn->fetchAll(PDO::FETCH_ASSOC);

    // Prepare and execute outgoing transactions query
    $stmtOut = $conn->prepare($queryOut);
    $stmtOut->execute([
        'start_date' => $startDate ?: null,
        'end_date' => $endDate ?: null
    ]);
    $resultsOut = $stmtOut->fetchAll(PDO::FETCH_ASSOC);

    // Merge and sort transactions
    $transactions = array_merge(
        array_map(function ($row) {
            $row['type'] = 'in';
            return $row;
        }, $resultsIn),
        array_map(function ($row) {
            $row['type'] = 'out';
            return $row;
        }, $resultsOut)
    );

    usort($transactions, function ($a, $b) {
        return strtotime($b['date']) - strtotime($a['date']);
    });
} catch (PDOException $e) {
    echo "<p>Database error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}
?>
<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $date_deposit = $_POST['date_deposit'];
    $bank_id = $_POST['bank_id'];
    $amount = $_POST['amount'];
    $payment_status = $_POST['payment_status'];

    if (empty($date_deposit) || empty($bank_id) || empty($amount) || empty($payment_status)) {
        echo "All fields are required.";
    } else {
        try {
            $query = "INSERT INTO `cash_deposit` (`bank_id`, `amount`, `payment_status`, `date_deposit`,  `invoice`) 
                      VALUES (:bank_id, :amount, :payment_status, :date_deposit, 0)";

            $stmt = $conn->prepare($query);

            $stmt->bindParam(':bank_id', $bank_id);
            $stmt->bindParam(':amount', $amount);
            $stmt->bindParam(':payment_status', $payment_status);
            $stmt->bindParam(':date_deposit', $date_deposit);

            $stmt->execute();

            echo "<script>alert('Payment added successfully!'); window.location.href='list_transaction.php';</script>";
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
    }
}

$query = "SELECT `id`, `bank_name` FROM `banks`";
$stmt = $conn->prepare($query);
$stmt->execute();
$banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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;
        }
    </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> > Bank Transactions
                                    </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;">


                                <!-- Date Filter Form -->
                                <form method="GET" class="row g-3 mb-4">
                                    <div class="col-md-4">
                                        <label for="start_date" class="form-label">Start Date</label>
                                        <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="end_date" class="form-label">End Date</label>
                                        <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">
                                    </div>
                                    <div class="col-md-4 align-self-end">
                                        <button type="submit" class="btn btn-primary">Filter</button>
                                        <a href="list_transaction.php" class="btn btn-secondary">Clear Filter</a>

                                    </div>

                                </form>
<!-- Add jsPDF and autoTable -->
<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.15/jspdf.plugin.autotable.min.js"></script>
<button id="exportBtn" class="btn btn-primary">Export to PDF</button>
<script>
    // Wait for the document to load before adding event listeners
    document.addEventListener("DOMContentLoaded", function() {
        // Get the export button
        const exportBtn = document.getElementById('exportBtn');
        
        exportBtn.addEventListener('click', function () {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            
            // Convert the HTML table to an array of data using autoTable
            doc.autoTable({ 
                html: '#bankTable',
                startY: 20, // Adjust the Y position of the table on the PDF
                theme: 'grid', // You can choose different themes like 'striped', 'grid', etc.
                headStyles: {
                    fillColor: [22, 160, 133], // You can adjust this color as you wish
                    textColor: 255
                },
                bodyStyles: {
                    textColor: [51, 51, 51]
                },
            });

            // Save the generated PDF
            doc.save('transactions.pdf');
        });
    });
</script>

                                <!-- Transactions Table -->
                           <table class="table table-hover table-bordered" id="bankTable">
    <thead>
        <tr>
            <th>Date</th>
            <th>Account</th>
            <th>Category</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($transactions)) : ?>
            <tr>
                <td colspan="4" class="text-center">No transactions found for the selected date range.</td>
            </tr>
        <?php else : ?>
            <?php foreach ($transactions as $transaction): ?>
                <tr>
                    <td><?php echo date("d M Y", strtotime($transaction['date'])); ?></td>
                    <td><?php echo htmlspecialchars($transaction['bank_name']); ?></td>
                    <td>
                        <?php
                        if ($transaction['type'] === 'in') {
                            if (!empty($transaction['invoice'])) {
                                echo "Invoice Payment #" . htmlspecialchars($transaction['invoice']);
                            } else {
                                echo htmlspecialchars($transaction['payment_status']);
                            }
                        } else {
                            if (!empty($transaction['ref_no'])) {
                                echo "Purchase / " . htmlspecialchars($transaction['ref_no']);
                            } else {
                                echo htmlspecialchars($transaction['note']);
                            }
                        }
                        ?>
                    </td>
                    <td class="<?php echo $transaction['type'] === 'in' ? 'amount-in' : 'amount-out'; ?>">
                        <?php
                        $amount = $transaction['amount'];
                        if (is_numeric($amount)) {
                            $sign = $transaction['type'] === 'in' ? '+' : '-';
                            echo $sign . " " . number_format((float)$amount, 2);
                        } else {
                            echo "Invalid Amount";
                        }
                        ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>

    <!-- Footer section showing totals -->
<tfoot style="background-color: #f2f2f2;">
        <?php
        $total_in = 0;
        $total_out = 0;
        foreach ($transactions as $t) {
            if ($t['type'] === 'in' && is_numeric($t['amount'])) {
                $total_in += $t['amount'];
            } elseif ($t['type'] === 'out' && is_numeric($t['amount'])) {
                $total_out += $t['amount'];
            }
        }
        $net = $total_in - $total_out;
        ?>
        <tr>
            <td colspan="3" class="text-end"><strong>Total Incoming</strong></td>
            <td class="amount-in"><strong><?php echo "+ " . number_format($total_in, 2); ?></strong></td>
        </tr>
        <tr>
            <td colspan="3" class="text-end"><strong>Total Outgoing</strong></td>
            <td class="amount-out"><strong><?php echo "- " . number_format($total_out, 2); ?></strong></td>
        </tr>
        <tr>
            <td colspan="3" class="text-end"><strong>Net Balance</strong></td>
            <td>
                <strong>
                    <?php
                    $netSign = $net >= 0 ? '+' : '-';
                    echo $netSign . " " . number_format(abs($net), 2);
                    ?>
                </strong>
            </td>
        </tr>
    </tfoot>
</table>

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