<?= $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">Area</li>
   <li class="breadcrumb-item"><?= esc($kantor_cabang->satker) ?></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-building"></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 btn btn-secondary" href="<?= $link_back ?>">
                     <i class="fal fa-arrow-left"></i> Kembali ke Area
                  </a>
               </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 -->

<!-- flot utama -->
<div class="row">
   <div class="col-lg-12 sortable-grid ui-sortable">
      <div id="panel-10" 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>

<div class="row">
   <!-- Panel Chart Top 5 Karyawan -->
   <div class="col-xl-6">
      <div id="panel-karyawan" class="panel">
         <div class="panel-hdr">
            <h2>Leaderboard <span class="fw-300"><i>Promoter</i></span></h2>
            <div class="panel-toolbar ml-2">
               <h5 class="m-0">
                  <span class="badge badge-info fw-400 l-h-n">
                     Top 5
                  </span>
               </h5>
            </div>
            <div class="panel-toolbar">
               <button class="btn btn-panel waves-effect waves-themed" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button>
            </div>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div class="table-responsive">
                  <table class="table table-clean">
                     <thead>
                        <tr>
                           <th colspan="2">Karyawan</th>
                           <th class="text-center">Kegiatan</th>
                           <th class="text-center">Calon</th>
                           <th class="text-center">Closing</th>
                           <th class="text-center">% Konversi</th>
                           <th class="text-center">Efektivitas</th>
                         </tr>
                     </thead>
                     <tbody id="karyawan-efektif-table">
                     </tbody>
                  </table>
               </div>
            </div>
         </div>
      </div>
   </div><!-- end col-xl-6 -->

   <!-- Panel Chart Produk -->
   <div class="col-xl-6">
      <div id="panel-produk" class="panel">
         <div class="panel-hdr">
            <h2>Produk <span class="fw-300"><i>Paling Diminati</i></span></h2>
            <div class="panel-toolbar">
               <button class="btn btn-panel waves-effect waves-themed" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button>
            </div>
         </div>
         <div class="panel-container show">
             <div class="panel-content">
                <div id="produk-horizontal-bar" style="height: 400px; width: 100%;"></div>
             </div>
          </div>
       </div>
   </div><!-- end col-xl-6 -->
</div>

<div class="row">
   <!-- Panel Chart Kategori Lokasi -->
   <div class="col-xl-6">
      <div id="panel-lokasi" class="panel">
         <div class="panel-hdr">
            <h2>Kategori <span class="fw-300"><i>Lokasi</i></span></h2>
            <div class="panel-toolbar">
               <button class="btn btn-panel waves-effect waves-themed" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button>
            </div>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div id="lokasi-pie" style="height: 300px; width: 100%;"></div>
               <!-- Tabel Efektivitas -->
               <div class="mt-3">
                  <h6 class="text-muted mb-2">📊 Analisis Efektivitas Kategori Lokasi</h6>
                  <div class="table-responsive">
                     <table class="table table-sm table-hover">
                        <thead>
                        <tr>
                        <th>Kategori</th>
                        <th>Kegiatan</th>
                        <th>Calon</th>
                           <th>Closing</th>
                              <th>% Konversi</th>
                               <th>Efektivitas</th>
                            </tr>
                         </thead>
                        <tbody id="efektivitas-lokasi-table">
                        </tbody>
                     </table>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div><!-- end col-xl-6 -->

   <!-- Panel Chart Jenis Promosi -->
   <div class="col-xl-6">
      <div id="panel-jprom" class="panel">
         <div class="panel-hdr">
            <h2>Jenis <span class="fw-300"><i>Promosi</i></span></h2>
            <div class="panel-toolbar">
               <button class="btn btn-panel waves-effect waves-themed" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button>
            </div>
         </div>
         <div class="panel-container show">
            <div class="panel-content">
               <div id="jenis-promosi-pie" style="height: 300px; width: 100%;"></div>
               <!-- Tabel Efektivitas -->
               <div class="mt-3">
                  <h6 class="text-muted mb-2">📊 Analisis Efektivitas Jenis Promosi</h6>
                  <div class="table-responsive">
                     <table class="table table-sm table-hover" id="efektivitas-table">
                        <thead class="thead-light">
                           <tr>
                              <th>Jenis Kegiatan</th>
                              <th class="text-center">Kegiatan</th>
                              <th class="text-center">Calon</th>
                              <th class="text-center">Closing</th>
                              <th class="text-center">% Konversi</th>
                              <th class="text-center">Efektivitas</th>
                           </tr>
                        </thead>
                        <tbody id="efektivitas-tbody">
                           <!-- Will be populated by JavaScript -->
                        </tbody>
                     </table>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div><!-- end col-xl-6 -->
</div>
<?= $this->endSection() ?>

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script src="<?= base_url('smart/dist/js/statistics/flot/flot.bundle.js') ?>"></script>
<script>
$(document).ready(function() {
    // Event handler untuk input tahun
    $('#cari-tahun').on('keypress', function(e) {
        if (e.which == 13) { // Enter key
            var tahun = $(this).val();
            
            if (tahun.length == 4 && $.isNumeric(tahun)) {
                $.ajax({
                    url: '<?= base_url('dashboard/area/setTahun') ?>',
                    type: 'POST',
                    data: {
                        tahun: tahun
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status == 'success') {
                            // Reload halaman untuk update data
                            location.reload();
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function() {
                        alert('Terjadi kesalahan sistem');
                    }
                });
            } else {
                alert('Format tahun tidak valid. Gunakan format 4 digit (contoh: 2025)');
            }
        }
    });
    
    // Hanya allow input angka
    $('#cari-tahun').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '');
    });

    // Data bulanan dari PHP
    var dataBulanan = <?= json_encode($data_bulanan) ?>;
    
    // 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();
    });

    // ========== JENIS PROMOSI PIE CHART ==========
    var dataJenisPromosiPie = <?= json_encode($data_jenis_promosi_pie) ?>;
    
    if (dataJenisPromosiPie && dataJenisPromosiPie.length > 0) {
        var pieData = [];
        var colors = ["#8456c4", "#e2a851", "#08d3bf", "#dc3545", "#28a745", "#ffc107", "#17a2b8", "#6f42c1", "#fd7e14", "#20c997"];
        
        for (var i = 0; i < dataJenisPromosiPie.length; i++) {
            var item = dataJenisPromosiPie[i];
            var jenisPromosi = item.jenis_promosi || 'Jenis Promosi ' + (i + 1);
            var proporsiPie = parseFloat(item.proporsi_pie) || 0;
            
            pieData.push({
                label: jenisPromosi + " (" + proporsiPie + "%)",
                data: proporsiPie,
                color: colors[i % colors.length]
            });
        }
        
        var pieOptions = {
            series: {
                pie: {
                    show: true,
                    radius: 1,
                    label: {
                        show: true,
                        radius: 2/3,
                        formatter: function(label, series) {
                            return '<div style="font-size:8pt; text-align:center; padding:2px; color:white;">' + 
                                   Math.round(series.percent) + '%</div>';
                        },
                        threshold: 0.1
                    }
                }
            },
            legend: {
                show: true,
                position: "ne"
            },
            grid: {
                hoverable: true,
                clickable: true
            }
        };
        
        $.plot("#jenis-promosi-pie", pieData, pieOptions);
    } else {
        $("#jenis-promosi-pie").html('<div class="text-center p-4"><h5 class="text-muted">Belum ada data untuk tahun ini</h5></div>');
    }

    // ========== TABEL JENIS PROMOSI ==========
    var dataJenisPromosi = <?= json_encode($data_jenis_promosi) ?>;
    
    if (dataJenisPromosi && dataJenisPromosi.length > 0) {
        var dataWithEfektivitas = dataJenisPromosi.map(function(item) {
            var konversi = parseFloat(item.persentase_konversi) || 0;
            var jumlahKegiatan = parseInt(item.total_kegiatan) || 1;
            var skorEfektivitas = jumlahKegiatan > 0 ? (konversi / jumlahKegiatan) * 10 : 0;
            
            return {
                jenis_promosi: item.jenis_promosi,
                total_kegiatan: item.total_kegiatan,
                total_calon: item.total_calon,
                total_closing: item.total_closing,
                persentase_konversi: item.persentase_konversi,
                skor_efektivitas: skorEfektivitas.toFixed(2)
            };
        });
        
        dataWithEfektivitas.sort(function(a, b) {
            return parseFloat(b.persentase_konversi) - parseFloat(a.persentase_konversi);
        });
        
        // Cari yang paling efektif (skor efektivitas tertinggi)
        var maxEfektivitas = Math.max.apply(Math, dataWithEfektivitas.map(function(item) {
            return parseFloat(item.skor_efektivitas);
        }));
        
        // Cari yang paling tidak efektif (skor efektivitas terendah)
        var minEfektivitas = Math.min.apply(Math, dataWithEfektivitas.map(function(item) {
            return parseFloat(item.skor_efektivitas);
        }));
        
        var tableRows = '';
        dataWithEfektivitas.forEach(function(item, index) {
            var isEfektif = parseFloat(item.skor_efektivitas) === maxEfektivitas;
            var isTidakEfektif = parseFloat(item.skor_efektivitas) === minEfektivitas && dataWithEfektivitas.length > 1;
            
            var rowClass = '';
            if (isEfektif) {
                rowClass = 'table-success';
            } else if (isTidakEfektif) {
                rowClass = 'table-danger';
            }
            
            var efektivitasBadge = '';
            if (isEfektif) {
                efektivitasBadge = '<span class="badge badge-success">★ ' + item.skor_efektivitas + '</span>';
            } else if (isTidakEfektif) {
                efektivitasBadge = '<span class="badge badge-danger">⚠ ' + item.skor_efektivitas + '</span>';
            } else {
                efektivitasBadge = item.skor_efektivitas;
            }
            
            var labelBadge = '';
            if (isEfektif) {
                labelBadge = ' <span class="badge badge-sm badge-success ml-1">EFEKTIF</span>';
            } else if (isTidakEfektif) {
                labelBadge = ' <span class="badge badge-sm badge-danger ml-1">KURANG EFEKTIF</span>';
            }
            
            tableRows += '<tr class="' + rowClass + '">' +
                '<td><strong>' + item.jenis_promosi + '</strong>' + labelBadge + '</td>' +
                '<td class="text-center">' + item.total_kegiatan + '</td>' +
                '<td class="text-center">' + item.total_calon + '</td>' +
                '<td class="text-center"><strong>' + item.total_closing + '</strong></td>' +
                '<td class="text-center"><span class="badge badge-primary">' + item.persentase_konversi + '%</span></td>' +
                '<td class="text-center">' + efektivitasBadge + '</td>' +
                '</tr>';
        });
        
        $('#efektivitas-tbody').html(tableRows);
    } else {
        $('#efektivitas-tbody').html('<tr><td colspan="6" class="text-center text-muted"><i>Tidak ada data untuk ditampilkan</i></td></tr>');
    }

    // ========== PRODUK HORIZONTAL BAR CHART ==========
    var dataProdukDiminati = <?= json_encode($data_produk_diminati) ?>;
    
    if (dataProdukDiminati && dataProdukDiminati.length > 0) {
        var produkData = [];
        var produkLabels = [];
        var reversedData = dataProdukDiminati.slice().reverse();
        
        for (var i = 0; i < reversedData.length; i++) {
            var item = reversedData[i];
            var konversi = parseFloat(item.persentase_konversi) || 0;
            produkData.push([konversi, i]);
            produkLabels.push([i, item.nama_produk]);
        }
        
        var horizontalBarData = [{
            data: produkData,
            color: "#f39c12",
            bars: {
                show: true,
                horizontal: true,
                barWidth: 0.6,
                align: "center"
            }
        }];
        
        var horizontalBarOptions = {
            series: { shadowSize: 0 },
            xaxis: {
                min: 0,
                tickFormatter: function(val) { return val + "%"; },
                tickColor: "rgba(0,0,0,0.15)"
            },
            yaxis: {
                ticks: produkLabels,
                tickColor: "rgba(0,0,0,0.15)"
            },
            grid: {
                borderWidth: 1,
                borderColor: "rgba(0,0,0,0.15)",
                hoverable: true
            },
            tooltip: true,
            tooltipOpts: {
                content: function(label, xval, yval, flotItem) {
                    var originalIndex = dataProdukDiminati.length - 1 - yval;
                    var item = dataProdukDiminati[originalIndex];
                    return "<strong>" + item.nama_produk + "</strong><br>" + 
                           "Konversi: " + item.persentase_konversi + "%<br>" +
                           "Total Calon: " + item.total_calon + " calon<br>" +
                           "Total Closing: " + item.total_closing + " nasabah";
                }
            }
        };
        
        $.plot("#produk-horizontal-bar", horizontalBarData, horizontalBarOptions);
    } else {
        $("#produk-horizontal-bar").html('<div class="text-center p-4"><h5 class="text-muted">Belum ada data produk untuk tahun ini</h5></div>');
    }

    // ========== KATEGORI LOKASI PIE CHART ==========
    var dataKategoriLokasiPie = <?= json_encode($data_kategori_lokasi_pie) ?>;
    
    if (dataKategoriLokasiPie && dataKategoriLokasiPie.length > 0) {
        var pieDataLokasi = [];
        var colorsLokasi = ["#28a745", "#dc3545", "#ffc107", "#17a2b8", "#6f42c1", "#fd7e14", "#20c997"];
        
        for (var i = 0; i < dataKategoriLokasiPie.length; i++) {
            var item = dataKategoriLokasiPie[i];
            pieDataLokasi.push({
                label: item.kategori_lokasi + " (" + item.proporsi_pie + "%)",
                data: parseFloat(item.proporsi_pie),
                color: colorsLokasi[i % colorsLokasi.length]
            });
        }
        
        var pieOptionsLokasi = {
            series: {
                pie: {
                    show: true,
                    radius: 1,
                    label: {
                        show: true,
                        radius: 2/3,
                        formatter: function(label, series) {
                            return '<div style="font-size:8pt; text-align:center; padding:2px; color:white;">' + 
                                   Math.round(series.percent) + '%</div>';
                        },
                        threshold: 0.1
                    }
                }
            },
            legend: { show: true, position: "ne" },
            grid: { hoverable: true, clickable: true }
        };
        
        $.plot("#lokasi-pie", pieDataLokasi, pieOptionsLokasi);
    } else {
        $("#lokasi-pie").html('<div class="text-center p-4"><h5 class="text-muted">Belum ada data untuk tahun ini</h5></div>');
    }

    // ========== TABEL KATEGORI LOKASI ==========
    var dataKategoriLokasi = <?= json_encode($data_kategori_lokasi) ?>;
    
    if (dataKategoriLokasi && dataKategoriLokasi.length > 0) {
        var dataWithEfektivitasLokasi = dataKategoriLokasi.map(function(item) {
            var konversi = parseFloat(item.persentase_konversi) || 0;
            var jumlahKegiatan = parseInt(item.total_kegiatan) || 1;
            var skorEfektivitas = jumlahKegiatan > 0 ? (konversi / jumlahKegiatan) * 10 : 0;
            
            return {
                kategori_lokasi: item.kategori_lokasi,
                total_kegiatan: item.total_kegiatan,
                total_calon: item.total_calon,
                total_closing: item.total_closing,
                persentase_konversi: item.persentase_konversi,
                skor_efektivitas: skorEfektivitas.toFixed(2)
            };
        });
        
        dataWithEfektivitasLokasi.sort(function(a, b) {
            return parseFloat(b.persentase_konversi) - parseFloat(a.persentase_konversi);
        });
        
        // Cari yang paling efektif (skor efektivitas tertinggi)
        var maxEfektivitasLokasi = Math.max.apply(Math, dataWithEfektivitasLokasi.map(function(item) {
            return parseFloat(item.skor_efektivitas);
        }));
        
        // Cari yang paling tidak efektif (skor efektivitas terendah)
        var minEfektivitasLokasi = Math.min.apply(Math, dataWithEfektivitasLokasi.map(function(item) {
            return parseFloat(item.skor_efektivitas);
        }));
        
        var tableRowsLokasi = '';
        dataWithEfektivitasLokasi.forEach(function(item, index) {
            var isEfektif = parseFloat(item.skor_efektivitas) === maxEfektivitasLokasi;
            var isTidakEfektif = parseFloat(item.skor_efektivitas) === minEfektivitasLokasi && dataWithEfektivitasLokasi.length > 1;
            
            var rowClass = '';
            if (isEfektif) {
                rowClass = 'table-success';
            } else if (isTidakEfektif) {
                rowClass = 'table-danger';
            }
            
            var efektivitasBadge = '';
            if (isEfektif) {
                efektivitasBadge = '<span class="badge badge-success">★ ' + item.skor_efektivitas + '</span>';
            } else if (isTidakEfektif) {
                efektivitasBadge = '<span class="badge badge-danger">⚠ ' + item.skor_efektivitas + '</span>';
            } else {
                efektivitasBadge = item.skor_efektivitas;
            }
            
            var labelBadge = '';
            if (isEfektif) {
                labelBadge = ' <span class="badge badge-sm badge-success ml-1">EFEKTIF</span>';
            } else if (isTidakEfektif) {
                labelBadge = ' <span class="badge badge-sm badge-danger ml-1">KURANG EFEKTIF</span>';
            }
            
            // Truncate category name to 20 characters
            var kategoriName = item.kategori_lokasi.length > 20 ? 
                item.kategori_lokasi.substr(0, 20) + '...' : item.kategori_lokasi;
            
            tableRowsLokasi += '<tr class="' + rowClass + '">' +
                '<td><strong>' + kategoriName + '</strong>' + labelBadge + '</td>' +
                '<td class="text-center">' + item.total_kegiatan + '</td>' +
                '<td class="text-center">' + item.total_calon + '</td>' +
                '<td class="text-center"><strong>' + item.total_closing + '</strong></td>' +
                '<td class="text-center"><span class="badge badge-primary">' + item.persentase_konversi + '%</span></td>' +
                '<td class="text-center">' + efektivitasBadge + '</td>' +
                '</tr>';
        });
        
        $('#efektivitas-lokasi-table').html(tableRowsLokasi);
    } else {
        $('#efektivitas-lokasi-table').html('<tr><td colspan="6" class="text-center text-muted"><i>Tidak ada data untuk ditampilkan</i></td></tr>');
    }

    // ========== TOP 5 KARYAWAN EFEKTIF ==========
    var dataKaryawanEfektif = <?= json_encode($data_karyawan_efektif) ?>;
    
    if (dataKaryawanEfektif && dataKaryawanEfektif.length > 0) {
        var tableRowsKaryawan = '';
        
        dataKaryawanEfektif.forEach(function(item, index) {
            var fotoKaryawan = item.foto_karyawan && item.foto_karyawan !== '' ? 
                '/files/avatar/' + item.foto_karyawan : 
                '/assets/img/demo/avatars/avatar-admin.png';
            
            var namaKaryawan = item.nama_karyawan.length > 15 ? 
                item.nama_karyawan.substr(0, 15) + '...' : 
                item.nama_karyawan;
            
            var nipKaryawan = item.nip_karyawan || '-';
            var efektivitasBadge = '<span class="badge badge-secondary">' + item.skor_efektivitas + '</span>';
            var rowClass = index === 0 ? 'table-success' : '';
            
            tableRowsKaryawan += '<tr class="' + rowClass + '">' +
                '<td class="text-center" style="width: 60px;">' +
                    '<img src="' + fotoKaryawan + '" alt="' + item.nama_karyawan + '" ' +
                    'class="img-thumbnail rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">' +
                '</td>' +
                '<td>' +
                    '<div class="d-flex flex-column">' +
                        '<strong>' + namaKaryawan + '</strong>' +
                        '<small class="text-muted">' + nipKaryawan + '</small>' +
                    '</div>' +
                '</td>' +
                '<td class="text-center">' + item.total_kegiatan + '</td>' +
                '<td class="text-center">' + item.total_calon + '</td>' +
                '<td class="text-center"><strong>' + item.total_closing + '</strong></td>' +
                '<td class="text-center"><span class="badge badge-primary">' + item.persentase_konversi + '%</span></td>' +
                '<td class="text-center">' + efektivitasBadge + '</td>' +
                '</tr>';
        });
        
        $('#karyawan-efektif-table').html(tableRowsKaryawan);
    } else {
        $('#karyawan-efektif-table').html('<tr><td colspan="7" class="text-center text-muted"><i>Belum ada data karyawan untuk tahun ini</i></td></tr>');
    }
    
    console.log('Detail cabang dashboard loaded for: <?= esc($kantor_cabang->satker) ?>');
});
</script>

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