<?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Include database connection
include '../config/db.php';

// Fetch all sales from the database
$stmt = $pdo->prepare("SELECT * FROM sales ORDER BY sale_date DESC");
$stmt->execute();
$sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total sales amount and total profit
$total_sales_amount = 0;
$total_profit = 0;
$total_discount = 0; // Initialize total discount
foreach ($sales as $sale) {
    $total_sales_amount += $sale['total'];
    $total_profit += $sale['profit'];
    $total_discount += $sale['discount']; // Sum discounts
}

// Variable to check if filters are applied
$isFiltered = false; // Update this variable based on your filter logic later

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View All Sales - Pharmacy Management System</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f0f2f5;
        }
        .sales-container {
            margin-top: 50px;
        }
        .table thead th {
            background-color: #343a40;
            color: white;
        }
        .view-sales-header {
            text-align: center;
            margin-bottom: 30px;
            color: #343a40;
            font-weight: bold;
        }
        .sales-summary {
            margin-top: 20px;
            padding: 15px;
            background-color: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        .filter-indicator {
            font-weight: bold;
            color: #dc3545; /* Red color for visibility */
        }
        .back-btn {
            margin-bottom: 20px;
        }
        .filter-form {
            margin-bottom: 20px;
        }
        .filter-btn-group button {
            margin-right: 10px;
            margin-bottom: 5px; /* Add margin for mobile devices */
        }
        .filter-label {
            font-weight: bold;
            color: #343a40;
        }

        /* Custom CSS for sidebar and content */
        body {
            display: flex;
        }

        /* Sidebar styling */
        .sidebar {
            width: 250px; /* Adjust width as needed */
            position: absolute;
            height: 100%;
            background-color: #343a40;
        }

        .sidebar a {
            color: #fff;
            padding: 10px;
            display: block;
        }

        /* Content styling */
        .content {
            margin-left: 250px; /* Same width as the sidebar */
            width: calc(100% - 250px); /* Ensure content takes remaining space */
        }

    </style>
</head>
<body>
    <div class="sidebar">
        <?php include('../includes/side_bar.php'); ?>
    </div>
    <div class="content">
        <div class="container sales-container">
            <div class="back-btn">
                <a href="admin_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            </div>
            <h2 class="view-sales-header">All Sales Records</h2>

            <!-- Display Total Sales Amount, Total Profit, and Total Discount -->
            <div class="sales-summary">
                <h5>Total Sales Amount: ₦<span id="totalSalesAmount"><?php echo number_format($total_sales_amount, 2); ?></span></h5>
                <h5>Total Profit: ₦<span id="totalProfit"><?php echo number_format($total_profit, 2); ?></span></h5>
                <h5>Total Discount: ₦<span id="totalDiscount"><?php echo number_format($total_discount, 2); ?></span></h5>
                <?php if ($isFiltered): ?>
                    <p class="filter-indicator">Filters are applied. Displaying filtered results.</p>
                <?php endif; ?>
            </div>

            <!-- Filter Form -->
            <div class="filter-form">
                <input type="text" id="searchInput" class="form-control" placeholder="Search by any field..." style="margin-bottom: 10px;">
                <div class="filter-btn-group text-right">
                    <button class="btn btn-outline-primary" id="dailyFilter">Daily</button>
                    <button class="btn btn-outline-primary" id="weeklyFilter">Weekly</button>
                    <button class="btn btn-outline-primary" id="monthlyFilter">Monthly</button>
                    <button class="btn btn-outline-primary" id="yearlyFilter">Yearly</button>
                    <button class="btn btn-outline-primary" id="customFilter">Custom Range</button>
                    <button class="btn btn-outline-danger" id="clearFilter">Clear Filter</button>
                </div>

                <!-- Custom Date Range Fields -->
                <div class="row mb-3" id="customDateRange" style="display: none;">
                    <div class="col-6">
                        <input type="date" id="startDate" class="form-control" placeholder="Start Date">
                    </div>
                    <div class="col-6">
                        <input type="date" id="endDate" class="form-control" placeholder="End Date">
                    </div>
                    <div class="col-12">
                        <button class="btn btn-outline-primary" id="applyDateRange">Apply Range</button>
                    </div>
                </div>
            </div>

            <?php if ($sales): ?>
                <table class="table table-bordered table-hover" id="salesTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Receipt Number</th>
                            <th>Username</th>
                            <th>Drug Name</th>
                            <th>Quantity</th>
                            <th>Discount (₦)</th> <!-- New column for Discount -->
                            <th>Total Amount (₦)</th>
                            <th>Profit (₦)</th>
                            <th>Payment Method</th>
                            <th>Sale Type</th> <!-- New column for Sale Type -->
                            <th>Sale Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($sales as $index => $sale): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($sale['receipt']); ?></td>
                                <td><?php echo htmlspecialchars($sale['username']); ?></td>
                                <td><?php echo htmlspecialchars($sale['drug_name']); ?></td>
                                <td><?php echo htmlspecialchars($sale['quantity']); ?></td>
                                <td class="discountAmount">₦<?php echo htmlspecialchars(number_format($sale['discount'], 2)); ?></td> <!-- Display Discount -->
                                <td class="totalAmount">₦<?php echo htmlspecialchars(number_format($sale['total'], 2)); ?></td>
                                <td class="profitAmount">₦<?php echo htmlspecialchars(number_format($sale['profit'], 2)); ?></td>
                                <td><?php echo htmlspecialchars($sale['payment_method']); ?></td>
                                <td><?php echo htmlspecialchars($sale['sale_type']); ?></td> <!-- Display Sale Type -->
                                <td><?php echo htmlspecialchars(date('Y-m-d H:i:s', strtotime($sale['sale_date']))); ?></td>
                                <td>
                                    <a href="receipt.php?receipt_no=<?php echo $sale['receipt']; ?>" class="btn btn-sm btn-primary">View Receipt</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p>No sales records found.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add filtering and searching functionality -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
        var isFiltered = false; // Track if filters are applied

        // Filter by search input
        $("#searchInput").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            $("#salesTable tbody tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
            });
            isFiltered = true; // Set filtered status
            recalculateTotals(); // Recalculate totals based on filtered rows
            updateFilterIndicator(); // Update filter indicator
        });

        // Predefined filters
        $("#dailyFilter").click(function() {
            filterByDateRange("daily");
        });
        $("#weeklyFilter").click(function() {
            filterByDateRange("weekly");
        });
        $("#monthlyFilter").click(function() {
            filterByDateRange("monthly");
        });
        $("#yearlyFilter").click(function() {
            filterByDateRange("yearly");
        });

        // Show custom date range filter
        $("#customFilter").click(function() {
            $("#customDateRange").toggle();
        });

        // Filter by custom date range
        $("#applyDateRange").click(function() {
            var startDate = new Date($("#startDate").val());
            var endDate = new Date($("#endDate").val());

            // Ensure valid dates
            if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
                alert("Please select valid start and end dates.");
                return; // If either date is invalid, do not filter
            }

            // Normalize endDate to include the entire end date
            endDate.setHours(23, 59, 59, 999); // Set to the end of the day

            $("#salesTable tbody tr").filter(function() {
                var saleDate = new Date($(this).find("td:nth-child(10)").text());
                $(this).toggle(saleDate >= startDate && saleDate <= endDate);
            });
            isFiltered = true; // Set filtered status
            recalculateTotals(); // Recalculate totals based on filtered rows
            updateFilterIndicator(); // Update filter indicator
        });

        // Clear filters
        $("#clearFilter").click(function() {
            $("#searchInput").val(""); // Clear search input
            $("#salesTable tbody tr").show(); // Show all rows
            isFiltered = false; // Reset filtered status
            recalculateTotals(); // Recalculate totals based on all rows
            updateFilterIndicator(); // Update filter indicator
        });

        // Function to recalculate totals
        function recalculateTotals() {
                var totalAmount = 0;
                var totalProfit = 0;
                var totalDiscount = 0; // Initialize total discount

                $("#salesTable tbody tr:visible").each(function() {
                    totalAmount += parseFloat($(this).find(".totalAmount").text().replace(/₦|,/g, ""));
                    totalProfit += parseFloat($(this).find(".profitAmount").text().replace(/₦|,/g, ""));
                    totalDiscount += parseFloat($(this).find(".discountAmount").text().replace(/₦|,/g, ""));
                });

                // Update totals on the page
                $("#totalSalesAmount").text(totalAmount.toFixed(2));
                $("#totalProfit").text(totalProfit.toFixed(2));
                $("#totalDiscount").text(totalDiscount.toFixed(2)); // Display total discount
            }

        // Function to update filter indicator
        function updateFilterIndicator() {
            if (isFiltered) {
                $(".filter-indicator").show();
            } else {
                $(".filter-indicator").hide();
            }
        }

        // Function to filter sales by date range
        function filterByDateRange(range) {
            // Logic to filter sales by specific range
            var now = new Date();
            var startDate, endDate;

            switch (range) {
                case "daily":
                    startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                    endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
                    break;
                case "weekly":
                    var dayOfWeek = now.getDay();
                    startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - dayOfWeek);
                    endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - dayOfWeek) + 1);
                    break;
                case "monthly":
                    startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                    endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
                    break;
                case "yearly":
                    startDate = new Date(now.getFullYear(), 0, 1);
                    endDate = new Date(now.getFullYear() + 1, 0, 1);
                    break;
                default:
                    return;
            }

            $("#salesTable tbody tr").filter(function() {
                var saleDate = new Date($(this).find("td:nth-child(10)").text());
                $(this).toggle(saleDate >= startDate && saleDate < endDate);
            });
            isFiltered = true; // Set filtered status
            recalculateTotals(); // Recalculate totals based on filtered rows
            updateFilterIndicator(); // Update filter indicator
        }
    });
    </script>
</body>
</html>
