<?= $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="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>
               <!--li class="nav-item">
                  <a class="nav-link btn btn-primary" href="#">Heatmap <i class="fal fa-arrow-right"></i></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-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 flot utama -->

<!-- tabel kantor cabang -->
<div class="row">
   <div class="col-lg-12 sortable-grid ui-sortable">
      <div id="panel-kacab" class="panel">
         <div class="panel-hdr">
            <h2>
               Data Kantor Cabang <span class="fw-300"><i>per Area</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="kegiatan">
                        <i class="fal fa-lightbulb"></i> Kegiatan Promosi
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="calon">
                        <i class="fal fa-user-clock"></i> Calon Nasabah
                     </a>
                     <a class="dropdown-item sort-option" href="#" data-sort="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-cabang">
                     <thead class="thead-light">
                        <tr>
                           <th width="50">No.</th>
                           <th>Nama Kantor</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-cabang">
                        <?php if (!empty($data_cabang)): ?>
                           <?php foreach ($data_cabang as $index => $cabang): ?>
                           <tr>
                              <td class="text-center"><?= $index + 1 ?></td>
                              <td><?= esc($cabang['nama_kantor']) ?></td>
                              <td class="text-center">
                                 <span class="badge badge-primary"><?= number_format($cabang['kegiatan']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-warning"><?= number_format($cabang['calon']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-success"><?= number_format($cabang['closing']) ?></span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-info"><?= $cabang['konversi'] ?>%</span>
                              </td>
                              <td class="text-center">
                                 <span class="badge badge-secondary"><?= $cabang['efektivitas'] ?></span>
                              </td>
                              <td class="text-center">
                                 <a href="<?= base_url('dashboard/area/detail-cabang/' . $cabang['id_kc']) ?>" 
                                    class="btn btn-sm btn-outline-info" 
                                    title="Lihat Detail <?= esc($cabang['nama_kantor']) ?>"
                                    data-toggle="tooltip">
                                    Detail
                                 </a>
                              </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 cabang 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 cabang -->

<?= $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() {
    // 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/area/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_cabang + ' 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 area:', 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();
    });

    // ========== SORTING TABEL CABANG ==========
    var dataCabangOriginal = <?= json_encode($data_cabang) ?>;
    var currentSort = 'kegiatan';
    var sortLabels = {
        'kegiatan': 'Kegiatan',
        'calon': 'Calon',
        '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 = dataCabangOriginal.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
        updateTabelCabang(sortedData);
    });

    function updateTabelCabang(data) {
        var tbody = $('#tbody-cabang');
        tbody.empty();
        
        if (data && data.length > 0) {
            data.forEach(function(cabang, index) {
                var row = '<tr>' +
                    '<td class="text-center">' + (index + 1) + '</td>' +
                    '<td>' + cabang.nama_kantor + '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-primary">' + parseInt(cabang.kegiatan).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-warning">' + parseInt(cabang.calon).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-success">' + parseInt(cabang.closing).toLocaleString() + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-info">' + parseFloat(cabang.konversi).toFixed(1) + '%</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<span class="badge badge-secondary">' + parseFloat(cabang.efektivitas).toFixed(2) + '</span>' +
                    '</td>' +
                    '<td class="text-center">' +
                        '<a href="<?= base_url("dashboard/area/detail-cabang/") ?>' + cabang.id_kc + '" ' +
                        'class="btn btn-sm btn-outline-info" ' +
                        'title="Lihat Detail ' + cabang.nama_kantor + '" ' +
                        'data-toggle="tooltip">' +
                        '<i class="fal fa-eye"></i> Detail' +
                        '</a>' +
                    '</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 cabang untuk tahun <?= $tahun_aktif ?>' +
                '<br><small>Silakan lakukan sync data terlebih dahulu</small>' +
                '</td></tr>');
        }
    }

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

});
</script>

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