<?php
/**
 * Map Component (LeafletJS)
 * Interactive map with markers
 * 
 * Attributes:
 * - lat: Center latitude (default: 41.0082 - Istanbul)
 * - lng: Center longitude (default: 28.9784)
 * - zoom: Zoom level (default: 13)
 * - height: Map height (default: 400px)
 * - markers: JSON array with lat, lng, title, popup
 * - style: Map style (streets, satellite, terrain)
 */

$lat = $lat ?? 41.0082;
$lng = $lng ?? 28.9784;
$zoom = $zoom ?? 13;
$height = $height ?? '400px';
$style = $style ?? 'streets';

$markers = $markers ?? [];
if (is_string($markers)) {
    $markers = json_decode(html_entity_decode($markers), true) ?: [];
}

if (empty($markers)) {
    $markers = [
        ['lat' => $lat, 'lng' => $lng, 'title' => 'Our Location', 'popup' => '<strong>Our Office</strong><br>123 Main Street<br>Istanbul, Turkey']
    ];
}

$mapId = 'map-' . uniqid();

// Tile layer URLs based on style
$tileLayers = [
    'streets' => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    'satellite' => 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
    'terrain' => 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png'
];
$tileUrl = $tileLayers[$style] ?? $tileLayers['streets'];
?>

<section class="section py-0">
    <div id="<?= $mapId ?>" style="height: <?= htmlspecialchars($height) ?>; width: 100%; border-radius: 8px;"></div>
</section>

<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>
    (function () {
        const map = L.map('<?= $mapId ?>').setView([<?= (float) $lat ?>, <?= (float) $lng ?>], <?= (int) $zoom ?>);

        L.tileLayer('<?= $tileUrl ?>', {
            maxZoom: 19,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        }).addTo(map);

        // Add markers
        const markers = <?= json_encode($markers) ?>;
        markers.forEach(m => {
            const marker = L.marker([m.lat, m.lng]).addTo(map);
            if (m.popup) {
                marker.bindPopup(m.popup);
            }
            if (m.title) {
                marker.bindTooltip(m.title);
            }
        });
    })();
</script>