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

<?= $this->section('title') ?>Dashboard <?= $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">Pusat</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-chart-area"></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">
               <button type="button" id="btn-sync" class="nav-link btn btn-danger" data-url="<?= $link_sync ?>"><i class="fal fa-sync"></i> Sync Data</button>&nbsp;
               </li>

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

<!-- ini bagian jumlah kegiatan promosi, calon nasabah, menjadi nasabah, dan persentase konversi -->
<div class="row">
   <div class="col-sm-6 col-xl-3">
      <div class="p-3 bg-primary-300 rounded overflow-hidden position-relative text-white mb-g">
         <div class="">
               <h3 class="display-4 d-block l-h-n m-0 fw-500">
               <?= $jumlah_kegiatan ?>
               <small class="m-0 l-h-n">Kegiatan Promosi</small>
               </h3>
         </div>
         <i class="fal fa-lightbulb-on position-absolute pos-right pos-bottom opacity-15 mb-n1 mr-n0" style="font-size:6rem"></i>
      </div>
   </div>
   <div class="col-sm-6 col-xl-3">
      <div class="p-3 bg-warning-400 rounded overflow-hidden position-relative text-white mb-g">
         <div class="">
               <h3 class="display-4 d-block l-h-n m-0 fw-500">
               <?= $jumlah_calon ?>
               <small class="m-0 l-h-n">Calon Nasabah</small>
               </h3>
         </div>
         <i class="fal fa-user-clock position-absolute pos-right pos-bottom opacity-15  mb-n1 mr-n1" style="font-size: 6rem;"></i>
      </div>
   </div>
   <div class="col-sm-6 col-xl-3">
      <div class="p-3 bg-success-200 rounded overflow-hidden position-relative text-white mb-g">
         <div class="">
               <h3 class="display-4 d-block l-h-n m-0 fw-500">
               <?= $jumlah_closing ?>
               <small class="m-0 l-h-n">Menjadi Nasabah</small>
               </h3>
         </div>
         <i class="fal fa-user-check position-absolute pos-right pos-bottom opacity-15 mb-n1 mr-n1" style="font-size: 6rem;"></i>
      </div>
   </div>
   <div class="col-sm-6 col-xl-3">
      <div class="p-3 bg-info-200 rounded overflow-hidden position-relative text-white mb-g">
         <div class="">
               <h3 class="display-4 d-block l-h-n m-0 fw-500">
               <?= $persentase_konversi ?>%
               <small class="m-0 l-h-n">Persentase Konversi</small>
               </h3>
         </div>
         <i class="fal fa-globe position-absolute pos-right pos-bottom opacity-15 mb-n1 mr-n4" style="font-size: 6rem;"></i>
      </div>
   </div>
</div>
<!-- end bagian jumlah kegiatan promosi, calon nasabah, menjadi nasabah, dan persentase konversi -->

<!-- chart bulanan -->
<div class="row">
   <div class="col-lg-12 sortable-grid ui-sortable">
      <div id="panel-promo" class="panel">
         <div class="panel-hdr">
            <h2>
               Kegiatan Promosi <span class="fw-300"><i> & Konversi Nasabah</i></span>
            </h2>
            
            <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="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="js-checkbox-toggles" class="d-flex mb-3">
               <div class="custom-control custom-switch mr-2">
                        <input type="checkbox" class="custom-control-input" name="gra-0" id="gra-0" checked="">
                         <label class="custom-control-label" for="gra-0">Kegiatan Promosi</label>
                   </div>
                   <div class="custom-control custom-switch mr-2">
                         <input type="checkbox" class="custom-control-input" name="gra-1" id="gra-1" checked="">
                         <label class="custom-control-label" for="gra-1">Calon Nasabah</label>
                   </div>
                   <div class="custom-control custom-switch mr-2">
                         <input type="checkbox" class="custom-control-input" name="gra-2" id="gra-2" checked="">
                         <label class="custom-control-label" for="gra-2">Menjadi Nasabah</label>
                   </div>
                </div>

                <div id="flot-toggles" class="w-100 mt-4" style="height: 300px; padding: 0px; position: relative;"></div>
             </div>
          </div>
      </div>
   </div>
</div>
<!-- end chart bulanan -->

<!-- heatmap kantor wilayah -->
<div class="row">
   <div class="col-lg-12 sortable-grid ui-sortable">
      <div id="panel-heatmap" class="panel">
         <div class="panel-hdr">
            <h2>
               Heatmap Kantor Wilayah <span class="fw-300"><i>berdasarkan Efektivitas</i></span>
            </h2>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div id="map-container" style="height: 400px; width: 100%;">
                  <div id="wilayah-heatmap" style="height: 100%; width: 100%;"></div>
               </div>
               <div class="mt-3">
                  <div class="d-flex justify-content-center">
                     <div class="mr-4">
                        <span class="badge badge-success mr-1"></span>
                        <small>Efektivitas Tinggi (> 75)</small>
                     </div>
                     <div class="mr-4">
                        <span class="badge badge-warning mr-1"></span>
                        <small>Efektivitas Sedang (25-75)</small>
                     </div>
                     <div>
                        <span class="badge badge-danger mr-1"></span>
                        <small>Efektivitas Rendah (< 25)</small>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<!-- end heatmap kantor wilayah -->

<!-- tabel kantor wilayah -->
<div class="row">
   <div class="col-lg-12 sortable-grid ui-sortable">
      <div id="panel-kwilayah" class="panel">
         <div class="panel-hdr">
            <h2>
               Data Kantor Wilayah <span class="fw-300"><i>Nasional</i></span>
            </h2>
            <div class="panel-toolbar">
               <div class="dropdown">
                  <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="sortDropdown" data-toggle="dropdown">
                     <i class="fal fa-sort-amount-down"></i> Urutkan: Kegiatan
                  </button>
                  <div class="dropdown-menu">
                     <a class="dropdown-item sort-option" href="#" data-sort="total_kegiatan">
                        <i class="fal fa-lightbulb"></i> Kegiatan Promosi
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="total_calon">
                        <i class="fal fa-user-clock"></i> Calon Nasabah
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="total_closing">
                        <i class="fal fa-user-check"></i> Closing Nasabah
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="konversi">
                        <i class="fal fa-percentage"></i> % Konversi
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="efektivitas">
                        <i class="fal fa-chart-line"></i> Efektivitas
                     </a>
                  </div>
               </div>
            </div>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div class="table-responsive">
                  <table class="table table-striped table-hover" id="tabel-wilayah">
                     <thead class="thead-light">
                        <tr>
                           <th width="50">No.</th>
                           <th>Nama Kantor Wilayah</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">Aksi</th>
                        </tr>
                     </thead>
                     <tbody id="tbody-wilayah">
                        <?php if (!empty($data_wilayah)): ?>
                           <?php foreach ($data_wilayah as $index => $wilayah): ?>
                           <tr class="wilayah-row" data-id-wilayah="<?= $wilayah['id_kw'] ?>">
                              <td class="text-center"><?= $index + 1 ?></td>
                              <td><?= esc($wilayah['nama_wilayah']) ?></td>
                              <td class="text-center">
                                 <span class="badge badge-primary"><?= number_format($wilayah['total_kegiatan']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-warning"><?= number_format($wilayah['total_calon']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-success"><?= number_format($wilayah['total_closing']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-info"><?= $wilayah['konversi'] ?>%</span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-secondary"><?= $wilayah['efektivitas'] ?></span>
                              </td>
                              <td class="text-center">
                                 <button class="btn btn-sm btn-outline-info drill-down-btn" 
                                         data-id-wilayah="<?= $wilayah['id_kw'] ?>"
                                         data-nama-wilayah="<?= esc($wilayah['nama_wilayah']) ?>"
                                         title="Drill Down ke Wilayah <?= esc($wilayah['nama_wilayah']) ?>"
                                         data-toggle="tooltip">
                                    <i class="fal fa-drill"></i> Drill Down
                                 </button>
                              </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 wilayah 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>
<!-- end tabel kantor wilayah -->

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

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script src="<?= base_url('smart/dist/js/statistics/flot/flot.bundle.js') ?>"></script>
<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;
            }
            
            // Send AJAX request to setTahun method
            $.ajax({
                url: '<?= base_url('dashboard/pusat/setTahun') ?>',
                type: 'POST',
                data: {
                    tahun: tahun
                },
                dataType: 'json',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend: function() {
                    // Show loading indicator
                    Swal.fire({
                        title: 'Loading...',
                        text: 'Mengubah tahun',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        willOpen: () => {
                            Swal.showLoading();
                        }
                    });
                },
                success: function(response) {
                    if (response.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            // Reload page to show data for new year
                            window.location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: response.message || 'Gagal mengubah tahun',
                            confirmButtonText: 'OK'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', {xhr, status, error});
                    
                    var errorMessage = 'Terjadi kesalahan pada server';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: errorMessage,
                        confirmButtonText: 'OK'
                    });
                }
            });
        }
    });
    
    // Handle sync button click
    $('#btn-sync').click(function() {
        var btn = $(this);
        var url = btn.data('url');
        var originalText = btn.html();
        
        // Disable button and show loading
        btn.prop('disabled', true);
        btn.html('<i class="fal fa-spinner fa-spin"></i> Syncing...');
        
        // Send AJAX POST request
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.status === 'success') {
                    // Show success notification
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: response.message + ' (' + response.total_wilayah + ' wilayah, ' + response.total_cabang_processed + ' cabang diproses)',
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                    // Optionally reload page to show updated data
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                    
                } else if (response.status === 'warning') {
                    // Show warning notification
                    Swal.fire({
                        icon: 'warning',
                        title: 'Peringatan',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                } else {
                    // Show error notification
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message || 'Terjadi kesalahan saat sinkronisasi',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', {xhr, status, error});
                
                var errorMessage = 'Terjadi kesalahan pada server';
                
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                } else if (xhr.status === 500) {
                    errorMessage = 'Internal Server Error';
                } else if (xhr.status === 404) {
                    errorMessage = 'URL tidak ditemukan';
                } else if (xhr.status === 403) {
                    errorMessage = 'Akses ditolak';
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: errorMessage,
                    confirmButtonText: 'OK'
                });
            },
            complete: function() {
                // Re-enable button and restore original text
                btn.prop('disabled', false);
                btn.html(originalText);
            }
        });
    });

    // ========== FLOT CHART DATA BULANAN ==========
    // Data bulanan dari PHP
    var dataBulanan = <?= json_encode($data_bulanan) ?>;
    console.log('Data bulanan pusat:', dataBulanan);
    
    // Persiapan data untuk Flot
    var dataKegiatan = [];
    var dataCalonNasabah = [];
    var dataClosingNasabah = [];
    var labelBulan = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nov', 'Des'];
    
    // Format data untuk Flot
    for (var i = 0; i < dataBulanan.length; i++) {
        var bulan = dataBulanan[i].bulan;
        dataKegiatan.push([bulan, dataBulanan[i].kegiatan_promosi]);
        dataCalonNasabah.push([bulan, dataBulanan[i].calon_nasabah]);
        dataClosingNasabah.push([bulan, dataBulanan[i].closing_nasabah]);
    }

    // Konfigurasi chart
    var chartData = [
        {
            data: dataKegiatan,
            label: "Kegiatan Promosi",
            bars: {
                show: true,
                barWidth: 0.6,
                align: "center"
            },
            color: "#8456c4"
        },
        {
            data: dataCalonNasabah,
            label: "Calon Nasabah",
            lines: {
                show: true,
                lineWidth: 3
            },
            points: {
                show: true,
                radius: 4
            },
            color: "#e2a851"
        },
        {
            data: dataClosingNasabah,
            label: "Menjadi Nasabah",
            lines: {
                show: true,
                lineWidth: 3
            },
            points: {
                show: true,
                radius: 4
            },
            color: "#08d3bf"
        }
    ];

    var chartOptions = {
        series: {
            shadowSize: 0
        },
        xaxis: {
            min: 0.5,
            max: 12.5,
            ticks: [
                [1, "Jan"], [2, "Feb"], [3, "Mar"], [4, "Apr"],
                [5, "Mei"], [6, "Jun"], [7, "Jul"], [8, "Ags"],
                [9, "Sep"], [10, "Okt"], [11, "Nov"], [12, "Des"]
            ],
            tickColor: "rgba(0,0,0,0.15)"
        },
        yaxis: {
            min: 0,
            tickColor: "rgba(0,0,0,0.15)"
        },
        grid: {
            borderWidth: 1,
            borderColor: "rgba(0,0,0,0.15)",
            hoverable: true,
            clickable: true
        },
        legend: {
            show: true,
            position: "ne",
            backgroundColor: "rgba(255,255,255,0.85)"
        },
        tooltip: true,
        tooltipOpts: {
            content: function(label, xval, yval) {
                return "<strong>" + label + "</strong><br>" + 
                       labelBulan[xval] + ": " + yval;
            }
        }
    };

    // Render chart
    var plot = $.plot("#flot-toggles", chartData, chartOptions);

    // Toggle chart series berdasarkan checkbox
    $("#js-checkbox-toggles input").on("change", function() {
        var seriesIndex = parseInt($(this).attr('name').split('-')[1]);
        var series = plot.getData()[seriesIndex];
        
        if ($(this).is(':checked')) {
            series.lines.show = seriesIndex > 0;
            series.points.show = seriesIndex > 0;
            series.bars.show = seriesIndex === 0;
        } else {
            series.lines.show = false;
            series.points.show = false;
            series.bars.show = false;
        }
        
        plot.setData(plot.getData());
        plot.draw();
    });

    // ========== LEAFLET HEATMAP ==========
    var dataKantor = <?= json_encode($data_kantor) ?>;
    var dataWilayahHeatmap = <?= json_encode($data_heatmap_wilayah) ?>;
    console.log('Data kantor pusat:', dataKantor);
    console.log('Data wilayah heatmap:', dataWilayahHeatmap);
    
    // Determine map center
    var centerLat = -6.2088; // Default Jakarta
    var centerLng = 106.8456;
    var initialZoom = 6; // Zoom out more for national view
    
    if (dataKantor && dataKantor.lati && dataKantor.longi) {
        centerLat = parseFloat(dataKantor.lati);
        centerLng = parseFloat(dataKantor.longi);
    }
    
    // Initialize map
    var map = L.map('wilayah-heatmap').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 pusat (center)
    if (dataKantor && dataKantor.lati && dataKantor.longi) {
        var pusatIcon = L.divIcon({
            className: 'custom-div-icon',
            html: '<div style="background-color: purple; width: 30px; height: 30px; border-radius: 50%; border: 4px solid white; box-shadow: 0 4px 8px rgba(0,0,0,0.5);"><div style="color: white; text-align: center; line-height: 22px; font-size: 14px; font-weight: bold;">P</div></div>',
            iconSize: [30, 30],
            iconAnchor: [15, 15]
        });
        
        var pusatMarker = L.marker([centerLat, centerLng], {icon: pusatIcon}).addTo(map);
        pusatMarker.bindPopup('<div class="popup-content"><h6><strong>Kantor Pusat</strong></h6><p>' + (dataKantor.satker || 'Unknown') + '</p></div>');
    }
    
    // Add markers for each wilayah with color based on efektivitas
    if (dataWilayahHeatmap && dataWilayahHeatmap.length > 0) {
        dataWilayahHeatmap.forEach(function(wilayah) {
            if (wilayah.lati && wilayah.longi && wilayah.lati !== '' && wilayah.longi !== '') {
                var lat = parseFloat(wilayah.lati);
                var lng = parseFloat(wilayah.longi);
                var efektivitas = parseFloat(wilayah.skor_efektivitas) || 0;
                
                // Determine marker color based on efektivitas
                var markerColor = 'red'; // default
                if (efektivitas > 75) {
                    markerColor = 'green';
                } else if (efektivitas > 25) {
                    markerColor = 'orange';
                }
                
                // Determine marker label
                var markerLabel = 'R';
                if (efektivitas > 75) {
                    markerLabel = 'T';
                } else if (efektivitas > 25) {
                    markerLabel = 'S';
                }
                
                // Create custom marker icon with letter
                var markerIcon = L.divIcon({
                    className: 'custom-div-icon',
                    html: '<div style="background-color:' + markerColor + '; width: 35px; height: 35px; 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: 29px; font-size: 16px; font-weight: bold;">' + markerLabel + '</div></div>',
                    iconSize: [35, 35],
                    iconAnchor: [17, 17]
                });
                
                // Create marker
                var marker = L.marker([lat, lng], {icon: markerIcon}).addTo(map);
                
                // Create popup content
                var popupContent = '<div class="popup-content">' +
                    '<h6><strong>' + wilayah.nama_wilayah + '</strong></h6>' +
                    '<table class="table table-sm">' +
                    '<tr><td>Kegiatan:</td><td><strong>' + parseInt(wilayah.total_kegiatan).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td>Calon:</td><td><strong>' + parseInt(wilayah.total_calon).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td>Closing:</td><td><strong>' + parseInt(wilayah.total_closing).toLocaleString() + '</strong></td></tr>' +
                    '<tr><td>Konversi:</td><td><strong>' + parseFloat(wilayah.persentase_konversi).toFixed(1) + '%</strong></td></tr>' +
                    '<tr><td>Efektivitas:</td><td><strong>' + parseFloat(wilayah.skor_efektivitas).toFixed(2) + '</strong></td></tr>' +
                    '</table>' +
                    '<button class="btn btn-sm btn-primary drill-down-btn-map" data-id-wilayah="' + wilayah.wilayah_id + '" data-nama-wilayah="' + wilayah.nama_wilayah + '">Drill Down</button>' +
                    '</div>';
                
                marker.bindPopup(popupContent);
            }
        });
        
        // Auto-fit map to show all markers if there are multiple wilayah
        var wilayahMarkers = [];
        map.eachLayer(function(layer) {
            if (layer instanceof L.Marker && layer !== pusatMarker) {
                wilayahMarkers.push(layer);
            }
        });
        
        if (wilayahMarkers.length > 1) {
            var group = new L.featureGroup(wilayahMarkers);
            if (pusatMarker) {
                group.addLayer(pusatMarker);
            }
            map.fitBounds(group.getBounds().pad(0.1));
        } else if (wilayahMarkers.length === 1) {
            // If only one wilayah, center between pusat and wilayah
            if (pusatMarker) {
                var bounds = L.latLngBounds([pusatMarker.getLatLng(), wilayahMarkers[0].getLatLng()]);
                map.fitBounds(bounds.pad(0.3));
            }
        }
    }

    // ========== SORTING TABEL WILAYAH ==========
    var dataWilayahOriginal = <?= json_encode($data_wilayah) ?>;
    var currentSort = 'total_kegiatan';
    var sortLabels = {
        'total_kegiatan': 'Kegiatan',
        'total_calon': 'Calon',
        'total_closing': 'Closing', 
        'konversi': '% Konversi',
        'efektivitas': 'Efektivitas'
    };

    // Handle sorting dropdown
    $('.sort-option').on('click', function(e) {
        e.preventDefault();
        
        var sortBy = $(this).data('sort');
        currentSort = sortBy;
        
        // Update dropdown button text
        $('#sortDropdown').html('<i class="fal fa-sort-amount-down"></i> Urutkan: ' + sortLabels[sortBy]);
        
        // Sort data
        var sortedData = dataWilayahOriginal.slice(); // Copy array
        sortedData.sort(function(a, b) {
            var valA = parseFloat(a[sortBy]) || 0;
            var valB = parseFloat(b[sortBy]) || 0;
            return valB - valA; // Descending order
        });
        
        // Update table
        updateTabelWilayah(sortedData);
    });

    function updateTabelWilayah(data) {
        var tbody = $('#tbody-wilayah');
        tbody.empty();
        
        if (data && data.length > 0) {
            data.forEach(function(wilayah, index) {
                var row = '<tr class="wilayah-row" data-id-wilayah="' + wilayah.id_kw + '">' +
                    '<td class="text-center">' + (index + 1) + '</td>' +
                    '<td>' + wilayah.nama_wilayah + '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-primary">' + parseInt(wilayah.total_kegiatan).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-warning">' + parseInt(wilayah.total_calon).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-success">' + parseInt(wilayah.total_closing).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-info">' + parseFloat(wilayah.konversi).toFixed(1) + '%</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-secondary">' + parseFloat(wilayah.efektivitas).toFixed(2) + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<button class="btn btn-sm btn-outline-info drill-down-btn" ' +
                        'data-id-wilayah="' + wilayah.id_kw + '" ' +
                        'data-nama-wilayah="' + wilayah.nama_wilayah + '" ' +
                        'title="Drill Down ke Wilayah ' + wilayah.nama_wilayah + '" ' +
                        'data-toggle="tooltip">' +
                        '<i class="fal fa-drill"></i> Drill Down' +
                        '</button>' +
                    '</td>' +
                '</tr>';
                
                tbody.append(row);
            });
            
            // Activate tooltips for new buttons
            $('[data-toggle="tooltip"]').tooltip();
        } else {
            tbody.html('<tr><td colspan="8" class="text-center text-muted">' +
                '<i class="fal fa-info-circle"></i> Belum ada data kantor wilayah untuk tahun <?= $tahun_aktif ?>' +
                '<br><small>Silakan lakukan sync data terlebih dahulu</small>' +
                '</td></tr>');
        }
    }

    // Handle drill down button clicks (both in table and map)
    $(document).on('click', '.drill-down-btn, .drill-down-btn-map', function() {
        var idWilayah = $(this).data('id-wilayah');
        var namaWilayah = $(this).data('nama-wilayah');
        
        // Redirect to drill down wilayah page
        Swal.fire({
            title: 'Drill Down',
            text: 'Membuka detail wilayah ' + namaWilayah,
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Ya, Buka',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Redirect to drill down wilayah page
                window.location.href = '<?= base_url('dashboard/pusat/drill-down-wilayah/') ?>' + idWilayah;
            }
        });
    });

    // Double click on table rows for drill down
    $(document).on('dblclick', '.wilayah-row', function() {
        var idWilayah = $(this).data('id-wilayah');
        $('.drill-down-btn[data-id-wilayah="' + idWilayah + '"]').click();
    });

    // Highlight tabel dengan animasi
    $('#tabel-wilayah tbody').on('mouseover', 'tr', function() {
        $(this).addClass('table-active');
    }).on('mouseout', 'tr', function() {
        $(this).removeClass('table-active');
    });

});
</script>

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