<?php
session_start();

// Redirect to login page if the user is not an admin
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Include database connection
include '../config/db.php';
$results = [];
$searchTerm = '';
$orderBy = 'total_spent DESC'; // Default sorting by total_spent

// Check if a search term is provided and sanitize it
if (isset($_GET['search'])) {
    $searchTerm = "%" . $_GET['search'] . "%";
}

// Check if a sort order is selected
if (isset($_GET['sort'])) {
    $sort = $_GET['sort'];
    if ($sort == 'name_asc') {
        $orderBy = 'c.full_name ASC';
    } elseif ($sort == 'name_desc') {
        $orderBy = 'c.full_name DESC';
    } elseif ($sort == 'amount_asc') {
        $orderBy = 'total_spent ASC';
    } elseif ($sort == 'amount_desc') {
        $orderBy = 'total_spent DESC';
    }
}

// Base query to fetch top 5 customers sorted by highest total spent with optional search filter (doesn't affect top 5)
$queryTop5 = "SELECT c.id, c.full_name, c.email, c.phone_number, 
                     SUM(s.total) AS total_spent 
              FROM customers c 
              LEFT JOIN sales s ON c.id = s.customer_id 
              GROUP BY c.id
              ORDER BY total_spent DESC
              LIMIT 5";  // Limit to top 5 customers

// Prepare and execute the query for top 5 customers
$stmt = $pdo->prepare($queryTop5);
$stmt->execute();
$top5Customers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Base query to fetch all customers sorted by total amount spent with search term (applies to all customers)
$queryAll = "SELECT c.id, c.full_name, c.email, c.phone_number, 
                     SUM(s.total) AS total_spent 
              FROM customers c 
              LEFT JOIN sales s ON c.id = s.customer_id 
              WHERE c.full_name LIKE :searchTerm 
                 OR c.email LIKE :searchTerm 
                 OR c.phone_number LIKE :searchTerm
              GROUP BY c.id
              ORDER BY  $orderBy"; // Sort by chosen order

// Prepare and execute the query for all customers
$stmt = $pdo->prepare($queryAll);
$stmt->execute(['searchTerm' => $searchTerm]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch pharmacy name from the settings table
$query = "SELECT pharmacy_name FROM settings LIMIT 1"; // Assuming only one entry
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name'; // Fallback to a default if not found
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Report - Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    
    <style>
        body {
            background-color: #f5f6fa;
            font-family: 'Mulish', sans-serif;
            overflow-x: hidden;
        }

        .content {
            margin-left: 240px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
            backdrop-filter: blur(10px);
        }

        .report-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .search-filters {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }

        .table thead th {
            background-color: #2c3e50;
            color: white;
            font-weight: 500;
            border: none;
        }

        .top-customers {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .currency-format {
            font-family: 'Consolas', monospace;
            font-weight: 500;
        }

        .btn-view {
            background: linear-gradient(135deg, #3498db, #2980b9);
            border: none;
            color: white;
            padding: 5px 15px;
            border-radius: 5px;
            transition: all 0.3s ease;
        }

        .btn-view:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
            
            .search-filters {
                flex-direction: column;
            }
            
            .search-filters > * {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <?php include '../includes/side_bar.php'; ?>

    <div class="content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Customer Reports</h4>
                <a href="admin_dashboard.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>

        <!-- Search and Filters -->
        <div class="report-card">
            <div class="search-filters">
                <div class="flex-grow-1">
                    <form method="GET" class="d-flex gap-2">
                        <input type="text" name="search" class="form-control" 
                               placeholder="Search by Name, Email, or Phone" 
                               value="<?= htmlspecialchars($searchTerm) ?>">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> Search
                        </button>
                    </form>
                </div>
                <div class="d-flex gap-2">
                    <select name="sort" class="form-select" onchange="this.form.submit()">
                        <option value="amount_desc" <?= ($orderBy == 'total_spent DESC') ? 'selected' : '' ?>>Amount (High to Low)</option>
                        <option value="amount_asc" <?= ($orderBy == 'total_spent ASC') ? 'selected' : '' ?>>Amount (Low to High)</option>
                        <option value="name_asc" <?= ($orderBy == 'c.full_name ASC') ? 'selected' : '' ?>>Name (A-Z)</option>
                        <option value="name_desc" <?= ($orderBy == 'c.full_name DESC') ? 'selected' : '' ?>>Name (Z-A)</option>
                    </select>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-times"></i> Clear
                    </button>
                </div>
            </div>
        </div>

        <!-- Top 5 Customers -->
        <div class="top-customers">
            <h5 class="mb-4"><i class="fas fa-crown"></i> Top 5 Customers</h5>
            <div class="table-responsive">
                <table class="table table-hover text-white">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Phone Number</th>
                            <th class="text-end">Total Spent</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($top5Customers as $customer): ?>
                            <tr>
                                <td><?= htmlspecialchars($customer['full_name']) ?></td>
                                <td><?= htmlspecialchars($customer['phone_number']) ?></td>
                                <td class="text-end currency-format">
                                    ₦<?= number_format($customer['total_spent'], 2) ?>
                                </td>
                                <td>
                                    <a href="view_customer_purchases.php?customer_id=<?= $customer['id'] ?>" 
                                       class="btn-view">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- All Customers Table -->
        <div class="report-card">
            <h5 class="mb-4"><i class="fas fa-users"></i> All Customers</h5>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Phone Number</th>
                            <th>Total Amount Spent</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($results)): ?>
                            <?php foreach ($results as $customer): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($customer['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($customer['phone_number']); ?></td>
                                    <td class="currency-format">
                                        <?php echo 'NGN ' . number_format($customer['total_spent'], 2); ?>
                                    </td>
                                    <td>
                                        <a href="view_customer_purchases.php?customer_id=<?php echo $customer['id']; ?>" class="btn btn-primary">View</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5">No records found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.querySelector('.sidebar').classList.toggle('active');
            document.querySelector('.content').classList.toggle('sidebar-active');
        }
    </script>
</body>
</html>
