<?php
require_once 'config.php';
checkLogin();

$id = $_GET['id'] ?? null;
if (!$id) {
    header("Location: index.php");
    exit();
}

$stmt = $pdo->prepare("SELECT * FROM contactos WHERE id = ?");
$stmt->execute([$id]);
$c = $stmt->fetch();

if (!$c) {
    header("Location: index.php");
    exit();
}

// Usaremos OpenStreetMap (Leaflet) para mostrar el mapa con la geoposición
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Mapa de Contacto - Directorio Corporativo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        #map { height: 500px; width: 100%; border-radius: 10px; }
        body { background: #f4f7f6; }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="card shadow">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Ubicación de <?php echo htmlspecialchars($c['nombre_apellido']); ?></h5>
                <a href="index.php" class="btn btn-light btn-sm">Volver</a>
            </div>
            <div class="card-body">
                <div id="map"></div>
                <div class="mt-3">
                    <p><strong>Coordenadas:</strong> <?php echo $c['latitud']; ?>, <?php echo $c['longitud']; ?></p>
                    <p><strong>Empresa:</strong> <?php echo htmlspecialchars($c['empresa']); ?></p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        var lat = <?php echo $c['latitud']; ?>;
        var lng = <?php echo $c['longitud']; ?>;
        
        var map = L.map('map').setView([lat, lng], 13);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        L.marker([lat, lng]).addTo(map)
            .bindPopup('<?php echo htmlspecialchars($c['nombre_apellido']); ?><br><?php echo htmlspecialchars($c['empresa']); ?>')
            .openPopup();
    </script>
</body>
</html>
