<?php
// =============================================
// VUE RÉSERVATIONS EN ATTENTE - views/reservations/pending.php
// Liste des réservations en attente de paiement
// =============================================
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-clock"></i> Réservations en Attente de Paiement</h2>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary" onclick="refreshPage()">
            <i class="bi bi-arrow-clockwise"></i> Actualiser
        </button>
        <a href="<?= base_url('reservations') ?>" class="btn btn-maritime">
            <i class="bi bi-plus-circle"></i> Nouvelle Réservation
        </a>
    </div>
</div>

<!-- Statistiques -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="stats-card">
            <div class="stats-label">En Attente</div>
            <div class="stats-value text-warning"><?= count($reservations_pending) ?></div>
            <div class="stats-change">
                <i class="bi bi-clock"></i> À traiter
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stats-card">
            <div class="stats-label">Montant Total</div>
            <div class="stats-value text-success">
                <?php 
                $total = array_sum(array_map(function($r) { return $r->tarif_total; }, $reservations_pending));
                echo format_currency($total);
                ?>
            </div>
            <div class="stats-change text-success">
                <i class="bi bi-currency-exchange"></i> À encaisser
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stats-card">
            <div class="stats-label">Aujourd'hui</div>
            <div class="stats-value text-info">
                <?php 
                $today_count = count(array_filter($reservations_pending, function($r) {
                    return date('Y-m-d', strtotime($r->created_at)) === date('Y-m-d');
                }));
                echo $today_count;
                ?>
            </div>
            <div class="stats-change text-info">
                <i class="bi bi-calendar-day"></i> Créées
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stats-card">
            <div class="stats-label">Urgentes</div>
            <div class="stats-value text-danger">
                <?php 
                $urgent_count = count(array_filter($reservations_pending, function($r) {
                    return date('Y-m-d', strtotime($r->date_voyage)) <= date('Y-m-d', strtotime('+1 day'));
                }));
                echo $urgent_count;
                ?>
            </div>
            <div class="stats-change text-danger">
                <i class="bi bi-exclamation-triangle"></i> < 24h
            </div>
        </div>
    </div>
</div>

<!-- Filtres -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Rechercher</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-search"></i></span>
                    <input type="text" class="form-control" id="search_reservation" 
                           placeholder="Code, nom, téléphone...">
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Voyage</label>
                <select class="form-select" id="filter_voyage">
                    <option value="">Tous les voyages</option>
                    <?php 
                    $voyages = array_unique(array_map(function($r) { 
                        return $r->numero_voyage; 
                    }, $reservations_pending));
                    foreach ($voyages as $voyage): ?>
                        <option value="<?= $voyage ?>"><?= $voyage ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Date Voyage</label>
                <input type="date" class="form-control" id="filter_date" 
                       min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Priorité</label>
                <select class="form-select" id="filter_priority">
                    <option value="">Toutes</option>
                    <option value="urgent">Urgentes (< 24h)</option>
                    <option value="today">Voyage aujourd'hui</option>
                    <option value="recent">Créées aujourd'hui</option>
                </select>
            </div>
        </div>
    </div>
</div>

<!-- Liste des Réservations -->
<div class="card table-maritime">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="bi bi-list"></i> Réservations en Attente
            <span class="badge bg-warning ms-2" id="count_display"><?= count($reservations_pending) ?></span>
        </h5>
    </div>
    <div class="card-body">
        <?php if (empty($reservations_pending)): ?>
            <div class="text-center py-5">
                <i class="bi bi-check-circle text-success" style="font-size: 4rem;"></i>
                <h4 class="mt-3 text-success">Parfait ! Aucune réservation en attente</h4>
                <p class="text-muted">Tous les billets émis ont été payés</p>
                <a href="<?= base_url('reservations') ?>" class="btn btn-maritime mt-3">
                    <i class="bi bi-plus-circle"></i> Créer une Nouvelle Réservation
                </a>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="table_pending">
                    <thead>
                        <tr>
                            <th>Priorité</th>
                            <th>Réservation</th>
                            <th>Passager</th>
                            <th>Voyage</th>
                            <th>Montant</th>
                            <th>Créé le</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reservations_pending as $reservation): ?>
                        <?php
                        $is_urgent = date('Y-m-d', strtotime($reservation->date_voyage)) <= date('Y-m-d', strtotime('+1 day'));
                        $is_today = date('Y-m-d', strtotime($reservation->date_voyage)) === date('Y-m-d');
                        $created_today = date('Y-m-d', strtotime($reservation->created_at)) === date('Y-m-d');
                        ?>
                        <tr data-reservation="<?= strtolower($reservation->code_reservation . ' ' . $reservation->nom . ' ' . $reservation->prenom . ' ' . $reservation->telephone) ?>" 
                            data-voyage="<?= $reservation->numero_voyage ?>" 
                            data-date="<?= $reservation->date_voyage ?>"
                            data-priority="<?= $is_urgent ? 'urgent' : ($is_today ? 'today' : ($created_today ? 'recent' : 'normal')) ?>">
                            <td>
                                <?php if ($is_urgent): ?>
                                    <span class="badge bg-danger">
                                        <i class="bi bi-exclamation-triangle"></i> Urgent
                                    </span>
                                <?php elseif ($is_today): ?>
                                    <span class="badge bg-warning">
                                        <i class="bi bi-clock"></i> Aujourd'hui
                                    </span>
                                <?php elseif ($created_today): ?>
                                    <span class="badge bg-info">
                                        <i class="bi bi-plus-circle"></i> Nouveau
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Normal</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div>
                                    <strong class="text-maritime"><?= $reservation->code_reservation ?></strong>
                                    <?php if (isset($reservation->numero_billet)): ?>
                                        <br><small class="text-muted">Billet: <?= $reservation->numero_billet ?></small>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div>
                                    <strong><?= $reservation->nom . ' ' . $reservation->prenom ?></strong>
                                    <?php if ($reservation->telephone): ?>
                                        <br><small class="text-muted">
                                            <i class="bi bi-phone"></i> <?= format_phone_km($reservation->telephone) ?>
                                        </small>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div>
                                    <strong><?= $reservation->numero_voyage ?></strong>
                                    <br><span class="badge bg-primary me-1"><?= $reservation->port_depart ?></span>
                                    <i class="bi bi-arrow-right mx-1"></i>
                                    <span class="badge bg-success"><?= $reservation->port_arrivee ?></span>
                                    <br><small class="text-muted">
                                        <?= date('d/m/Y', strtotime($reservation->date_voyage)) ?> 
                                        <?= $reservation->heure_depart ?>
                                    </small>
                                </div>
                            </td>
                            <td>
                                <div class="text-center">
                                    <strong class="text-success fs-5"><?= format_currency($reservation->tarif_total) ?></strong>
                                    <?php if ($reservation->tarif_vehicule > 0): ?>
                                        <br><small class="text-muted">
                                            <i class="bi bi-car-front"></i> Incl. véhicule
                                        </small>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <small class="text-muted">
                                    <?= date('d/m/Y H:i', strtotime($reservation->created_at)) ?>
                                </small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <?php if (isset($reservation->billet_id)): ?>
                                        <a href="<?= base_url('caisse/paiement/' . $reservation->billet_id) ?>" 
                                           class="btn btn-success" title="Traiter Paiement">
                                            <i class="bi bi-cash"></i>
                                        </a>
                                    <?php endif; ?>
                                    <a href="<?= base_url('reservations/details/' . $reservation->id) ?>" 
                                       class="btn btn-outline-info" title="Détails">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <button class="btn btn-outline-primary" 
                                            onclick="contactPassenger('<?= $reservation->telephone ?>', '<?= $reservation->nom ?>')" 
                                            title="Contacter">
                                        <i class="bi bi-phone"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Actions en lot -->
<?php if (!empty($reservations_pending)): ?>
<div class="card mt-3">
    <div class="card-body">
        <h6 class="fw-bold mb-3">Actions en Lot</h6>
        <div class="d-flex gap-2">
            <button class="btn btn-outline-warning" onclick="sendReminderSMS()">
                <i class="bi bi-chat-text"></i> Envoyer Rappels SMS
            </button>
            <button class="btn btn-outline-info" onclick="exportPendingList()">
                <i class="bi bi-download"></i> Exporter Liste
            </button>
            <button class="btn btn-outline-secondary" onclick="printPendingList()">
                <i class="bi bi-printer"></i> Imprimer
            </button>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Filtrage en temps réel
    const searchInput = document.getElementById('search_reservation');
    const voyageFilter = document.getElementById('filter_voyage');
    const dateFilter = document.getElementById('filter_date');
    const priorityFilter = document.getElementById('filter_priority');
    
    function filterTable() {
        const searchTerm = searchInput.value.toLowerCase();
        const voyageValue = voyageFilter.value;
        const dateValue = dateFilter.value;
        const priorityValue = priorityFilter.value;
        
        const rows = document.querySelectorAll('#table_pending tbody tr');
        let visibleCount = 0;
        
        rows.forEach(row => {
            const reservationData = row.dataset.reservation;
            const voyageData = row.dataset.voyage;
            const dateData = row.dataset.date;
            const priorityData = row.dataset.priority;
            
            const matchSearch = reservationData.includes(searchTerm);
            const matchVoyage = !voyageValue || voyageData === voyageValue;
            const matchDate = !dateValue || dateData === dateValue;
            const matchPriority = !priorityValue || priorityData === priorityValue;
            
            const isVisible = matchSearch && matchVoyage && matchDate && matchPriority;
            row.style.display = isVisible ? '' : 'none';
            
            if (isVisible) visibleCount++;
        });
        
        // Mettre à jour le compteur
        document.getElementById('count_display').textContent = visibleCount;
    }
    
    searchInput.addEventListener('input', filterTable);
    voyageFilter.addEventListener('change', filterTable);
    dateFilter.addEventListener('change', filterTable);
    priorityFilter.addEventListener('change', filterTable);
});

function refreshPage() {
    window.location.reload();
}

function contactPassenger(telephone, nom) {
    if (telephone) {
        // Ouvrir l'application téléphone ou WhatsApp
        const message = `Bonjour ${nom}, votre réservation maritime est en attente de paiement. Merci de vous présenter en agence.`;
        const whatsappUrl = `https://wa.me/${telephone.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(message)}`;
        window.open(whatsappUrl, '_blank');
    } else {
        alert('Aucun numéro de téléphone disponible');
    }
}

function sendReminderSMS() {
    if (confirm('Envoyer un rappel SMS à tous les passagers en attente ?')) {
        // Implémenter logique d'envoi SMS
        alert('Fonctionnalité SMS à implémenter');
    }
}

function exportPendingList() {
    window.location.href = '<?= base_url('reservations/export_pending') ?>';
}

function printPendingList() {
    window.print();
}

// Actualisation automatique toutes les 5 minutes
setInterval(function() {
    // Actualisation douce sans recharger la page
    fetch('<?= base_url('reservations/pending_count') ?>')
        .then(response => response.json())
        .then(data => {
            if (data.count !== <?= count($reservations_pending) ?>) {
                // Afficher notification de nouvelles réservations
                showNotification('Nouvelles réservations détectées', 'info');
            }
        })
        .catch(error => console.log('Erreur actualisation:', error));
}, 300000); // 5 minutes

function showNotification(message, type) {
    // Afficher une notification discrète
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(notification);
    
    // Supprimer après 5 secondes
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 5000);
}
</script>

<style>
@media print {
    .btn, .card-header, .alert, .pagination { display: none !important; }
    .table th, .table td { font-size: 12px !important; }
    .stats-card { border: 1px solid #ddd !important; }
}
</style>