<?php
$pageTitle = $pageTitle ?? 'Notifications - Gestion des Chambres';
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - StayManager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="<?= getBaseUrl() ?>/assets/css/dashboard.css" rel="stylesheet">
    <style>
        /* Styles pour les indicateurs clignotants */
        .blinking {
            animation: blink 1s infinite;
        }
        
        .blinking-fast {
            animation: blink 0.5s infinite;
        }
        
        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.3; }
        }
        
        .notification-card {
            transition: all 0.3s ease;
            border-left: 4px solid;
        }
        
        .notification-card.urgent {
            border-left-color: #dc3545;
            background-color: #f8d7da;
        }
        
        .notification-card.high {
            border-left-color: #fd7e14;
            background-color: #fff3cd;
        }
        
        .notification-card.medium {
            border-left-color: #ffc107;
            background-color: #fffbf0;
        }
        
        .notification-card.low {
            border-left-color: #28a745;
            background-color: #d4edda;
        }
        
        .room-status-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .room-status-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        
        .status-libre { background-color: #28a745; }
        .status-occupée { background-color: #007bff; }
        .status-à-nettoyer { background-color: #ffc107; animation: blink 1s infinite; }
        .status-à-occuper { background-color: #17a2b8; }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .auto-refresh {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../../includes/header_dynamic.php'; ?>

    <div class="container-fluid">
        <!-- En-tête de la page -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="page-title">
                        <i class="fas fa-bell text-primary"></i>
                        <?= $pageTitle ?>
                    </h1>
                    <p class="page-subtitle text-muted">
                        Gestion des notifications de check-out et nettoyage des chambres
                    </p>
                </div>
                <div class="col-md-4 text-end">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshNotifications()">
                            <i class="fas fa-sync-alt me-1"></i>Actualiser
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="processCheckouts()">
                            <i class="fas fa-cogs me-1"></i>Traiter Check-outs
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-success" onclick="processRoomStatus()">
                            <i class="fas fa-sync-alt me-1"></i>Mettre à jour Statuts
                        </button>
                    </div>
                    <a href="dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Retour au tableau de bord
                    </a>
                </div>
            </div>
        </div>

        <!-- Indicateur de rafraîchissement automatique -->
        <div class="auto-refresh">
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-sync-alt me-1"></i>
                <span id="refresh-status">Rafraîchissement automatique activé</span>
                <button type="button" class="btn-close" onclick="toggleAutoRefresh()"></button>
            </div>
        </div>

        <!-- Statistiques générales -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="card-title">Notifications Actives</h6>
                                <h3 class="mb-0" id="total-notifications"><?= $stats['total_notifications'] ?? 0 ?></h3>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-bell fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="card-title">Check-outs en Attente</h6>
                                <h3 class="mb-0 blinking" id="checkout-pending"><?= $stats['checkout_pending'] ?? 0 ?></h3>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-door-open fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="card-title">Nettoyage Requis</h6>
                                <h3 class="mb-0 blinking" id="cleaning-required"><?= $stats['cleaning_required'] ?? 0 ?></h3>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-broom fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6 class="card-title">Urgent</h6>
                                <h3 class="mb-0 blinking-fast" id="urgent-count"><?= $stats['urgent_count'] ?? 0 ?></h3>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-exclamation-triangle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Notifications actives -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>Notifications Actives
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="notifications-list">
                            <?php foreach ($notifications as $notification): ?>
                            <div class="notification-card <?= $notification['priority'] ?> mb-3 p-3 rounded">
                                <div class="row align-items-center">
                                    <div class="col-md-1">
                                        <span class="status-indicator status-<?= str_replace(' ', '-', strtolower($notification['notification_type'])) ?>"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Chambre <?= htmlspecialchars($notification['room_number']) ?></strong>
                                        <?php if ($notification['floor']): ?>
                                        <br><small class="text-muted">Étage <?= $notification['floor'] ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-3">
                                        <span class="badge bg-<?= $notification['priority'] === 'urgent' ? 'danger' : ($notification['priority'] === 'high' ? 'warning' : 'info') ?>">
                                            <?= ucfirst($notification['priority']) ?>
                                        </span>
                                        <br><small class="text-muted"><?= ucfirst(str_replace('_', ' ', $notification['notification_type'])) ?></small>
                                    </div>
                                    <div class="col-md-3">
                                        <?php if ($notification['reservation_number']): ?>
                                        <strong><?= htmlspecialchars($notification['reservation_number']) ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($notification['client_first_name'] . ' ' . $notification['client_last_name']) ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-2 text-end">
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-success" onclick="acknowledgeNotification(<?= $notification['id'] ?>)">
                                                <i class="fas fa-check"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-primary" onclick="completeNotification(<?= $notification['id'] ?>)">
                                                <i class="fas fa-flag-checkered"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-12">
                                        <small class="text-muted">
                                            <i class="fas fa-clock me-1"></i>
                                            Créé le <?= date('d/m/Y H:i', strtotime($notification['created_at'])) ?>
                                        </small>
                                        <p class="mb-0 mt-1"><?= htmlspecialchars($notification['message']) ?></p>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- État des chambres -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-bed me-2"></i>État des Chambres
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row" id="rooms-grid">
                            <?php foreach ($roomsByStatus as $room): ?>
                            <div class="col-md-3 mb-3">
                                <div class="card room-status-card" onclick="showRoomDetails(<?= $room['id'] ?>)">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title mb-1">
                                                    <span class="status-indicator status-<?= str_replace(' ', '-', strtolower($room['computed_status'])) ?>"></span>
                                                    Chambre <?= htmlspecialchars($room['room_number']) ?>
                                                </h6>
                                                <small class="text-muted">Étage <?= $room['floor'] ?? 'N/A' ?></small>
                                            </div>
                                            <div class="text-end">
                                                <?php
                                                $roomStatus = $room['room_status'];
                                                $statusClass = '';
                                                $statusText = '';
                                                
                                                switch ($roomStatus) {
                                                    case 'available':
                                                        $statusClass = 'bg-success';
                                                        $statusText = 'Libre';
                                                        break;
                                                    case 'occupied':
                                                        $statusClass = 'bg-primary';
                                                        $statusText = 'Occupée';
                                                        break;
                                                    case 'reserved':
                                                        $statusClass = 'bg-info';
                                                        $statusText = 'Réservée';
                                                        break;
                                                    case 'checkout':
                                                        $statusClass = 'bg-warning blinking';
                                                        $statusText = 'À nettoyer';
                                                        break;
                                                    case 'maintenance':
                                                        $statusClass = 'bg-danger';
                                                        $statusText = 'Maintenance';
                                                        break;
                                                    default:
                                                        $statusClass = 'bg-secondary';
                                                        $statusText = ucfirst($roomStatus);
                                                }
                                                ?>
                                                <span class="badge <?= $statusClass ?>">
                                                    <?= $statusText ?>
                                                </span>
                                            </div>
                                        </div>
                                        <?php if ($room['reservation_number']): ?>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                <i class="fas fa-calendar me-1"></i>
                                                <?= htmlspecialchars($room['reservation_number']) ?>
                                            </small>
                                            <br>
                                            <small class="text-muted">
                                                <i class="fas fa-user me-1"></i>
                                                <?= htmlspecialchars($room['client_first_name'] . ' ' . $room['client_last_name']) ?>
                                            </small>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Boutons d'action -->
                                        <div class="mt-2">
                                            <div class="btn-group btn-group-sm w-100">
                                                <?php if ($roomStatus === 'checkout'): ?>
                                                <button type="button" class="btn btn-success btn-sm" onclick="markRoomAsCleaned(<?= $room['id'] ?>)">
                                                    <i class="fas fa-broom me-1"></i>Nettoyé
                                                </button>
                                                <?php elseif ($roomStatus === 'available'): ?>
                                                <button type="button" class="btn btn-warning btn-sm" onclick="setRoomMaintenance(<?= $room['id'] ?>)">
                                                    <i class="fas fa-tools me-1"></i>Maintenance
                                                </button>
                                                <?php elseif ($roomStatus === 'maintenance'): ?>
                                                <button type="button" class="btn btn-success btn-sm" onclick="setRoomAvailable(<?= $room['id'] ?>)">
                                                    <i class="fas fa-check me-1"></i>Libre
                                                </button>
                                                <?php endif; ?>
                                                
                                                <button type="button" class="btn btn-outline-info btn-sm" onclick="showRoomDetails(<?= $room['id'] ?>)">
                                                    <i class="fas fa-info me-1"></i>Détails
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let autoRefreshInterval;
        let isAutoRefreshEnabled = true;
        
        // Rafraîchissement automatique
        function startAutoRefresh() {
            if (autoRefreshInterval) clearInterval(autoRefreshInterval);
            
            autoRefreshInterval = setInterval(() => {
                refreshNotifications();
            }, 30000); // Rafraîchir toutes les 30 secondes
        }
        
        function toggleAutoRefresh() {
            isAutoRefreshEnabled = !isAutoRefreshEnabled;
            
            if (isAutoRefreshEnabled) {
                startAutoRefresh();
                document.getElementById('refresh-status').textContent = 'Rafraîchissement automatique activé';
            } else {
                clearInterval(autoRefreshInterval);
                document.getElementById('refresh-status').textContent = 'Rafraîchissement automatique désactivé';
            }
        }
        
        // Rafraîchir les notifications
        function refreshNotifications() {
            fetch('notifications_api.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateNotificationsDisplay(data);
                    }
                })
                .catch(error => {
                    console.error('Erreur lors du rafraîchissement:', error);
                });
        }
        
        // Mettre à jour l'affichage des notifications
        function updateNotificationsDisplay(data) {
            // Mettre à jour les statistiques
            document.getElementById('total-notifications').textContent = data.stats.total_notifications;
            document.getElementById('checkout-pending').textContent = data.stats.checkout_pending;
            document.getElementById('cleaning-required').textContent = data.stats.cleaning_required;
            document.getElementById('urgent-count').textContent = data.stats.urgent_count;
            
            // Mettre à jour la liste des notifications
            const notificationsList = document.getElementById('notifications-list');
            notificationsList.innerHTML = '';
            
            data.notifications.forEach(notification => {
                const notificationHtml = createNotificationHTML(notification);
                notificationsList.innerHTML += notificationHtml;
            });
        }
        
        // Créer le HTML d'une notification
        function createNotificationHTML(notification) {
            const priorityClass = notification.priority;
            const priorityColor = notification.priority === 'urgent' ? 'danger' : 
                                (notification.priority === 'high' ? 'warning' : 'info');
            
            return `
                <div class="notification-card ${priorityClass} mb-3 p-3 rounded">
                    <div class="row align-items-center">
                        <div class="col-md-1">
                            <span class="status-indicator status-${notification.notification_type.replace('_', '-')}"></span>
                        </div>
                        <div class="col-md-3">
                            <strong>Chambre ${notification.room_number}</strong>
                            ${notification.floor ? `<br><small class="text-muted">Étage ${notification.floor}</small>` : ''}
                        </div>
                        <div class="col-md-3">
                            <span class="badge bg-${priorityColor}">${notification.priority.charAt(0).toUpperCase() + notification.priority.slice(1)}</span>
                            <br><small class="text-muted">${notification.notification_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}</small>
                        </div>
                        <div class="col-md-3">
                            ${notification.reservation_number ? `
                                <strong>${notification.reservation_number}</strong>
                                <br><small class="text-muted">${notification.client_first_name} ${notification.client_last_name}</small>
                            ` : ''}
                        </div>
                        <div class="col-md-2 text-end">
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-outline-success" onclick="acknowledgeNotification(${notification.id})">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="completeNotification(${notification.id})">
                                    <i class="fas fa-flag-checkered"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-12">
                            <small class="text-muted">
                                <i class="fas fa-clock me-1"></i>
                                Créé le ${new Date(notification.created_at).toLocaleString('fr-FR')}
                            </small>
                            <p class="mb-0 mt-1">${notification.message}</p>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // Acquitter une notification
        function acknowledgeNotification(notificationId) {
            fetch('notifications_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'acknowledge',
                    notification_id: notificationId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    refreshNotifications();
                } else {
                    alert('Erreur: ' + data.error);
                }
            });
        }
        
        // Terminer une notification
        function completeNotification(notificationId) {
            fetch('notifications_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'complete',
                    notification_id: notificationId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    refreshNotifications();
                } else {
                    alert('Erreur: ' + data.error);
                }
            });
        }
        
        // Traiter les check-outs
        function processCheckouts() {
            fetch('notifications_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'process_checkouts'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`${data.processed} check-outs traités`);
                    refreshNotifications();
                } else {
                    alert('Erreur: ' + data.error);
                }
            });
        }
        
        // Traiter les statuts des chambres
        function processRoomStatus() {
            fetch('notifications_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'process_room_status'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`${data.processed} statuts de chambres mis à jour`);
                    refreshNotifications();
                } else {
                    alert('Erreur: ' + data.error);
                }
            });
        }
        
        // Afficher les détails d'une chambre
        function showRoomDetails(roomId) {
            // Implémenter l'affichage des détails de la chambre
            console.log('Détails de la chambre:', roomId);
        }
        
        // Marquer une chambre comme nettoyée
        function markRoomAsCleaned(roomId) {
            if (confirm('Marquer cette chambre comme nettoyée ?')) {
                fetch('notifications_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'mark_cleaned',
                        room_id: roomId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Chambre marquée comme nettoyée');
                        refreshNotifications();
                    } else {
                        alert('Erreur: ' + data.error);
                    }
                });
            }
        }
        
        // Mettre une chambre en maintenance
        function setRoomMaintenance(roomId) {
            if (confirm('Mettre cette chambre en maintenance ?')) {
                updateRoomStatus(roomId, 'maintenance');
            }
        }
        
        // Mettre une chambre disponible
        function setRoomAvailable(roomId) {
            if (confirm('Mettre cette chambre disponible ?')) {
                updateRoomStatus(roomId, 'available');
            }
        }
        
        // Mettre à jour le statut d'une chambre
        function updateRoomStatus(roomId, newStatus) {
            fetch('notifications_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'update_room_status',
                    room_id: roomId,
                    new_status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Statut de la chambre mis à jour');
                    refreshNotifications();
                } else {
                    alert('Erreur: ' + data.error);
                }
            });
        }
        
        // Démarrer le rafraîchissement automatique au chargement
        document.addEventListener('DOMContentLoaded', function() {
            startAutoRefresh();
        });
    </script>
    
    <?php include __DIR__ . '/../../includes/footer.php'; ?>
</body>
</html>
