<?php
require_once 'auth.php';
require_once '../config/database.php';
check_admin_login();

if (isset($_GET['approve'])) {
    $stmt = $pdo->prepare("UPDATE hall_reservations SET status = 'approved' WHERE id = ?");
    $stmt->execute([$_GET['approve']]);
    header("Location: reservations.php");
    exit;
}

if (isset($_GET['reject'])) {
    $stmt = $pdo->prepare("UPDATE hall_reservations SET status = 'rejected' WHERE id = ?");
    $stmt->execute([$_GET['reject']]);
    header("Location: reservations.php");
    exit;
}

if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM hall_reservations WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header("Location: reservations.php");
    exit;
}

$reservations = $pdo->query("SELECT * FROM hall_reservations ORDER BY created_at DESC")->fetchAll();

$events = [];
foreach($reservations as $r) {
    $color = '#eab308'; // yellow for pending
    if ($r['status'] == 'approved') $color = '#22c55e'; // green
    if ($r['status'] == 'rejected') $color = '#dc2626'; // red
    
    // +1 day for FullCalendar exclusive end date display
    $end_date = date('Y-m-d', strtotime($r['end_date'] . ' +1 day'));
    
    $events[] = [
        'title' => $r['hall_name'] . ' (' . $r['user_name'] . ')',
        'start' => $r['start_date'],
        'end' => $end_date,
        'color' => $color,
        'allDay' => true
    ];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Réservations de Salles - Admin</title>
    <script src="../js/tailwind.min.js"></script>
    <script src="../js/lucide.min.js"></script>
    <script src='../js/fullcalendar.min.js'></script>
    <script src='../js/fullcalendar-fr.min.js'></script>
    <style>
        .fc-theme-standard td, .fc-theme-standard th { border-color: #e5e7eb; }
        .fc-col-header-cell-cushion { padding: 8px !important; color: #374151; font-weight: bold; text-decoration: none !important; }
        .fc-daygrid-day-number { color: #4b5563; text-decoration: none !important; padding: 4px !important; }
        .fc-event { border-radius: 4px; border: none; padding: 2px 4px; cursor: pointer; }
    </style>
</head>
<body class="bg-gray-50 flex h-screen font-sans text-gray-800">
    <?php include 'includes/sidebar.php'; ?>
    <main class="flex-1 flex flex-col h-screen overflow-hidden">
        <header class="h-20 bg-white shadow-sm flex items-center justify-between px-8 flex-shrink-0">
            <h1 class="text-2xl font-bold text-gray-800">Gestion des Réservations de Salles</h1>
        </header>

        <div class="flex-1 overflow-auto p-8 space-y-8">
            
            <!-- Calendrier -->
            <div class="bg-white rounded-xl shadow p-6">
                <h2 class="text-xl font-bold mb-4 flex items-center"><i data-lucide="calendar-days" class="w-6 h-6 mr-2 text-gray-600"></i> Planning des réservations</h2>
                <div class="flex items-center space-x-4 mb-4 text-sm font-medium">
                    <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-green-500 mr-2"></span> Approuvées</span>
                    <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-yellow-500 mr-2"></span> En attente</span>
                    <span class="flex items-center"><span class="w-3 h-3 rounded-full bg-red-600 mr-2"></span> Refusées</span>
                </div>
                <div id='calendar' class="max-h-[600px]"></div>
            </div>

            <!-- Liste Table -->
            <div class="bg-white rounded-xl shadow p-6">
                <h2 class="text-xl font-bold mb-4 flex items-center"><i data-lucide="list" class="w-6 h-6 mr-2 text-gray-600"></i> Historique et traitement</h2>
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="border-b bg-gray-50"><th class="p-3">Salle & Option</th><th class="p-3">Dates</th><th class="p-3">Demandeur</th><th class="p-3">Statut</th><th class="p-3">Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($reservations as $r): ?>
                        <tr class="border-b hover:bg-gray-50">
                            <td class="p-3 font-medium">
                                <?php echo htmlspecialchars($r['hall_name']); ?><br>
                                <span class="text-xs text-gray-500"><?php echo htmlspecialchars($r['booking_option']); ?></span>
                            </td>
                            <td class="p-3">
                                <?php echo date('d/m/Y', strtotime($r['start_date'])); ?> au <br><?php echo date('d/m/Y', strtotime($r['end_date'])); ?>
                            </td>
                            <td class="p-3">
                                <?php echo htmlspecialchars($r['user_name']); ?><br>
                                <span class="text-xs text-gray-500"><?php echo htmlspecialchars($r['user_phone']); ?></span>
                            </td>
                            <td class="p-3">
                                <?php if($r['status'] == 'approved'): ?>
                                    <span class="px-2 py-1 bg-green-100 text-green-800 rounded text-xs font-bold">Approuvée</span>
                                <?php elseif($r['status'] == 'rejected'): ?>
                                    <span class="px-2 py-1 bg-red-100 text-red-800 rounded text-xs font-bold">Refusée</span>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs font-bold">En attente</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3 space-x-2">
                                <?php if($r['status'] == 'pending'): ?>
                                    <a href="?approve=<?php echo $r['id']; ?>" class="text-green-600 hover:underline text-sm font-bold">Approuver</a> | 
                                    <a href="?reject=<?php echo $r['id']; ?>" class="text-yellow-600 hover:underline text-sm font-bold">Refuser</a> | 
                                <?php endif; ?>
                                <a href="?delete=<?php echo $r['id']; ?>" onclick="return confirm('Êtes-vous sûr de vouloir supprimer cette réservation ?');" class="text-red-600 hover:underline text-sm font-bold">Supprimer</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($reservations)): ?>
                            <tr><td colspan="5" class="p-4 text-center text-gray-500">Aucune demande de réservation.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
    <script>
        lucide.createIcons();
        document.addEventListener('DOMContentLoaded', function() {
            var calendarEl = document.getElementById('calendar');
            var calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'dayGridMonth',
                locale: 'fr',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,dayGridWeek'
                },
                events: <?php echo json_encode($events); ?>,
                eventDisplay: 'block'
            });
            calendar.render();
        });
    </script>
</body>
</html>
