<?php
// Vue cartographie simplifiée pour débogage
$base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
if ($base === '/') { $base = ''; }
?>

<h2>🗺️ Cartographie (Version Debug)</h2>

<div id="debug-info" style="background: #f0f0f0; padding: 15px; margin: 15px 0; border-radius: 5px;">
    <strong>Debug Info:</strong><br>
    BASE: <code id="base-value"><?= htmlspecialchars($base) ?></code><br>
    API URL: <code id="api-url"></code><br>
    Status: <span id="load-status">Initialisation...</span>
</div>

<div id="stats" style="background: #fff; padding: 15px; margin: 15px 0; border: 1px solid #ddd; border-radius: 5px;">
    <h4>Statistiques</h4>
    <div>Incidents: <strong id="stat-incidents">--</strong></div>
    <div>Techniciens: <strong id="stat-techs">--</strong></div>
</div>

<div id="map" style="height: 500px; border: 1px solid #ccc; margin: 15px 0;"></div>

<div style="background: #000; color: #0f0; padding: 10px; margin: 15px 0; border-radius: 5px; font-family: monospace; font-size: 12px; max-height: 300px; overflow-y: auto;">
    <strong style="color: #fff;">Console Logs:</strong>
    <pre id="console-output" style="margin: 10px 0;"></pre>
</div>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
// Configuration
const BASE = '<?= $base ?>';
const consoleOutput = document.getElementById('console-output');

// Fonction pour logger dans la console ET dans la page
function log(message, type = 'info') {
    const timestamp = new Date().toLocaleTimeString();
    const formattedMsg = `[${timestamp}] ${message}`;
    console.log(formattedMsg);
    consoleOutput.textContent += formattedMsg + '\n';
    consoleOutput.parentElement.scrollTop = consoleOutput.parentElement.scrollHeight;
}

log('=== DÉMARRAGE ===');
log('BASE = ' + BASE);

document.getElementById('api-url').textContent = BASE + '/cartography/data';

// Initialiser la carte
log('Initialisation de Leaflet...');
const map = L.map('map').setView([5.35, -4.02], 7);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19
}).addTo(map);
log('Carte initialisée');

// Charger les données
async function loadIncidents() {
    log('Chargement des incidents...');
    document.getElementById('load-status').textContent = 'Chargement...';
    
    try {
        const url = BASE + '/cartography/data';
        log('Fetch vers: ' + url);
        
        const response = await fetch(url, {
            credentials: 'include'
        });
        
        log('Réponse reçue - Status: ' + response.status);
        
        if (!response.ok) {
            const errorText = await response.text();
            log('ERREUR HTTP ' + response.status + ': ' + errorText);
            document.getElementById('load-status').textContent = 'Erreur ' + response.status;
            
            if (response.status === 401) {
                document.getElementById('load-status').innerHTML = '❌ Non authentifié - <a href="' + BASE + '/login">Se connecter</a>';
            }
            return;
        }
        
        const text = await response.text();
        log('Réponse texte (100 premiers caractères): ' + text.substring(0, 100));
        
        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            log('ERREUR parsing JSON: ' + e.message);
            document.getElementById('load-status').textContent = 'Erreur parsing';
            return;
        }
        
        log('Données parsées: ' + (Array.isArray(data) ? data.length + ' éléments' : 'PAS UN TABLEAU'));
        log('Données complètes: ' + JSON.stringify(data));
        
        if (!Array.isArray(data)) {
            log('ERREUR: data n\'est pas un tableau');
            document.getElementById('load-status').textContent = 'Format invalide';
            return;
        }
        
        // Mettre à jour les stats
        document.getElementById('stat-incidents').textContent = data.length;
        
        if (data.length === 0) {
            log('⚠️ Aucun incident trouvé');
            document.getElementById('load-status').textContent = 'Aucune donnée';
            return;
        }
        
        // Afficher les incidents
        log('Ajout de ' + data.length + ' marqueurs...');
        const bounds = [];
        
        data.forEach((incident, i) => {
            log('Incident ' + (i+1) + ': ' + incident.title + ' [' + incident.lat + ', ' + incident.lng + ']');
            
            if (incident.lat && incident.lng) {
                const marker = L.marker([incident.lat, incident.lng])
                    .bindPopup('<strong>' + incident.title + '</strong><br>Status: ' + incident.status)
                    .addTo(map);
                bounds.push([incident.lat, incident.lng]);
                log('✓ Marqueur ajouté');
            } else {
                log('✗ Coordonnées manquantes');
            }
        });
        
        if (bounds.length > 0) {
            log('Ajustement de la vue...');
            const group = L.featureGroup(bounds.map(b => L.marker(b)));
            map.fitBounds(group.getBounds().pad(0.1));
            document.getElementById('load-status').textContent = '✅ ' + bounds.length + ' incident(s)';
            log('=== SUCCÈS ===');
        } else {
            log('⚠️ Aucune coordonnée valide');
            document.getElementById('load-status').textContent = 'Aucune position valide';
        }
        
    } catch (error) {
        log('EXCEPTION: ' + error.message);
        log('Stack: ' + error.stack);
        document.getElementById('load-status').textContent = 'Erreur: ' + error.message;
    }
}

// Démarrer le chargement
log('Lancement du chargement...');
map.whenReady(() => {
    log('Carte prête, chargement des données...');
    loadIncidents();
});
</script>