<?= $this->extend('template/layout') ?>

<?= $this->section('title') ?><?= $title ?><?= $this->endSection() ?>

<!-- main section start-->
<?= $this->section('main') ?>
<?php
   $uri      = current_url(true);
   $segment1 = $uri->setSilent()->getSegment(1);
   $segment2 = $uri->setSilent()->getSegment(2);
   $segment3 = $uri->setSilent()->getSegment(3);
?>
<!-- Breadcumb -->
<ol class="breadcrumb page-breadcrumb">
   <li class="breadcrumb-item"><a href="javascript:void(0);"><?= env('app.name') ?></a></li>
   <li class="breadcrumb-item">Dashboard</li>
   <li class="breadcrumb-item">Cabang/ UPC/ UPS</li>
   <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<div class="subheader">
   <h1 class="subheader-title">
      <i class="subheader-icon fal fa-map-marked-alt"></i> <?= $title ?> <span class="fw-300"><?= $tahun_aktif ?></span>
   </h1>
   <div class="subheader-block d-lg-flex align-items-center">
      <div class="d-flex mr-4">
         <div class="mr-2">
               
         </div>
         <div>
            
         </div>
      </div>
      <div class="d-flex mr-0">
         <div class="mr-2">
            <ul class="nav nav-pills border-bottom-0" role="tablist">
               <li class="nav-item">
                  <a class="nav-link active" href="<?= $link_back ?>"><i class="fal fa-arrow-left"></i> Summary</a>
               </li>
            </ul>
         </div>
         <div>
               
         </div>
      </div>
   </div>
</div>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
   <a class="navbar-brand d-flex align-items-center fw-500" href="#">
      Legend
   </a>
   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
   </button>
   <div class="collapse navbar-collapse" id="navbarColor01">
      <ul class="navbar-nav mr-auto">
         <li class="nav-item active">
            <div class="d-flex align-items-center mb-2 nav-link">
               <div style="width: 20px; height: 20px; background: #007bff; border-radius: 50%; margin-right: 10px;"></div>
               <span>Kantor Anda</span>
            </div>
         </li>
         <li class="nav-item active">
            <div class="d-flex align-items-center mb-2 nav-link">
               <div style="width: 20px; height: 20px; background: #28a745; border-radius: 50%; margin-right: 10px;"></div>
               <span>Nilai Tinggi</span>
            </div>
         </li>
         <li class="nav-item active">
            <div class="d-flex align-items-center nav-link">
               <div style="width: 20px; height: 20px; background: #dc3545; border-radius: 50%; margin-right: 10px;"></div>
               <span>Nilai Rendah</span>
            </div>
         </li>
      </ul>
      <div class="btn-group mr-3" role="group">
         <input type="radio" class="btn-check" name="heatmap_mode" id="mode_efektivitas" value="efektivitas" checked>&nbsp;&nbsp;
         <label class="btn btn-outline-success" for="mode_efektivitas">
            <i class="fa fa-chart-line mr-1"></i>Efektivitas
         </label>&nbsp;&nbsp;
         <input type="radio" class="btn-check" name="heatmap_mode" id="mode_konversi" value="konversi">&nbsp;&nbsp;
         <label class="btn btn-outline-primary" for="mode_konversi">
            <i class="fa fa-percentage mr-1"></i>% Konversi
         </label>
      </div>
   </div>
</nav>

<div class="row">
   <div class="col-xl-12">
      <!-- Panel Header dengan kontrol -->
      <div class="panel">
         <div class="panel-hdr">
            <h2>
               Lokasi Kegiatan Promosi 
               <span class="fw-300"><i>Tahun <?= $tahun_aktif ?></i></span>
            </h2>
            <!-- Filter Tahun -->
            <div class="panel-toolbar ml-2">
               <div class="d-flex position-relative ml-auto" style="max-width: 8rem;">
                  <i class="fal fa-search position-absolute pos-left fs-lg px-2 py-1 mt-1 fs-xs"></i>
                  <input type="text" id="filter-tahun" class="form-control form-control-sm pl-5" maxlength="4" placeholder="Cari Tahun" value="<?= $tahun_aktif ?>" min="2020" max="<?= date('Y') + 1 ?>">
               </div>
            </div>
         </div>
         
         <div class="panel-container show">
            <div class="panel-content">
               
               <!-- Loading indicator -->
               <div id="map-loading" class="text-center p-4">
                  <div class="spinner-border text-primary" role="status">
                     <span class="sr-only">Loading...</span>
                  </div>
                  <p class="mt-2">Memuat peta...</p>
               </div>
               
               <!-- Map Container -->
               <div id="heatmap" style="height: 600px; width: 100%; display: none;"></div>
               
               <!-- Legend -->
               <div id="legend" class="mt-3" style="display: none;">
                  <div class="row">
                     <div class="col-md-12">
                        <h6>📊 Gradasi Warna:</h6>
                        <div class="gradient-bar" style="background: linear-gradient(to right, #dc3545, #ffc107, #28a745); height: 20px; border-radius: 10px; margin-bottom: 10px;"></div>
                        <div class="d-flex justify-content-between small">
                           <span>Rendah</span>
                           <span>Sedang</span>
                           <span>Tinggi</span>
                        </div>
                     </div>
                  </div>
               </div>

               <!-- Info Panel -->
               <div class="mt-3">
                  <div class="row">
                     <div class="col-md-12">
                        <div class="alert alert-info">
                           <h6><i class="fa fa-info-circle mr-2"></i>Informasi Heatmap</h6>
                           <p class="mb-1">• <strong>Efektivitas:</strong> Menampilkan efektivitas lokasi berdasarkan (% konversi ÷ jumlah kegiatan) × 10</p>
                           <p class="mb-1">• <strong>% Konversi:</strong> Menampilkan persentase konversi calon nasabah menjadi closing</p>
                           <p class="mb-0">• <strong>Radius:</strong> Menampilkan area dalam radius 5 km dari kantor</p>
                        </div>
                     </div>
                  </div>
               </div>

            </div>
         </div>
      </div>
   </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('pageScripts') ?>

<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
$(document).ready(function() {
    // Data dari PHP
    var dataKantor = <?= json_encode($data_kantor) ?>;
    var dataLokasiHeatmap = <?= json_encode($data_lokasi_heatmap) ?>;
    var tahunAktif = <?= $tahun_aktif ?>;
    
    console.log('Data kantor:', dataKantor);
    console.log('Data lokasi heatmap:', dataLokasiHeatmap);
    
    var map;
    var markers = [];
    var officeMarker;
    
    // Inisialisasi peta
    function initMap() {
        // Default center jika tidak ada data kantor
        var defaultLat = -6.2088;
        var defaultLng = 106.8456;
        var centerLat = dataKantor && dataKantor.lati ? parseFloat(dataKantor.lati) : defaultLat;
        var centerLng = dataKantor && dataKantor.longi ? parseFloat(dataKantor.longi) : defaultLng;
        
        // Buat peta
        map = L.map('heatmap').setView([centerLat, centerLng], 13);
        
        // Tambahkan tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        // Tambahkan marker kantor
        if (dataKantor && dataKantor.lati && dataKantor.longi) {
            var officeIcon = L.divIcon({
                className: 'custom-div-icon',
                html: '<div style="background-color: #007bff; width: 20px; height: 20px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 5px rgba(0,0,0,0.3);"></div>',
                iconSize: [26, 26],
                iconAnchor: [13, 13]
            });
            
            officeMarker = L.marker([centerLat, centerLng], { icon: officeIcon })
                .addTo(map)
                .bindPopup(`
                    <div class="text-center">
                        <h6><i class="fa fa-building text-primary"></i> ${dataKantor.satker || 'Kantor'}</h6>
                        <small class="text-muted">Lat: ${centerLat}, Lng: ${centerLng}</small>
                    </div>
                `);
        }
        
        // Tambahkan circle radius 5km
        if (dataKantor && dataKantor.lati && dataKantor.longi) {
            L.circle([centerLat, centerLng], {
                color: '#007bff',
                fillColor: '#007bff',
                fillOpacity: 0.1,
                radius: 5000 // 5km
            }).addTo(map);
        }
        
        // Render markers lokasi
        renderLocationMarkers();
        
        // Hide loading, show map
        $('#map-loading').hide();
        $('#heatmap').show();
        $('#legend').show();
        
        // Invalidate size untuk memastikan peta render dengan benar
        setTimeout(function() {
            map.invalidateSize();
        }, 100);
    }
    
    // Function untuk render markers lokasi
    function renderLocationMarkers() {
        // Clear existing markers
        markers.forEach(function(marker) {
            map.removeLayer(marker);
        });
        markers = [];
        
        if (!dataLokasiHeatmap || dataLokasiHeatmap.length === 0) {
            return;
        }
        
        // Get mode yang aktif
        var mode = $('input[name="heatmap_mode"]:checked').val();
        var isEfektivitas = mode === 'efektivitas';
        
        // Hitung min/max untuk normalisasi warna
        var values = dataLokasiHeatmap.map(function(item) {
            return isEfektivitas ? parseFloat(item.skor_efektivitas) : parseFloat(item.persentase_konversi);
        });
        
        var minValue = Math.min.apply(Math, values);
        var maxValue = Math.max.apply(Math, values);
        
        console.log('Value range:', minValue, 'to', maxValue, 'Mode:', mode);
        
        // Render setiap lokasi
        dataLokasiHeatmap.forEach(function(item) {
            var lat = parseFloat(item.lati);
            var lng = parseFloat(item.longi);
            
            if (isNaN(lat) || isNaN(lng)) {
                return;
            }
            
            var value = isEfektivitas ? parseFloat(item.skor_efektivitas) : parseFloat(item.persentase_konversi);
            
            // Normalisasi nilai ke range 0-1
            var normalizedValue = maxValue > minValue ? (value - minValue) / (maxValue - minValue) : 0.5;
            
            // Generate warna berdasarkan nilai (merah ke hijau)
            var color = getHeatmapColor(normalizedValue);
            
            // Buat custom marker
            var markerIcon = L.divIcon({
                className: 'custom-div-icon',
                html: `<div style="background-color: ${color}; width: 15px; height: 15px; border-radius: 50%; border: 2px solid white; box-shadow: 0 2px 5px rgba(0,0,0,0.3);"></div>`,
                iconSize: [19, 19],
                iconAnchor: [9.5, 9.5]
            });
            
            // Buat marker
            var marker = L.marker([lat, lng], { icon: markerIcon })
                .addTo(map)
                .bindPopup(`
                    <div>
                        <h6><i class="fa fa-map-marker-alt text-danger"></i> ${item.nama_lokasi}</h6>
                        <hr class="my-2">
                        <div class="row text-center">
                            <div class="col-6">
                                <strong>${item.total_kegiatan}</strong><br>
                                <small>Kegiatan</small>
                            </div>
                            <div class="col-6">
                                <strong>${item.total_calon}</strong><br>
                                <small>Calon</small>
                            </div>
                        </div>
                        <div class="row text-center mt-2">
                            <div class="col-4">
                                <strong>${item.total_closing}</strong><br>
                                <small>Closing</small>
                            </div>
                            <div class="col-4">
                                <strong>${item.persentase_konversi}%</strong><br>
                                <small>Konversi</small>
                            </div>
                            <div class="col-4">
                                <strong>${item.skor_efektivitas}</strong><br>
                                <small>Efektivitas</small>
                            </div>
                        </div>
                    </div>
                `);
            
            markers.push(marker);
        });
    }
    
    // Function untuk generate warna heatmap
    function getHeatmapColor(normalizedValue) {
        // Gradasi dari merah (0) ke kuning (0.5) ke hijau (1)
        var r, g, b;
        
        if (normalizedValue < 0.5) {
            // Merah ke kuning
            r = 255;
            g = Math.round(255 * normalizedValue * 2);
            b = 0;
        } else {
            // Kuning ke hijau
            r = Math.round(255 * (1 - normalizedValue) * 2);
            g = 255;
            b = 0;
        }
        
        return `rgb(${r},${g},${b})`;
    }
    
    // Event handler untuk toggle mode
    $('input[name="heatmap_mode"]').on('change', function() {
        renderLocationMarkers();
    });
    
    // Event handler untuk input tahun dengan Enter key
    $('#filter-tahun').on('keypress', function(e) {
        if (e.which == 13) { // Enter key
            var tahun = $(this).val();

            if (tahun.length == 4 && $.isNumeric(tahun)) {
                // Show loading
                $('#map-loading').show();
                $('#heatmap').hide();
                $('#legend').hide();
                
                $.ajax({
                    url: '<?= base_url('dashboard/cabang/setTahun') ?>',
                    type: 'POST',
                    data: { tahun: tahun },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status == 'success') {
                            // Redirect ke halaman dengan tahun baru untuk reload data
                            window.location.href = `${window.location.pathname}?tahun=${tahun}`;
                        } else {
                            alert('Error: ' + response.message);
                            $('#map-loading').hide();
                            $('#heatmap').show();
                            $('#legend').show();
                        }
                    },
                    error: function() {
                        alert('Terjadi kesalahan saat mengupdate tahun');
                        $('#map-loading').hide();
                        $('#heatmap').show();
                        $('#legend').show();
                    }
                });
            } else {
                alert('Format tahun tidak valid. Gunakan format 4 digit (contoh: 2024)');
            }
        }
    });
    
    // Hanya allow input angka
    $('#filter-tahun').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '');
    });
    
    // Event handler untuk tombol filter (tetap ada untuk fallback)
    $('#btn-filter-tahun').on('click', function() {
        $('#filter-tahun').trigger($.Event('keypress', { which: 13 }));
    });
    
    // Initialize map setelah DOM ready
    setTimeout(function() {
        initMap();
    }, 500);
});
</script>

<?= $this->endSection() ?>
