<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demografi Per Poli</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css" rel="stylesheet">
    
    <style>
        .nav-pills .nav-link { border-radius: 50px; padding: 10px 20px; font-weight: 500; margin-right: 10px; border: 1px solid #e3e6f0; color: #5a5c69; background-color: #fff; }
        .nav-pills .nav-link.active { background-color: #007bff; color: #fff; border-color: #007bff; }
        .card { border: none; border-radius: 10px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); margin-bottom: 20px;}
        .chart-area { position: relative; height: 350px; width: 100%; }
        /* Style khusus untuk Select2 agar sejajar dengan input bootstrap */
        .select2-container .select2-selection--single { height: 38px !important; border: 1px solid #ced4da; }
        .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 36px; }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height: 36px; }
    </style>
</head>

<body>
<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4">Demografi Pasien Per Poli</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                <li class="breadcrumb-item active">Per Poliklinik</li>
            </ol>

            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <form action="<?= base_url('demousiaperpoli/tampildata') ?>" method="POST" id="formFilterPoli">
                        <input type="hidden" name="active_tab" id="active_tab" value="<?= $this->input->post('active_tab') ?? '#tab-usia-poli' ?>">
                        
                        <div class="row align-items-end">
                            <div class="col-md-2">
                                <label class="small font-weight-bold">TANGGAL AWAL</label>
                                <input type="date" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required>
                            </div>
                            <div class="col-md-2">
                                <label class="small font-weight-bold">TANGGAL AKHIR</label>
                                <input type="date" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label class="small font-weight-bold">PILIH POLIKLINIK</label>
                                <select name="kd_jenispoli" id="kd_jenispoli" class="form-control select2" required>
                                    <option value="" disabled selected>-- Cari Poli --</option>
                                    <?php if(isset($list_poli)) { 
                                        foreach($list_poli as $p) { 
                                            $is_selected = (isset($selected_poli) && $selected_poli == $p->kd_poliklinik) ? 'selected' : '';
                                            
                                            echo "<option value='{$p->kd_poliklinik}' {$is_selected}>{$p->nm_poliklinik}</option>";
                                        }
                                    } ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary"><i class="fas fa-sync-alt"></i> Update Data</button>
                                
                                <button type="button" id="btnDownloadUsia" class="btn btn-success ml-2 tab-download-btn">
                                    <i class="fas fa-file-excel"></i> Download Excel Usia
                                </button>
                                <button type="button" id="btnDownloadGender" class="btn btn-info ml-2 tab-download-btn" style="display: none;">
                                    <i class="fas fa-file-excel"></i> Download Excel Gender
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-toggle="pill" href="#tab-usia-poli"><i class="fas fa-user-clock mr-2"></i>Usia Per Poli</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#tab-gender-poli"><i class="fas fa-venus-mars mr-2"></i>Gender Per Poli</a>
                </li>
            </ul>

            <div class="tab-content">
                
                <div class="tab-pane fade show active" id="tab-usia-poli">
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Grafik Distribusi Usia (<?= $nama_poli_selected ?? 'Semua' ?>)</div>
                                <div class="card-body">
                                    <div class="chart-area"><canvas id="chartUsiaPoli"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Ringkasan Usia</div>
                                <div class="card-body p-0">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light text-center"><tr><th>Kategori Umur</th><th>Jumlah</th></tr></thead>
                                        <tbody id="bodyUsia">
                                            <?php 
                                            // Siapkan array untuk Grafik JS nanti
                                            $chartLabels = [];
                                            $chartData = [];

                                            if(isset($demografi_usia->response) && is_array($demografi_usia->response)) { 
                                                foreach($demografi_usia->response as $u) {
                                                    // Deteksi nama field (umur / kategori)
                                                    $kategori = $u->umur ?? $u->kategori ?? '-';
                                                    $jumlah = $u->qty ?? 0;

                                                    // Simpan data untuk Grafik
                                                    $chartLabels[] = $kategori;
                                                    $chartData[] = $jumlah;
                                            ?>
                                                <tr>
                                                    <td><?= $kategori ?></td>
                                                    <td class="text-center font-weight-bold"><?= $jumlah ?></td>
                                                </tr>
                                            <?php 
                                                } 
                                            } else { 
                                                echo "<tr><td colspan='2' class='text-center'>Data Kosong / Pilih Poli</td></tr>"; 
                                            } 
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-gender-poli">
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary text-center">Proporsi Gender (<?= $nama_poli_selected ?? 'Semua' ?>)</div>
                                <div class="card-body">
                                    <div style="max-width: 350px; margin: auto;"><canvas id="chartGenderPoli"></canvas></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4">
                            <div class="card shadow">
                                <div class="card-header py-3 font-weight-bold text-primary">Ringkasan Gender</div>
                                <div class="card-body p-0">
                                    <table class="table table-sm table-bordered mb-0">
                                        <thead class="bg-light text-center"><tr><th>Jenis Kelamin</th><th>Jumlah</th></tr></thead>
                                        <tbody id="bodyGender">
                                            <?php if(isset($datagender->response)) { 
                                                foreach($datagender->response as $g) { ?>
                                                <tr>
                                                    <td><?= $g->nm_jenis_kelamin ?></td>
                                                    <td class="text-center font-weight-bold"><?= $g->qty ?></td>
                                                </tr>
                                            <?php }} else { echo "<tr><td colspan='2' class='text-center'>Data Kosong/Pilih Poli</td></tr>"; } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<script>
    $(document).ready(function() {

        // 1. Inisialisasi Select2
        $('.select2').select2({
            theme: 'bootstrap4',
            placeholder: "Cari Poliklinik...",
            allowClear: true
        });

     // 2. Fungsi Load Poli (AJAX untuk mengisi dropdown saat pertama load atau jika kosong)
        // PENTING: Hanya jalankan jika dropdown kosong (belum diisi oleh PHP)
        if ($('#kd_jenispoli option').length <= 1) { 
            const url_ref_poli = "<?= base_url('demousiaperpoli/refpoliklinik') ?>"; 
            const dropdown = $('#kd_jenispoli');

            $.ajax({
                url: url_ref_poli,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    if (data && data.response && Array.isArray(data.response)) {
                        $.each(data.response, function(index, poli) {
                            var option = new Option(poli.nm_poliklinik, poli.kd_poliklinik);
                            dropdown.append(option);
                        });
                        // Jika ada data old input (dari PHP), set selected
                        var selectedVal = "<?= $selected_poli ?? '' ?>";
                        if(selectedVal) { dropdown.val(selectedVal).trigger('change'); }
                    }
                }
            });
        }

        // 3. Logic Tab Active & Update Button
        $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
            var target = $(e.target).attr("href");
            $('#active_tab').val(target);
            updateViewComponents(target);
        });

        var lastTab = $('#active_tab').val();
        if (lastTab) {
            $('.nav-pills a[href="' + lastTab + '"]').tab('show');
            updateViewComponents(lastTab);
        }

        function updateViewComponents(tabId) {
            $('.tab-download-btn').hide();
            if(tabId === '#tab-usia-poli') {
                $('#formFilterPoli').attr('action', "<?= base_url('demousiaperpoli/tampildatausia') ?>");
                $('#btnDownloadUsia').show();
            } else {
                $('#formFilterPoli').attr('action', "<?= base_url('demousiaperpoli/tampildatagender') ?>");
                $('#btnDownloadGender').show();
            }
        }

        // ==========================================
        // 4. RENDER CHART USIA (DATA DARI PHP CONTROLLER)
        // ==========================================
        
        // Siapkan Data dari PHP
        <?php 
            $labelsUsia = [];
            $dataUsia = [];
            if(isset($demografi_usia->response) && is_array($demografi_usia->response)) {
                foreach($demografi_usia->response as $u) {
                    $labelsUsia[] = $u->umur ?? $u->kategori ?? '-';
                    $dataUsia[] = (int)($u->qty ?? 0);
                }
            }
        ?>

        const ctxUsia = document.getElementById('chartUsiaPoli').getContext('2d');
        const labelsUsiaJs = <?= json_encode($labelsUsia) ?>;
        const dataUsiaJs = <?= json_encode($dataUsia) ?>;

        // Jika data kosong, buat data dummy agar chart tetap muncul (kosong)
        if(labelsUsiaJs.length === 0) {
            // Opsional: Tampilkan pesan "Data Kosong"
        }

        new Chart(ctxUsia, {
            type: 'bar',
            data: {
                labels: labelsUsiaJs.length > 0 ? labelsUsiaJs : ['Data Kosong'],
                datasets: [{
                    label: 'Jumlah Pasien',
                    data: dataUsiaJs.length > 0 ? dataUsiaJs : [0],
                    backgroundColor: '#4e73df'
                }]
            },
            options: { 
                maintainAspectRatio: false, 
                scales: { 
                    y: { 
                        beginAtZero: true,
                        ticks: { stepSize: 1 } // Agar sumbu Y bilangan bulat
                    } 
                } 
            }
        });

        // ==========================================
        // 5. RENDER CHART GENDER (DATA DARI PHP CONTROLLER)
        // ==========================================
        
        <?php 
            $labelsGender = [];
            $dataGender = [];
            if(isset($datagender->response) && is_array($datagender->response)) {
                foreach($datagender->response as $g) {
                    $labelsGender[] = $g->nm_jenis_kelamin;
                    $dataGender[] = (int)($g->qty ?? 0);
                }
            }
        ?>

        // Cek apakah elemen canvas ada (karena mungkin kita ada di controller usia)
        const canvasGender = document.getElementById('chartGenderPoli');
        if(canvasGender) {
            const ctxGender = canvasGender.getContext('2d');
            const labelsGenderJs = <?= json_encode($labelsGender) ?>;
            const dataGenderJs = <?= json_encode($dataGender) ?>;

            new Chart(ctxGender, {
                type: 'doughnut',
                data: {
                    labels: labelsGenderJs,
                    datasets: [{
                        data: dataGenderJs,
                        backgroundColor: ['#36b9cc', '#e74a3b', '#1cc88a']
                    }]
                },
                options: { maintainAspectRatio: false, cutout: '70%' }
            });
        }

        // 6. Logic Download
        $('#btnDownloadUsia').click(function(){ downloadFile("<?= base_url('demousiaperpoli/unduhdataperpoliusia') ?>"); });
        $('#btnDownloadGender').click(function(){ downloadFile("<?= base_url('demousiaperpoli/unduhdataperpoligender') ?>"); });

        function downloadFile(baseUrl) {
            var ta = $('input[name="tanggal_awal"]').val();
            var tak = $('input[name="tanggal_akhir"]').val();
            var poli = $('#kd_jenispoli').val();
            if(!poli) { alert("Pilih Poliklinik dulu!"); return; }
            window.location.href = baseUrl + "?TANGGAL_AWAL=" + ta + "&TANGGAL_AKHIR=" + tak + "&KD_POLIKLINIK=" + poli;
        }
    });
</script>
</body>
</html>