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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instalasi Rawat Jalan</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://cdn.datatables.net/1.13.4/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    
    <style>
        .card { border: 1px solid #e3e6f0; border-radius: 8px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); }
        .form-control-sm { height: calc(1.5em + 0.5rem + 2px); padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        
        /* Loading Overlay yang Menutup Layar dengan Rapi */
        #loadingOverlay { 
            position: fixed; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 100%; 
            background: rgba(255,255,255,0.8); /* Background putih transparan */
            z-index: 9999; /* Pastikan di atas segalanya */
            display: none; /* Default sembunyi */
            justify-content: center; 
            align-items: center; 
            flex-direction: column;
        }
        
        /* Agar tabel rapi dengan rowspan */
        th, td { white-space: nowrap; vertical-align: middle !important; }
        .valign-middle { vertical-align: middle !important; background-color: #fff; }
    </style>
</head>

<body class="bg-light">

    <div id="loadingOverlay">
        <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;"></div>
        <div class="mt-3 font-weight-bold text-primary" style="font-size: 1.2rem;">Sedang Memuat Data...</div>
    </div>

    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4 mt-4">
                <h1 class="h3 mb-2 text-gray-800">Rawat Jalan Poli Konsul</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                    <li class="breadcrumb-item active">Data Poli Konsul</li>
                </ol>

                <div class="card mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-filter mr-1"></i> Filter Data Poli Konsul</h6>
                    </div>
                    <div class="card-body">
                        <form id="filterFormPO"> 
                            <div class="row align-items-end">
                                <div class="col-md-3">
                                    <div class="form-group mb-0">
                                        <label class="small mb-1 font-weight-bold">Tanggal Awal</label>
                                        <input type="date" id="tgl_awal" name="TANGGAL_AWAL" class="form-control form-control-sm" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group mb-0">
                                        <label class="small mb-1 font-weight-bold">Tanggal Akhir</label>
                                        <input type="date" id="tgl_akhir" name="TANGGAL_AKHIR" class="form-control form-control-sm" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group mb-0 d-flex">
                                        <button type="submit" class="btn btn-primary btn-sm mr-2 flex-fill">
                                            <i class="fas fa-search"></i> Tampilkan
                                        </button>
                                        <button type="button" id="btnDownloadpoli" class="btn btn-success btn-sm flex-fill" style="display: none;">
                                            <i class="fas fa-file-excel"></i> <span id="lblDownload">Download</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-body">
                        <div id="tableContainer" class="table-responsive">
                            <div class="text-center text-muted py-5">Silakan filter data terlebih dahulu.</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="py-4 bg-light mt-auto">
            <div class="container-fluid px-4">
                <div class="small text-muted text-center">Copyright &copy; IT RSU ANANDA PURWOKERTO 2024</div>
            </div>
        </footer>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.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.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>

<script>
    $(document).ready(function() {
        
        // 1. Set Default Date (Hari ini)
        const today = new Date().toISOString().split('T')[0];
        $('#tgl_awal').val(today);
        $('#tgl_akhir').val(today);

        // 2. Handle Form Submit (AJAX)
        $('#filterFormPO').on('submit', function(e) {
            e.preventDefault(); 
            
            let tglAwal = $('#tgl_awal').val();
            let tglAkhir = $('#tgl_akhir').val();

            // Tampilkan Loading Overlay (ID: loadingOverlay)
            $('#loadingOverlay').css('display', 'flex').show(); 
            
            // Sembunyikan elemen lain sementara
            $('#tableContainer').hide();
            $('#btnDownloadpoli').hide();

            $.ajax({
                url: '<?= base_url("polikonsul/tampildata") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir
                },
                dataType: 'json',
                success: function(data) {
                    // PERBAIKAN DI SINI: Gunakan ID #loadingOverlay
                    $('#loadingOverlay').hide();
                    
                    if (data && data.response && Array.isArray(data.response) && data.response.length > 0) {
                        
                        if ($.fn.DataTable.isDataTable('#dataTablePO')) {
                            $('#dataTablePO').DataTable().destroy();
                        }

                        // Generate Tabel Normal (Semua kolom terisi)
                        let html = `<table id="dataTablePO" class="table table-bordered table-striped table-sm w-100" style="white-space: nowrap;">
                            <thead class="thead-dark">
                                <tr>
                                    <th style="vertical-align: middle;">Nama DPJP</th>
                                    <th>Kd Poliklinik</th>
                                    <th>Nama Konsul</th>
                                    <th>Jumlah Konsul</th>
                                    <th>Nama Dokter Tujuan</th>
                                </tr>
                            </thead>
                            <tbody>`;
                        
                        data.response.forEach(item => {
                            html += `<tr>
                                     <td>${item.dpjp}</td>
                                     <td>${item.kd_poliklinik}</td>
                                     <td>${item.nm_sifat_konsul}</td>
                                     <td class="text-center">${item.jumlah_konsul}</td>
                                     <td>${item.nm_dokter}</td>
                                   </tr>`;
                        });

                        html += `</tbody></table>`;
                        
                        $('#tableContainer').html(html).show();

                        // Init DataTables dengan Logic Merge (Rowspan)
                        $('#dataTablePO').DataTable({
                            "language": { "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Indonesian.json" },
                            "pageLength": 50,
                            "scrollX": true,
                            "ordering": false, // Matikan sorting agar merge tidak pecah
                            "drawCallback": function(settings) {
                                var api = this.api();
                                var rows = api.rows({ page: 'current' }).nodes();
                                var last = null;
                                var lastCell = null;

                                // Loop Kolom DPJP (Index 0)
                                api.column(0, { page: 'current' }).data().each(function(group, i) {
                                    var currentCell = $(rows).eq(i).find('td:eq(0)');
                                    
                                    if (last === group) {
                                        currentCell.remove(); // Hapus sel duplikat
                                        if (lastCell) {
                                            var oldRowspan = lastCell.attr('rowspan') || 1;
                                            lastCell.attr('rowspan', parseInt(oldRowspan) + 1);
                                            lastCell.css('vertical-align', 'middle');
                                            lastCell.css('background-color', '#fff');
                                        }
                                    } else {
                                        last = group;
                                        lastCell = currentCell;
                                        lastCell.css('vertical-align', 'middle');
                                    }
                                });
                            }
                        });

                        $('#lblDownload').text('Download Data');
                        $('#btnDownloadpoli').data('mode', 'rekap').show();

                    } else {
                        $('#tableContainer').html('<div class="alert alert-info text-center">Tidak ada data ditemukan.</div>').show();
                    }
                },
                error: function(xhr, status, error) {
                    // Pastikan loading hilang jika error
                    $('#loadingOverlay').hide();
                    console.error(error);
                    let msg = xhr.responseText ? xhr.responseText : "Gagal mengambil data.";
                    $('#tableContainer').html(`<div class="alert alert-danger text-center">Error: ${msg}</div>`).show();
                }
            });
        });

        // 3. Tombol Download
        $('#btnDownloadpoli').on('click', function() {
            let tglAwal = $('#tgl_awal').val();
            let tglAkhir = $('#tgl_akhir').val();
            let downloadUrl = `<?= base_url("polikonsul/unduhdata") ?>?TANGGAL_AWAL=${tglAwal}&TANGGAL_AKHIR=${tglAkhir}`;
            window.location.href = downloadUrl;
        });

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