<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("../db/cn.php");
ob_start();
$conn = $connection;
// Check session
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName       = $_SESSION['user_name'];
    $userRole       = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name    = $_SESSION['outlet_name'];
} else {
    echo "Session variables not set. Please log in.";
    exit;
}

// Fetch distinct customer names from credit_note for dropdown
$customers_query = "SELECT DISTINCT cr_name FROM credit_note ORDER BY cr_name";
$customers_result = mysqli_query($conn, $customers_query);

// Handle filter
$selected_customer = isset($_POST['customer_name']) ? $_POST['customer_name'] : '';

// Build query for creditor closing balances
if (!empty($selected_customer)) {
    $closing_query = "SELECT creditor_name, remain_balance FROM creditor_closing WHERE creditor_name = ? ORDER BY creditor_name";
    $stmt = mysqli_prepare($conn, $closing_query);
    mysqli_stmt_bind_param($stmt, "s", $selected_customer);
    mysqli_stmt_execute($stmt);
    $closing_result = mysqli_stmt_get_result($stmt);
} else {
    $closing_query = "SELECT creditor_name, remain_balance FROM creditor_closing ORDER BY creditor_name";
    $closing_result = mysqli_query($conn, $closing_query);
}

// Fetch all rows into an array to compute total
$rows = [];
if (isset($closing_result) && mysqli_num_rows($closing_result) > 0) {
    while ($row = mysqli_fetch_assoc($closing_result)) {
        $rows[] = $row;
    }
}
$total_balance = 0;
foreach ($rows as $r) {
    $total_balance += (float)$r['remain_balance'];
}

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Customer Closing</title>
    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<style>
    body {
        font-family: 'Quicksand', sans-serif;
    }
    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
    canvas {
        max-width: 100%;
        height: auto;
    }
    .bg-gradient-primary {
        background: #0A4657;
        color: #fff;
    }
    .btn-primary {
        background: #0A4657;
        color: #fff;
        border: 1px #0A4657 solid;
    }
    .btn-primary:hover {
        background: #fff;
        border: 1px #0A4657 solid;
        color: #0A4657;
    }
    .chart-container {
        position: relative;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        padding: 15px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
    canvas {
        max-width: 100%;
        height: auto;
    }
    .fa-download:hover {
        color: #953E39;
    }
    .form-control, option {
        font-weight: 700;
        color: #000;
    }
</style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-sm-9">
                            <h3 style="color:#212529; font-weight:700;">Customer Closing Report</h3>
                        </div>
                        <div class="col-sm-3"></div>
                    </div>
                </div>

                <!-- Filter & Table Section -->
                <div class="container-fluid">
                    <!-- Filter Form -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Filter by Customer</h6>
                        </div>
                        <div class="card-body">
                            <form method="post" action="">
                                <div class="form-row align-items-end">
                                    <div class="col-md-4 mb-3">
                                        <label for="customer_name">Select Customer</label>
                                        <select class="form-control" id="customer_name" name="customer_name">
                                            <option value="">-- All Customers --</option>
                                            <?php
                                            if ($customers_result && mysqli_num_rows($customers_result) > 0) {
                                                while ($row = mysqli_fetch_assoc($customers_result)) {
                                                    $selected = ($row['cr_name'] == $selected_customer) ? 'selected' : '';
                                                    echo '<option value="' . htmlspecialchars($row['cr_name']) . '" ' . $selected . '>' . htmlspecialchars($row['cr_name']) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <button type="submit" class="btn btn-primary btn-block">Filter</button>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <a href="?" class="btn btn-secondary btn-block">Refresh</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Data Table -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Customer Closing Balances</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Customer Name</th>
                                            <th>Closing Balance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        if (!empty($rows)) {
                                            $counter = 1;
                                            foreach ($rows as $row) {
                                                echo '<tr>';
                                                echo '<td>' . $counter++ . '</td>';
                                                echo '<td>' . htmlspecialchars($row['creditor_name']) . '</td>';
                                                echo '<td>' . number_format((float)$row['remain_balance'], 2) . '</td>';
                                                echo '</tr>';
                                            }
                                        } else {
                                            echo '<tr><td colspan="3" class="text-center">No records found.</td></tr>';
                                        }
                                        ?>
                                    </tbody>
                                    <tfoot>
                                        <tr style="font-weight: bold; background-color: #f8f9fa;">
                                            <td colspan="2" class="text-right">Total Closing Balance:</td>
                                            <td><?php echo number_format($total_balance, 2); ?></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var sidebar = document.getElementById("sidebar");
            var overlay = document.createElement("div");
            overlay.classList.add("overlay");
            document.body.appendChild(overlay);

            function toggleSidebar() {
                sidebar.classList.toggle("hide");
                overlay.classList.toggle("hide");
                var mainContent = document.querySelector(".main-content");
                if (sidebar.classList.contains("hide")) {
                    mainContent.style.marginLeft = "0";
                } else {
                    mainContent.style.marginLeft = "100px";
                }
            }

            overlay.addEventListener("click", function () {
                toggleSidebar();
            });

            var navbarToggler = document.querySelector(".navbar-toggler");
            navbarToggler.addEventListener("click", function () {
                toggleSidebar();
            });

            function checkScreenSize() {
                if (window.innerWidth > 768) {
                    sidebar.classList.remove("hide");
                    overlay.classList.remove("hide");
                } else {
                    sidebar.classList.add("hide");
                    overlay.classList.add("hide");
                }
            }
            checkScreenSize();
            window.addEventListener("resize", checkScreenSize);
        });

        function toggleSubMenu(element) {
            $(element).next('.sub-menu').slideToggle();
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>