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

<?= $this->section('title') ?>Heatmap Wilayah <?= $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"><?= ucfirst($segment1) ?></li>
   <li class="breadcrumb-item">Wilayah</li>
   <li class="breadcrumb-item active">Heatmap</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-0">
         <div class="mr-2">
            <ul class="nav nav-pills border-bottom-0" role="tablist">
               <li class="nav-item">
                  <a class="nav-link btn btn-primary" href="<?= $link_back ?>"><i class="fal fa-arrow-left"></i> Kembali</a>
               </li>
            </ul>
         </div>
         <div></div>
      </div>
   </div>
</div>

<!-- info kantor wilayah -->
<div class="row">
   <div class="col-lg-12">
      <div class="alert alert-info border-faded bg-transparent text-info">
         <div class="d-flex align-items-center">
            <div class="alert-icon">
               <span class="icon-stack icon-stack-md">
                  <i class="base base-6 icon-stack-3x opacity-100 color-info-500"></i>
                  <i class="base base-10 icon-stack-2x opacity-100 color-info-300 fa-flip-vertical"></i>
                  <i class="fal fa-building icon-stack-1x opacity-100 color-white"></i>
               </span>
            </div>
            <div class="flex-1">
               <span class="h5">Kantor Wilayah: <?= esc($data_kantor->satker ?? 'Unknown') ?></span>
               <br>
               Koordinat: <?= esc($data_kantor->lati ?? '-') ?>, <?= esc($data_kantor->longi ?? '-') ?>
            </div>
         </div>
      </div>
   </div>
</div>

<!-- heatmap full size -->
<div class="row">
   <div class="col-lg-12">
      <div id="panel-heatmap-full" class="panel">
         <div class="panel-hdr">
            <h2>
               Heatmap Kantor Area <span class="fw-300"><i>berdasarkan Efektivitas - Tahun <?= $tahun_aktif ?></i></span>
            </h2>
            <div class="panel-toolbar">
               <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="cari-tahun" class="form-control form-control-sm pl-5" maxlength="4" placeholder="Cari Tahun" value="<?= $tahun_aktif ?>">
               </div>
            </div>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div id="map-container-full" style="height: 600px; width: 100%;">
                  <div id="area-heatmap-full" style="height: 100%; width: 100%;"></div>
               </div>
               <div class="mt-3">
                  <div class="row">
                     <div class="col-md-6">
                        <h6>Legenda Efektivitas:</h6>
                        <div class="d-flex flex-wrap">
                           <div class="mr-4 mb-2">
                              <span class="badge badge-success mr-1" style="width: 15px; height: 15px; border-radius: 50%;"></span>
                              <small>Efektivitas Tinggi (> 75)</small>
                           </div>
                           <div class="mr-4 mb-2">
                              <span class="badge badge-warning mr-1" style="width: 15px; height: 15px; border-radius: 50%;"></span>
                              <small>Efektivitas Sedang (25-75)</small>
                           </div>
                           <div class="mb-2">
                              <span class="badge badge-danger mr-1" style="width: 15px; height: 15px; border-radius: 50%;"></span>
                              <small>Efektivitas Rendah (< 25)</small>
                           </div>
                        </div>
                     </div>
                     <div class="col-md-6">
                        <h6>Keterangan:</h6>
                        <ul class="list-unstyled mb-0">
                           <li><small><i class="fal fa-info-circle text-info"></i> Klik marker untuk melihat detail area</small></li>
                           <li><small><i class="fal fa-mouse-pointer text-primary"></i> Gunakan kontrol zoom untuk memperbesar/memperkecil</small></li>
                           <li><small><i class="fal fa-search text-success"></i> Masukkan tahun di kotak pencarian untuk mengubah data</small></li>
                        </ul>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

<!-- statistik summary -->
<div class="row">
   <div class="col-lg-12">
      <div id="panel-statistik" class="panel">
         <div class="panel-hdr">
            <h2>
               Statistik Area <span class="fw-300"><i>per Wilayah</i></span>
            </h2>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div class="table-responsive">
                  <table class="table table-striped table-hover" id="tabel-statistik-area">
                     <thead class="thead-light">
                        <tr>
                           <th width="50">No.</th>
                           <th>Nama Kantor Area</th>
                           <th class="text-center" width="100">Kegiatan</th>
                           <th class="text-center" width="100">Calon</th>
                           <th class="text-center" width="100">Closing</th>
                           <th class="text-center" width="120">% Konversi</th>
                           <th class="text-center" width="120">Efektivitas</th>
                           <th class="text-center" width="80">Status</th>
                        </tr>
                     </thead>
                     <tbody id="tbody-statistik-area">
                        <?php if (!empty($data_heatmap_area)): ?>
                           <?php foreach ($data_heatmap_area as $index => $area): ?>
                           <tr>
                              <td class="text-center"><?= $index + 1 ?></td>
                              <td><?= esc($area['nama_area']) ?></td>
                              <td class="text-center">
                                 <span class="badge badge-primary"><?= number_format($area['total_kegiatan']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-warning"><?= number_format($area['total_calon']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-success"><?= number_format($area['total_closing']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-info"><?= $area['persentase_konversi'] ?>%</span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-secondary"><?= $area['skor_efektivitas'] ?></span>
                              </td>
                              <td class="text-center">
                                 <?php 
                                    $efektivitas = floatval($area['skor_efektivitas']);
                                    if ($efektivitas > 75): 
                                 ?>
                                    <span class="badge badge-success"><i class="fal fa-thumbs-up"></i> Tinggi</span>
                                 <?php elseif ($efektivitas > 25): ?>
                                    <span class="badge badge-warning"><i class="fal fa-minus-circle"></i> Sedang</span>
                                 <?php else: ?>
                                    <span class="badge badge-danger"><i class="fal fa-thumbs-down"></i> Rendah</span>
                                 <?php endif; ?>
                              </td>
                           </tr>
                           <?php endforeach; ?>
                        <?php else: ?>
                           <tr>
                              <td colspan="8" class="text-center text-muted">
                                 <i class="fal fa-info-circle"></i> Belum ada data kantor area untuk tahun <?= $tahun_aktif ?>
                                 <br><small>Silakan lakukan sync data terlebih dahulu</small>
                              </td>
                           </tr>
                        <?php endif; ?>
                     </tbody>
                  </table>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

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

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />

<script>
$(document).ready(function() {
    // Handle tahun search input enter key
    $('#cari-tahun').keypress(function(e) {
        if (e.which == 13) { // Enter key
            var tahun = $(this).val().trim();
            
            // Validate tahun input
            if (tahun === '') {
                Swal.fire({
                    icon: 'warning',
                    title: 'Peringatan',
                    text: 'Silakan masukkan tahun',
                    confirmButtonText: 'OK'
                });
                return;
            }
            
            if (!/^\d{4}$/.test(tahun)) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Format tahun harus 4 digit angka',
                    confirmButtonText: 'OK'
                });
                return;
            }
            
            // Redirect to same page with tahun parameter
            window.location.href = '<?= base_url('dashboard/wilayah/hmap') ?>?tahun=' + tahun;
        }
    });

    // ========== LEAFLET HEATMAP FULL SIZE ==========
    var dataKantor = <?= json_encode($data_kantor) ?>;
    var dataAreaHeatmap = <?= json_encode($data_heatmap_area) ?>;
    
    console.log('Data kantor wilayah:', dataKantor);
    console.log('Data area heatmap:', dataAreaHeatmap);
    
    // Determine map center
    var centerLat = -6.2088; // Default Jakarta
    var centerLng = 106.8456;
    var initialZoom = 10;
    
    if (dataKantor && dataKantor.lati && dataKantor.longi) {
        centerLat = parseFloat(dataKantor.lati);
        centerLng = parseFloat(dataKantor.longi);
    }
    
    // Initialize map
    var map = L.map('area-heatmap-full').setView([centerLat, centerLng], initialZoom);
    
    // Add tile layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 18
    }).addTo(map);
    
    // Add marker for kantor wilayah (center)
    if (dataKantor && dataKantor.lati && dataKantor.longi) {
        var wilayahIcon = L.divIcon({
            className: 'custom-div-icon',
            html: '<div style="background-color: blue; width: 25px; height: 25px; border-radius: 50%; border: 3px solid white; box-shadow: 0 3px 6px rgba(0,0,0,0.4);"><div style="color: white; text-align: center; line-height: 19px; font-size: 12px; font-weight: bold;">W</div></div>',
            iconSize: [25, 25],
            iconAnchor: [12, 12]
        });
        
        var wilayahMarker = L.marker([centerLat, centerLng], {icon: wilayahIcon}).addTo(map);
        wilayahMarker.bindPopup('<div class="popup-content"><h6><strong>Kantor Wilayah</strong></h6><p>' + (dataKantor.satker || 'Unknown') + '</p></div>');
    }
    
    // Add markers for each area with color based on efektivitas
    var areaMarkers = [];
    if (dataAreaHeatmap && dataAreaHeatmap.length > 0) {
        dataAreaHeatmap.forEach(function(area) {
            if (area.lati && area.longi && area.lati !== '' && area.longi !== '') {
                var lat = parseFloat(area.lati);
                var lng = parseFloat(area.longi);
                var efektivitas = parseFloat(area.skor_efektivitas) || 0;
                
                // Determine marker color based on efektivitas
                var markerColor = 'red'; // default
                var markerLabel = 'R';
                if (efektivitas > 75) {
                    markerColor = 'green';
                    markerLabel = 'T';
                } else if (efektivitas > 25) {
                    markerColor = 'orange';
                    markerLabel = 'S';
                }
                
                // Create custom marker icon with letter
                var markerIcon = L.divIcon({
                    className: 'custom-div-icon',
                    html: '<div style="background-color:' + markerColor + '; width: 30px; height: 30px; border-radius: 50%; border: 3px solid white; box-shadow: 0 3px 6px rgba(0,0,0,0.4);"><div style="color: white; text-align: center; line-height: 24px; font-size: 14px; font-weight: bold;">' + markerLabel + '</div></div>',
                    iconSize: [30, 30],
                    iconAnchor: [15, 15]
                });
                
                // Create marker
                var marker = L.marker([lat, lng], {icon: markerIcon}).addTo(map);
                areaMarkers.push(marker);
                
                // Create popup content
                var popupContent = '<div class="popup-content">' +
                    '<h6><strong>' + area.nama_area + '</strong></h6>' +
                    '<table class="table table-sm table-borderless">' +
                    '<tr><td style="padding: 2px;">Kegiatan:</td><td style="padding: 2px;"><strong>' + parseInt(area.total_kegiatan).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td style="padding: 2px;">Calon:</td><td style="padding: 2px;"><strong>' + parseInt(area.total_calon).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td style="padding: 2px;">Closing:</td><td style="padding: 2px;"><strong>' + parseInt(area.total_closing).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td style="padding: 2px;">Konversi:</td><td style="padding: 2px;"><strong>' + parseFloat(area.persentase_konversi).toFixed(1) + '%</strong></td></tr>' +
                    '<tr><td style="padding: 2px;">Efektivitas:</td><td style="padding: 2px;"><strong>' + parseFloat(area.skor_efektivitas).toFixed(2) + '</strong></td></tr>' +
                    '</table>' +
                    '<div class="text-center mt-2">' +
                    '<button class="btn btn-sm btn-primary drill-down-btn-map" data-id-area="' + area.area_id + '" data-nama-area="' + area.nama_area + '">Drill Down</button>' +
                    '</div>' +
                    '</div>';
                
                marker.bindPopup(popupContent, {
                    maxWidth: 300,
                    className: 'custom-popup'
                });
            }
        });
        
        // Auto-fit map to show all markers if there are multiple areas
        if (areaMarkers.length > 1) {
            var group = new L.featureGroup(areaMarkers);
            if (wilayahMarker) {
                group.addLayer(wilayahMarker);
            }
            map.fitBounds(group.getBounds().pad(0.1));
        } else if (areaMarkers.length === 1) {
            // If only one area, center between wilayah and area
            if (wilayahMarker) {
                var bounds = L.latLngBounds([wilayahMarker.getLatLng(), areaMarkers[0].getLatLng()]);
                map.fitBounds(bounds.pad(0.3));
            }
        }
    }

    // Handle drill down button clicks in map popups
    $(document).on('click', '.drill-down-btn-map', function() {
        var idArea = $(this).data('id-area');
        var namaArea = $(this).data('nama-area');
        
        // Redirect to area dashboard with specific area ID
        Swal.fire({
            title: 'Drill Down',
            text: 'Membuka dashboard area ' + namaArea,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Ya, Buka',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Redirect to area dashboard
                window.open('<?= base_url('dashboard/area') ?>', '_blank');
            }
        });
    });

    // Add map controls info
    map.on('load', function() {
        console.log('Map loaded successfully');
    });

    // Add zoom event handler
    map.on('zoomend', function() {
        console.log('Current zoom level: ' + map.getZoom());
    });

});
</script>

<style>
.custom-popup .leaflet-popup-content-wrapper {
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}

.custom-popup .leaflet-popup-content {
    margin: 12px;
    min-width: 200px;
}

.custom-popup .table-sm td {
    border: none;
    padding: 2px 4px;
    font-size: 12px;
}

.leaflet-control-zoom a {
    color: #333;
    background-color: rgba(255,255,255,0.9);
}

.leaflet-control-zoom a:hover {
    background-color: rgba(255,255,255,1);
}
</style>

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