<?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';

// Get the customer ID from the URL parameter
$customer_id = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;

// Initialize filter variables
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Build the SQL query based on the selected filter
$whereClause = "WHERE s.customer_id = :customer_id";
$params = ['customer_id' => $customer_id];

if ($filter === 'daily') {
    $whereClause .= " AND DATE(s.sale_date) = CURDATE()";
} elseif ($filter === 'weekly') {
    $whereClause .= " AND YEARWEEK(s.sale_date, 1) = YEARWEEK(CURDATE(), 1)";
} elseif ($filter === 'monthly') {
    $whereClause .= " AND MONTH(s.sale_date) = MONTH(CURDATE()) AND YEAR(s.sale_date) = YEAR(CURDATE())";
} elseif ($filter === 'yearly') {
    $whereClause .= " AND YEAR(s.sale_date) = YEAR(CURDATE())";
} elseif ($filter === 'custom' && $start_date && $end_date) {
    $whereClause .= " AND DATE(s.sale_date) BETWEEN :start_date AND :end_date";
    $params['start_date'] = $start_date;
    $params['end_date'] = $end_date;
}

// Fetch customer purchases grouped by sale date
$query = "SELECT s.id, s.drug_name, s.quantity, s.total, s.sale_date 
          FROM sales s 
          $whereClause
          ORDER BY s.sale_date DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch customer details
$query = "SELECT full_name FROM customers WHERE id = :customer_id LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute(['customer_id' => $customer_id]);
$customer = $stmt->fetch(PDO::FETCH_ASSOC);

// Group purchases by sale date and calculate total amount
$groupedPurchases = [];
$totalAmount = 0;

foreach ($purchases as $purchase) {
    $saleDate = $purchase['sale_date'];
    if (!isset($groupedPurchases[$saleDate])) {
        $groupedPurchases[$saleDate] = [];
    }
    $groupedPurchases[$saleDate][] = $purchase;
    $totalAmount += $purchase['total'];
}
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Purchases - 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;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

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

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

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

        .purchase-date {
            background: #2c3e50;
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            margin: 15px 0;
            font-weight: 500;
        }

        .table {
            margin-bottom: 0;
        }

        .table thead th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
        }

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

        @media print {
            body {
                background: white;
                padding: 0;
            }
            .no-print {
                display: none;
            }
            .purchase-card {
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Top Bar -->
        <div class="top-bar no-print">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Customer Purchase History</h4>
                <div class="d-flex gap-2">
                    <button onclick="window.print()" class="btn btn-primary">
                        <i class="fas fa-print"></i> Print
                    </button>
                    <a href="customers_report.php" class="btn btn-outline-primary">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                </div>
            </div>
        </div>

        <!-- Customer Summary -->
        <div class="summary-card">
            <div class="row">
                <div class="col-md-6">
                    <h5>Customer Details</h5>
                    <p class="mb-1">
                        <strong><?= htmlspecialchars($customer['full_name']) ?></strong>
                    </p>
                </div>
                <div class="col-md-6 text-md-end">
                    <h5>Total Purchases</h5>
                    <h3 class="currency">₦<?= number_format($totalAmount, 2) ?></h3>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="filter-card no-print">
            <form method="GET" class="row g-3">
                <input type="hidden" name="customer_id" value="<?= $customer_id ?>">
                <div class="col-md-4">
                    <label class="form-label">Filter By</label>
                    <select name="filter" class="form-select" onchange="toggleDateRange(this.value)">
                        <option value="all" <?= ($filter === 'all') ? 'selected' : '' ?>>All Time</option>
                        <option value="daily" <?= ($filter === 'daily') ? 'selected' : '' ?>>Today</option>
                        <option value="weekly" <?= ($filter === 'weekly') ? 'selected' : '' ?>>This Week</option>
                        <option value="monthly" <?= ($filter === 'monthly') ? 'selected' : '' ?>>This Month</option>
                        <option value="yearly" <?= ($filter === 'yearly') ? 'selected' : '' ?>>This Year</option>
                        <option value="custom" <?= ($filter === 'custom') ? 'selected' : '' ?>>Custom Range</option>
                    </select>
                </div>
                <div class="col-md-3 custom-date" style="display: <?= ($filter === 'custom') ? 'block' : 'none' ?>">
                    <label class="form-label">Start Date</label>
                    <input type="date" name="start_date" class="form-control" value="<?= htmlspecialchars($start_date) ?>">
                </div>
                <div class="col-md-3 custom-date" style="display: <?= ($filter === 'custom') ? 'block' : 'none' ?>">
                    <label class="form-label">End Date</label>
                    <input type="date" name="end_date" class="form-control" value="<?= htmlspecialchars($end_date) ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Apply
                    </button>
                </div>
            </form>
        </div>

        <!-- Purchases List -->
        <?php if (!empty($groupedPurchases)): ?>
            <?php foreach ($groupedPurchases as $saleDate => $purchasesByDate): ?>
                <div class="purchase-card">
                    <div class="purchase-date">
                        <i class="fas fa-calendar"></i> 
                        <?= date('F j, Y', strtotime($saleDate)) ?>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Drug Name</th>
                                    <th class="text-center">Quantity</th>
                                    <th class="text-end">Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($purchasesByDate as $purchase): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($purchase['drug_name']) ?></td>
                                        <td class="text-center"><?= htmlspecialchars($purchase['quantity']) ?></td>
                                        <td class="text-end currency">₦<?= number_format($purchase['total'], 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="purchase-card">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                    <p>No purchases found for this customer.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
        function toggleDateRange(value) {
            const customDateInputs = document.querySelectorAll('.custom-date');
            customDateInputs.forEach(input => {
                input.style.display = value === 'custom' ? 'block' : 'none';
            });
        }
    </script>
</body>
</html>
