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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rekap Demografi Pasien</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    
    <style>
        /* Custom Style untuk Tab agar lebih cantik */
        .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: #0d6efd; color: #fff; border-color: #0d6efd; }
        .card { border: none; border-radius: 10px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); margin-bottom: 20px;}
        .table-responsive { margin-top: 15px; }
    </style>
</head>

<body>
<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4" id="judulPasien">Rekap Data Demografi Pasien</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li>
                <li class="breadcrumb-item active">Rekap Demografi</li>
            </ol>

            <div class="card mb-4">
                <div class="card-body">
                    <form id="filterForm" class="row g-3 align-items-end">
                        <input type="hidden" id="active_tab" value="rajal"> <div class="col-md-3">
                            <label for="tgl_awal" class="form-label fw-bold">Tanggal Awal</label>
                            <input type="date" id="tanggal_awal" name="TGL_AWAL" class="form-control" value="<?= $tgl_awal ?>" required />
                        </div>
                        <div class="col-md-3">
                            <label for="tgl_akhir" class="form-label fw-bold">Tanggal Akhir</label>
                            <input type="date" id="tanggal_akhir" name="TGL_AKHIR" class="form-control" value="<?= $tgl_akhir ?>" required />
                        </div>
                        <div class="col-md-6">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> Tampilkan Data</button>
                            <button type="button" id="downloadButton" class="btn btn-success ms-2" style="display: none;"><i class="fas fa-file-excel"></i> Download Excel</button>
                        </div>
                    </form>
                </div>
            </div>

            <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="tab-rajal-btn" data-bs-toggle="pill" data-bs-target="#tab-rajal" type="button" role="tab">Rawat Jalan</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-ranap-btn" data-bs-toggle="pill" data-bs-target="#tab-ranap" type="button" role="tab">Rawat Inap</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-igd-btn" data-bs-toggle="pill" data-bs-target="#tab-igd" type="button" role="tab">IGD</button>
                </li>
            </ul>

            <div class="tab-content" id="pills-tabContent">
                
                <div id="loadingIcon" style="display: none; text-align: center; padding: 20px;">
                    <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                </div>

                <div class="tab-pane fade show active" id="tab-rajal" role="tabpanel">
                    <div class="card">
                        <div class="card-header fw-bold text-primary">Tabel Rekap Rawat Jalan</div>
                        <div class="card-body">
                            <div class="table-responsive" id="containerRajal">
                                <p class="text-center text-muted">Silakan klik "Tampilkan Data" untuk melihat data.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-ranap" role="tabpanel">
                    <div class="card">
                        <div class="card-header fw-bold text-success">Tabel Rekap Rawat Inap</div>
                        <div class="card-body">
                            <div class="table-responsive" id="containerRanap">
                                <p class="text-center text-muted">Silakan klik "Tampilkan Data" untuk melihat data.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-igd" role="tabpanel">
                    <div class="card">
                        <div class="card-header fw-bold text-danger">Tabel Rekap IGD</div>
                        <div class="card-body">
                            <div class="table-responsive" id="containerIGD">
                                <p class="text-center text-muted">Silakan klik "Tampilkan Data" untuk melihat data.</p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </main>
    <footer class="py-4 bg-light mt-auto">
        <div class="container-fluid px-4">
            <div class="small">Copyright &copy; By IT RSU Ananda Purwokerto 2024</div>
        </div>
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>

<script>
    $(document).ready(function() {
        
        // 1. DETEKSI PERPINDAHAN TAB
        $('button[data-bs-toggle="pill"]').on('shown.bs.tab', function (e) {
            let targetId = $(e.target).attr("data-bs-target"); // #tab-rajal, #tab-ranap, dll
            
            // Set active tab value
            if(targetId === '#tab-rajal') $('#active_tab').val('rajal');
            else if(targetId === '#tab-ranap') $('#active_tab').val('ranap');
            else if(targetId === '#tab-igd') $('#active_tab').val('igd');

            // Opsional: Sembunyikan tombol download saat pindah tab sebelum load data
            $('#downloadButton').hide();
        });

        // 2. EVENT SUBMIT FILTER
        $('#filterForm').on('submit', function(event) {
            event.preventDefault();
            
            const activeTab = $('#active_tab').val();
            const tglAwal = $('#tanggal_awal').val();
            const tglAkhir = $('#tanggal_akhir').val();

            // Tentukan URL dan Container ID berdasarkan Tab Aktif
            // PERHATIAN: GANTI URL DI BAWAH INI DENGAN ROUTE CONTROLLER ANDA YANG SEBENARNYA
            let urlAPI = '';
            let containerId = '';

            if(activeTab === 'rajal') {
                urlAPI = '<?= base_url("demorekap/tampildatarajal") ?>';
                containerId = '#containerRajal';
            } 
            else if(activeTab === 'ranap') {
                // Ganti dengan route Ranap Anda
                urlAPI = '<?= base_url("demorekap/tampildataranap") ?>'; 
                containerId = '#containerRanap';
            } 
            else if(activeTab === 'igd') {
                // Ganti dengan route IGD Anda
                urlAPI = '<?= base_url("demorekap/tampildataigd") ?>'; 
                containerId = '#containerIGD';
            }

            // Mulai Proses AJAX
            $('#loadingIcon').show();
            $(containerId).html(''); // Kosongkan container
            $('#downloadButton').hide();

            $.ajax({
                url: urlAPI,
                type: 'POST',
                data: { TANGGAL_AWAL: tglAwal, TANGGAL_AKHIR: tglAkhir },
                success: function(response) {
                    $('#loadingIcon').hide();
                    try {
                        const data = JSON.parse(response);
                        renderTable(data, containerId);
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $(containerId).html('<p class="text-danger text-center">Gagal memproses data JSON.</p>');
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide();
                    console.error("AJAX Error: ", error);
                    $(containerId).html('<p class="text-danger text-center">Terjadi kesalahan koneksi server.</p>');
                }
            });
        });

        // 3. FUNGSI RENDER TABEL (Reusable)
        function renderTable(data, containerId) {
            if (data && Array.isArray(data.response) && data.response.length > 0) {
                let list = data.response;
                
                // Header Tabel (Asumsi kolom sama untuk semua, jika beda bisa dikondisikan)
                let html = `
                    <table class="table table-striped table-bordered display nowrap" style="width:100%">
                        <thead class="table-dark">
                            <tr>
                                <th>Nama Dokter</th>
                                <th>Total</th>
                                <th>Umum</th>
                                <th>Asuransi</th>
                                <th>BPJS</th>
                                <th>Baru</th>
                                <th>Lama</th>
                                <th>L</th>
                                <th>P</th>
                                <th>Dari Inap</th>
                                <th>Dari Rajal</th>
                                <th>Datang Sendiri</th>
                                <th>Ruj. Fas. Rehab</th>
                                <th>Ruj. FKRL</th>
                                <th>Ruj. FKTP</th>
                                <th>Ruj. Dr. Spesialis</th>
                                <th>Lain-lain</th>
                            </tr>
                        </thead>
                        <tbody>
                `;

                list.forEach(item => {
                    html += `
                        <tr>
                            <td>${item.nm_dokter}</td>
                            <td>${item.total}</td>
                            <td>${item.umum}</td>
                            <td>${item.asuransi}</td>
                            <td>${item.bpjs}</td>
                            <td>${item.pasien_baru}</td>
                            <td>${item.pasien_lama}</td>
                            <td>${item.laki_laki}</td>
                            <td>${item.perempuan}</td>
                            <td>${item.dari_rawat_inap}</td>
                            <td>${item.dari_rawat_jalan}</td>
                            <td>${item.datang_sendiri}</td>
                            <td>${item.rujukan_fasilitas_rehab}</td>
                            <td>${item.rujukan_fkrl}</td>
                            <td>${item.rujukan_fktp}</td>
                            <td>${item.rujukan_dokter_spesialis}</td>
                            <td>${item.lain_lain}</td>
                        </tr>
                    `;
                });

                html += '</tbody></table>';
                $(containerId).html(html);

                // Inisialisasi DataTable pada tabel yang baru dibuat
                $(containerId + ' table').DataTable({
                    "order": [[ 2, "asc" ]],
                    "scrollX": true // Aktifkan scroll horizontal jika kolom banyak
                });

                $('#downloadButton').show(); // Munculkan tombol download
            } else {
                $(containerId).html('<div class="alert alert-warning text-center">Tidak ada data ditemukan.</div>');
            }
        }

        // 4. EVENT DOWNLOAD
        $('#downloadButton').on('click', function() {
            const activeTab = $('#active_tab').val();
            const tglAwal = $('#tanggal_awal').val();
            const tglAkhir = $('#tanggal_akhir').val();
            let downloadUrl = '';

            // Tentukan URL Download berdasarkan Tab
            if(activeTab === 'rajal') {
                downloadUrl = `<?= base_url("demorekap/unduhrajal") ?>`;
            } else if (activeTab === 'ranap') {
                downloadUrl = `<?= base_url("demorekap/unduhranap") ?>`; // Ganti sesuai route Anda
            } else if (activeTab === 'igd') {
                downloadUrl = `<?= base_url("demorekap/unduhigd") ?>`; // Ganti sesuai route Anda
            }

            window.location.href = `${downloadUrl}?TANGGAL_AWAL=${tglAwal}&TANGGAL_AKHIR=${tglAkhir}`;
        });

    });
</script>
</body>
</html>