<?php
/**
 * Page des pointages Boumerdes - Version Corrigée
 * FactDGR - Système de facturation
 */
?>

<style>
    /* Animation de chargement */
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }

    /* Animation des cartes */
    @keyframes slideInUp {
        0% { transform: translateY(30px); opacity: 0; }
        100% { transform: translateY(0); opacity: 1; }
    }

    /* Style des cartes */
    .stats-card {
        transition: all 0.3s ease;
        animation: slideInUp 0.5s ease-out;
        height: 100%;
        cursor: pointer;
    }

    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    }

    .stats-card .icon-box {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        margin-right: 15px;
        animation: pulse 2s infinite;
    }

    /* Style du tableau */
    .table-hover tbody tr:hover {
        background-color: rgba(0, 123, 255, 0.1);
    }

    /* Style de la carte GPS */
    #map {
        height: 400px;
        border-radius: 0.5rem;
    }
</style>

<div class="container-fluid">
    <div class="row">
        <!-- Sélecteur de date -->
        <div class="col-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0"><i class="fas fa-calendar-alt"></i> Sélectionner la date</h5>
                </div>
                <div class="card-body">
                    <div class="row align-items-end">
                        <div class="col-md-4">
                            <div class="form-group mb-0">
                                <label for="pointageDate" class="font-weight-bold">Date du pointage</label>
                                <input type="date" class="form-control" id="pointageDate" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-primary" id="chargerPointages">
                                <i class="fas fa-sync-alt"></i> Charger les pointages
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Cartes Statistiques (Ordre: Bus Disp, Bus Point, Bus Abs, Taxi Disp, Taxi Point, Taxi Abs) -->
        <div class="col-12 mb-4">
            <div class="row">
                <!-- Bus Disponible -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-success text-white" onclick="afficherDetails('Bus', 'Disponible')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-white bg-opacity-25 rounded-circle">
                                    <i class="fas fa-bus"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Bus Disponible</h6>
                                    <p class="card-text h3" id="busDisponible">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bus Pointer -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-info text-white" onclick="afficherDetails('Bus', 'Pointer')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-white bg-opacity-25 rounded-circle">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Bus Pointer</h6>
                                    <p class="card-text h3" id="busPointer">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bus Absent -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-danger text-white" onclick="afficherDetails('Bus', 'Absent')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-white bg-opacity-25 rounded-circle">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Bus Absent</h6>
                                    <p class="card-text h3" id="busAbsent">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Taxi Disponible -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-primary text-white" onclick="afficherDetails('Taxi', 'Disponible')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-white bg-opacity-25 rounded-circle">
                                    <i class="fas fa-taxi"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Taxi Disponible</h6>
                                    <p class="card-text h3" id="taxiDisponible">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Taxi Pointer -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-warning text-dark" onclick="afficherDetails('Taxi', 'Pointer')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-dark bg-opacity-10 rounded-circle">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Taxi Pointer</h6>
                                    <p class="card-text h3" id="taxiPointer">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Taxi Absent -->
                <div class="col-md-2 mb-3">
                    <div class="card stats-card bg-secondary text-white" onclick="afficherDetails('Taxi', 'Absent')">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="icon-box bg-white bg-opacity-25 rounded-circle">
                                    <i class="fas fa-times-circle"></i>
                                </div>
                                <div>
                                    <h6 class="card-title mb-0">Taxi Absent</h6>
                                    <p class="card-text h3" id="taxiAbsent">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tableau des pointages -->
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Liste des pointages</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="mainPointagesTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Matricule</th>
                                    <th>Type</th>
                                    <th>Opérateur</th>
                                    <th>Ligne</th>
                                    <th>Date</th>
                                    <th>Heure</th>
                                    <th>Agent</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="pointagesTableBody">
                                <!-- Chargé par AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Détails -->
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="detailsModalTitle">Détails</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="detailsModalBody">
                <!-- Chargé dynamiquement -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal GPS -->
<div class="modal fade" id="mapModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title">Localisation GPS</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="map"></div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

<script>
    let map;
    let marker;
    let allPointages = [];

    // Configuration de l'API - Chemin vers votre index.php
    const API_URL = 'api/apiversement/index.php';

    $(document).ready(function() {
        chargerDonnees();

        $('#chargerPointages').click(function() {
            chargerDonnees();
        });

        $('#pointageDate').change(function() {
            chargerDonnees();
        });
    });

    function chargerDonnees() {
        const date = $('#pointageDate').val();
        const btn = $('#chargerPointages');
        
        btn.html('<i class="fas fa-spinner fa-spin"></i> Chargement...').prop('disabled', true);

        $.ajax({
            url: API_URL,
            type: 'GET',
            data: {
                route: 'pointages',
                action: 'getDashboardData',
                date: date
            },
            success: function(response) {
                if (response.success) {
                    $('#busDisponible').text(response.busDisponible);
                    $('#busPointer').text(response.busPointer);
                    $('#busAbsent').text(response.busAbsent);
                    $('#taxiDisponible').text(response.taxiDisponible);
                    $('#taxiPointer').text(response.taxiPointer);
                    $('#taxiAbsent').text(response.taxiAbsent);

                    allPointages = response.pointages;
                    renderTable(allPointages);
                } else {
                    alert('Erreur: ' + response.message);
                }
            },
            error: function() {
                alert('Erreur lors du chargement des données.');
            },
            complete: function() {
                btn.html('<i class="fas fa-sync-alt"></i> Charger les pointages').prop('disabled', false);
            }
        });
    }

    function renderTable(data) {
        const tbody = $('#pointagesTableBody');
        tbody.empty();

        if (data.length === 0) {
            tbody.append('<tr><td colspan="9" class="text-center">Aucun pointage trouvé pour cette date.</td></tr>');
            return;
        }

        data.forEach(p => {
            tbody.append(`
                <tr>
                    <td>${p.id}</td>
                    <td>${p.matricule}</td>
                    <td>${p.type}</td>
                    <td>${p.operateur || '-'}</td>
                    <td>${p.ligne || '-'}</td>
                    <td>${p.date}</td>
                    <td>${p.time}</td>
                    <td>${p.agent}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="afficherGPS(${p.latitude}, ${p.longitude})">
                            <i class="fas fa-map-marker-alt"></i> GPS
                        </button>
                    </td>
                </tr>
            `);
        });
    }

    function afficherDetails(type, category) {
        const date = $('#pointageDate').val();
        $('#detailsModalTitle').text(`Détails ${type} - ${category}`);
        $('#detailsModalBody').html('<div class="text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></div>');
        $('#detailsModal').modal('show');

        $.ajax({
            url: API_URL,
            type: 'GET',
            data: {
                route: 'pointages',
                action: 'getDetails',
                type: type,
                category: category,
                date: date
            },
            success: function(response) {
                if (response.success) {
                    let html = `<p class="font-weight-bold">Total: ${response.count}</p>`;
                    html += `
                        <table class="table table-sm table-striped">
                            <thead>
                                <tr>
                                    <th>Matricule</th>
                                    <th>Opérateur</th>
                                    <th>Ligne</th>
                                    ${category === 'Pointer' ? '<th>Heure</th><th>Agent</th>' : ''}
                                </tr>
                            </thead>
                            <tbody>
                    `;

                    response.details.forEach(d => {
                        html += `
                            <tr>
                                <td>${d.matricule}</td>
                                <td>${d.operateur || '-'}</td>
                                <td>${d.ligne || '-'}</td>
                                ${category === 'Pointer' ? `<td>${d.time}</td><td>${d.agent}</td>` : ''}
                            </tr>
                        `;
                    });

                    html += '</tbody></table>';
                    $('#detailsModalBody').html(html);
                } else {
                    $('#detailsModalBody').html('<div class="alert alert-danger">Erreur: ' + response.message + '</div>');
                }
            },
            error: function() {
                $('#detailsModalBody').html('<div class="alert alert-danger">Erreur lors du chargement des détails.</div>');
            }
        });
    }

    function afficherGPS(lat, lng) {
        $('#mapModal').modal('show');
        
        setTimeout(() => {
            if (!map) {
                map = L.map('map').setView([lat, lng], 15);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap'
                }).addTo(map);
                marker = L.marker([lat, lng]).addTo(map);
            } else {
                map.setView([lat, lng], 15);
                if (marker) map.removeLayer(marker);
                marker = L.marker([lat, lng]).addTo(map);
            }
            map.invalidateSize();
        }, 500);
    }
</script>
