<style>
    /* 1. MENCEGAH HALAMAN MELAR KE KANAN */
    body {
        overflow-x: hidden !important;
        width: 100%;
        background-color: #f4f6f9;
    }

    /* 2. KUNCI PERBAIKAN: MENGATASI BUG TERGENCET SB ADMIN DI HP */
    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
            width: 100% !important;
        }
    }

    table.dataTable {
        width: 100% !important;
        margin: 0 auto;
        clear: both;
        border-collapse: collapse;
    }

    .filter-wrapper {
        background-color: #ffffff;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        border: 1px solid #e0e4e8;
    }

    /* --- CSS PERBAIKAN TAMPILAN TABEL SUMMARY (KHUSUS UMUM) --- */
    .summary-table-container {
        border: 1px solid #dee2e6;
        border-radius: .25rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, .075);
        background-color: #fff;
    }

    .summary-table-container table {
        margin-bottom: 0;
    }

    .summary-table-container thead th {
        position: sticky;
        top: 0;
        background-color: #f8f9fa;
        z-index: 1;
        font-size: 0.85rem;
        border-bottom: 1px solid #ccc !important;
    }

    .summary-table-container .table td,
    .summary-table-container .table th {
        padding: 0.5rem 1.25rem;
        font-size: 0.875rem;
        vertical-align: middle;
    }

    .summary-table-container .bank-name-column {
        border-right: 1px solid #dee2e6;
    }

    /* --- AKHIR CSS SUMMARY --- */

    .daily-chart-wrapper {
        position: relative;
        width: 100%;
        height: 320px;
        max-height: 320px;
        overflow: visible;
    }

    .daily-chart-wrapper canvas {
        width: 100% !important;
        height: 100% !important;
    }

    /* Penyesuaian layar HP */
    @media (max-width: 768px) {
        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 15px;
        }

        .btn-group-custom button {
            width: 100%;
        }

        .daily-chart-wrapper {
            height: 260px;
            max-height: 260px;
        }

        .detail-header-controls {
            flex-direction: column;
            align-items: stretch !important;
            gap: 10px;
        }
    }

    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
    }

    /* DESAIN TAB MENJADI KOTAK */
    .nav-tabs-custom {
        flex-wrap: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        white-space: nowrap;
        -webkit-overflow-scrolling: touch;
        border-bottom: 1px solid #dee2e6;
        margin-bottom: 20px;
    }

    .nav-tabs-custom .nav-link {
        color: #495057;
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 6px 6px 0 0;
        margin-right: 5px;
        font-weight: 600;
        padding: 10px 20px;
        transition: background-color 0.3s, color 0.3s;
    }

    .nav-tabs-custom .nav-link:hover {
        background-color: #e9ecef;
    }

    .nav-tabs-custom .nav-link.active {
        color: #0d6efd;
        background-color: #ffffff;
        border-color: #dee2e6 #dee2e6 #ffffff;
    }

    /* --- MODERN SLIDE SWITCH CSS (KHUSUS ASURANSI TAHUNAN) --- */
    .switch-wrapper {
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        height: 100%;
        padding-bottom: 2px;
    }

    .switch {
        position: relative;
        display: inline-block;
        width: 70px;
        height: 38px;
        margin-right: 15px;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #17a2b8;
        transition: .4s;
        border-radius: 38px;
        box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    .slider:before {
        position: absolute;
        content: "\f554";
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
        height: 30px;
        width: 30px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #17a2b8;
        font-size: 16px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    input:checked+.slider {
        background-color: #dc3545;
    }

    input:focus+.slider {
        box-shadow: 0 0 1px #dc3545;
    }

    input:checked+.slider:before {
        transform: translateX(32px);
        content: "\f236";
        color: #dc3545;
    }

    #labelSwitchTahunan {
        font-weight: 600;
        font-size: 1rem;
        color: #17a2b8;
        transition: color 0.3s ease;
        margin-top: 5px;
        display: inline-block;
        vertical-align: middle;
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4 py-4">

            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="mb-0 font-weight-bold text-dark">Rekap Keuangan SIRUS</h2>
                    <ol class="breadcrumb bg-transparent p-0 mt-2 mb-0">
                        <li class="breadcrumb-item"><a href="index.html" class="text-decoration-none">Dashboard</a></li>
                        <li class="breadcrumb-item active">Tampilan Data Rekap & Detail</li>
                    </ol>
                </div>
            </div>

            <ul class="nav nav-tabs nav-tabs-custom" id="rekapTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="bpjs-tab" data-bs-toggle="tab" data-bs-target="#tab-bpjs" type="button" role="tab">REKAP BPJS</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="umum-tab" data-bs-toggle="tab" data-bs-target="#tab-umum" type="button" role="tab">REKAP UMUM</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="asuransi-tab" data-bs-toggle="tab" data-bs-target="#tab-asuransi" type="button" role="tab">REKAP ASURANSI</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tahunan-tab" data-bs-toggle="tab" data-bs-target="#tab-tahunan" type="button" role="tab">REKAP ASURANSI TAHUNAN</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="all-tab" data-bs-toggle="tab" data-bs-target="#tab-all" type="button" role="tab">REKAP BPJS & NON-BPJS</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="homecare-tab" data-bs-toggle="tab" data-bs-target="#tab-homecare" type="button" role="tab">REKAP HOMECARE</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="bpjsksm-tab" data-bs-toggle="tab" data-bs-target="#tab-bpjsksm" type="button" role="tab">REKAP BPJS PER-KSM</button>
                </li>
            </ul>

            <div class="tab-content" id="rekapTabsContent">

                <div class="tab-pane fade show active" id="tab-bpjs" role="tabpanel">
                    <div class="filter-wrapper mb-4">
                        <form id="formBpjs">
                            <div class="row g-3 align-items-end">
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label class="form-label text-muted font-weight-bold small mb-1">TANGGAL AWAL</label>
                                    <input type="date" id="tglAwalBpjs" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label class="form-label text-muted font-weight-bold small mb-1">TANGGAL AKHIR</label>
                                    <input type="date" id="tglAkhirBpjs" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-3">
                                    <label class="form-label text-muted font-weight-bold small mb-1">JENIS PASIEN</label>
                                    <select id="jenisPasienBpjs" class="form-select custom-select shadow-sm" required>
                                        <option value="" disabled <?= empty($kd_jenis_pasien) ? 'selected' : '' ?>>Pilih Jenis Pasien</option>
                                        <option value="1" <?= ($kd_jenis_pasien == '1') ? 'selected' : '' ?>>Rawat Jalan</option>
                                        <option value="2" <?= ($kd_jenis_pasien == '2') ? 'selected' : '' ?>>Rawat Inap</option>
                                        <option value="3" <?= ($kd_jenis_pasien == '3') ? 'selected' : '' ?>>IGD</option>
                                    </select>
                                </div>
                                <div class="col-12 col-md-3 col-lg-5">
                                    <div class="btn-group-custom">
                                        <button type="submit" class="btn btn-primary px-4 shadow-sm font-weight-bold"><i class="fas fa-search me-1"></i> Tampilkan Rekap</button>
                                        <button type="button" id="btnDownloadBpjs" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel Rekap</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="col-md-12 mb-3 px-0" id="chartButtonsBpjs" style="display:none;">
                        <div class="d-flex flex-wrap gap-2 p-2 bg-white rounded shadow-sm border">
                            <button type="button" class="btn btn-sm btn-primary active metric-btn-bpjs" data-metric="jumlah">
                                <i class="fas fa-users me-1"></i> Jumlah Pasien
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-success metric-btn-bpjs" data-metric="tarif_bpjs">
                                <i class="fas fa-file-invoice-dollar me-1"></i> Tarif BPJS
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-warning metric-btn-bpjs" data-metric="tarif_rs">
                                <i class="fas fa-hospital me-1"></i> Tarif RS
                            </button>
                            <div class="border-right mx-2 d-none d-md-block"></div>
                            <button type="button" id="btnDetailBpjs" class="btn btn-sm btn-outline-secondary font-weight-bold">
                                <i class="fas fa-list-alt me-1"></i> Detail Tagihan
                            </button>
                        </div>
                    </div>

                    <div id="resultBpjs" class="card border-0 shadow-sm mb-4" style="border-radius: 12px; overflow:hidden; display: none;">
                        <div class="card-body p-0 p-md-3">
                            <div id="loadingBpjs" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                                <p class="text-muted mt-2 font-weight-bold">Memproses data BPJS...</p>
                            </div>

                            <div id="chartSectionBpjs" class="mb-4" style="display: none;">
                                <div class="card border-0">
                                    <div class="card-body pb-0 text-center text-md-left">
                                        <h5 class="card-title text-secondary font-weight-bold mb-4">Grafik Pendapatan & Pasien per DPJP (BPJS)</h5>
                                        <div class="daily-chart-wrapper">
                                            <canvas id="dailyChartBpjs"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="detailContainerBpjs" class="mb-4" style="display: none;">
                                <div class="card border border-info shadow-none" style="border-radius: 10px; background-color: #fafbfc;">
                                    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center flex-wrap detail-header-controls">
                                        <h5 class="mb-0 font-weight-bold text-info"><i class="fas fa-file-invoice mr-2"></i>Rincian Detail Tagihan Pasien</h5>
                                        <div class="d-flex align-items-center flex-wrap gap-2">
                                            <label class="mb-0 mr-2 text-muted font-weight-bold small">TIPE BAYAR :</label>
                                            <select id="pembayaranDetailBpjs" class="form-control form-control-sm mr-2 shadow-sm" style="width: 220px; border-radius: 6px;">
                                                <option value="A12" selected>BPJS Kesehatan</option>
                                            </select>
                                            <button type="button" id="btnDownloadDetailBpjs" class="btn btn-sm btn-success shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel mr-1"></i> Excel Detail
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <div id="loadingDetailBpjs" style="display: none;" class="py-5 text-center">
                                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 40px;" />
                                            <p class="text-info mt-2 small font-weight-bold">Menarik rincian tagihan dari server...</p>
                                        </div>
                                        <div class="table-responsive p-3" id="tableDetailBpjs" style="display: none;"></div>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-2" id="hrBpjs" style="border-top: 2px dashed #e9ecef; display:none;">
                            <div class="table-responsive p-3" id="tableRekapBpjs" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-umum" role="tabpanel">

                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="filter-wrapper">
                                <form id="formUmum">
                                    <div class="row align-items-end">
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="tglAwalUmum" class="form-label text-muted small font-weight-bold mb-1">Tanggal Awal</label>
                                            <input type="date" id="tglAwalUmum" name="tglAwalUmum" class="form-control" value="<?= $tgl_awal ?? '' ?>" required />
                                        </div>
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="tglAkhirUmum" class="form-label text-muted small font-weight-bold mb-1">Tanggal Akhir</label>
                                            <input type="date" id="tglAkhirUmum" name="tglAkhirUmum" class="form-control" value="<?= $tgl_akhir ?? '' ?>" required />
                                        </div>
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="jenisPasienUmum" class="form-label text-muted small font-weight-bold mb-1">Jenis Pasien</label>
                                            <select id="jenisPasienUmum" name="kd_jenis_pasien" class="form-control" required>
                                                <option value="" disabled <?= empty($kd_jenis_pasien) ? 'selected' : '' ?>>Pilih Jenis Pasien</option>
                                                <option value="1" <?= ($kd_jenis_pasien == '1') ? 'selected' : '' ?>>Rawat Jalan</option>
                                                <option value="2" <?= ($kd_jenis_pasien == '2') ? 'selected' : '' ?>>Rawat Inap</option>
                                                <option value="3" <?= ($kd_jenis_pasien == '3') ? 'selected' : '' ?>>IGD</option>
                                            </select>
                                        </div>
                                        <div class="col-lg-6 col-md-12">
                                            <div class="btn-group-custom">
                                                <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                                <button id="btnDownloadUmumBilling" type="button" class="btn btn-success ml-2 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Rekap KEU</button>
                                                <button id="btnDownloadUmumDokter" type="button" class="btn btn-info ml-2 shadow-sm text-white" style="display: none;"><i class="fas fa-user-md me-1"></i> Rekap DPJP</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-12 mb-3 px-0" id="chartButtonsUmum" style="display:none;">
                        <div class="d-flex flex-wrap gap-2 p-2 bg-white rounded shadow-sm border">
                            <button type="button" class="btn btn-sm btn-primary active metric-btn-umum" data-metric="jumlah">
                                <i class="fas fa-users me-1"></i> Jumlah
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-warning metric-btn-umum" data-metric="tarif_rs">
                                <i class="fas fa-hospital me-1"></i> Tarif RS
                            </button>
                            <div class="border-right mx-2 d-none d-md-block"></div>
                            <button type="button" id="btnDetailUmum" class="btn btn-sm btn-outline-secondary font-weight-bold">
                                <i class="fas fa-list-alt me-1"></i> Detail Tagihan
                            </button>
                        </div>
                    </div>

                    <div id="resultUmum" class="card border-0 shadow-sm mb-4" style="border-radius: 12px; overflow:hidden; display: none;">
                        <div class="card-body p-0 p-md-3">

                            <div id="loadingUmum" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                                <p class="text-muted mt-2 font-weight-bold">Memproses data UMUM...</p>
                            </div>

                            <div id="chartSectionUmum" class="mb-4" style="display: none;">
                                <div class="card border-0">
                                    <div class="card-body pb-0 text-center text-md-left">
                                        <h5 class="card-title text-secondary font-weight-bold mb-4">Grafik Per DPJP Jumlah Pasien & Total Pendapatan Non BPJS - Umum</h5>
                                        <div class="daily-chart-wrapper">
                                            <canvas id="dailyChartUmum"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="detailContainerUmum" class="mb-4" style="display: none;">
                                <div class="card border border-warning shadow-none" style="border-radius: 10px; background-color: #fffaf0;">
                                    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center flex-wrap detail-header-controls">
                                        <h5 class="mb-0 font-weight-bold text-warning"><i class="fas fa-file-invoice mr-2"></i>Rincian Detail Tagihan (UMUM)</h5>
                                        <div class="d-flex align-items-center flex-wrap gap-2">
                                            <label class="mb-0 mr-2 text-muted font-weight-bold small">TIPE BAYAR :</label>
                                            <select id="pembayaranDetailUmum" class="form-control form-control-sm mr-2 shadow-sm" style="width: 220px; border-radius: 6px;">
                                                <option value="A08" selected>UMUM</option>
                                            </select>
                                            <button type="button" id="btnDownloadDetailUmum" class="btn btn-sm btn-success shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel mr-1"></i> Excel Detail
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <div id="loadingDetailUmum" style="display: none;" class="py-5 text-center">
                                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 40px;" />
                                            <p class="text-warning mt-2 small font-weight-bold">Menarik rincian tagihan dari server...</p>
                                        </div>
                                        <div class="table-responsive p-3" id="tableDetailUmum" style="display: none;"></div>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-2" id="hrUmum" style="border-top: 2px dashed #e9ecef; display:none;">

                            <div class="table-responsive p-3" id="tableRekapUmum" style="display: none;"></div>

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

                <div class="tab-pane fade" id="tab-asuransi" role="tabpanel">
                    <div class="filter-wrapper mb-4">
                        <form id="formAsuransi">
                            <div class="row g-3 align-items-end">
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label class="form-label text-muted font-weight-bold small mb-1">TANGGAL AWAL</label>
                                    <input type="date" id="tglAwalAsuransi" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-2">
                                    <label class="form-label text-muted font-weight-bold small mb-1">TANGGAL AKHIR</label>
                                    <input type="date" id="tglAkhirAsuransi" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                </div>
                                <div class="col-12 col-md-3 col-lg-3">
                                    <label class="form-label text-muted font-weight-bold small mb-1">JENIS PASIEN</label>
                                    <select id="jenisPasienAsuransi" class="form-select custom-select shadow-sm" required>
                                        <option value="" disabled selected>Pilih Jenis Pasien</option>
                                        <option value="1">Rawat Jalan</option>
                                        <option value="2">Rawat Inap</option>
                                        <option value="3">IGD</option>
                                    </select>
                                </div>
                                <div class="col-12 col-md-3 col-lg-5">
                                    <div class="btn-group-custom">
                                        <button type="submit" class="btn btn-primary px-4 shadow-sm font-weight-bold"><i class="fas fa-search me-1"></i> Tampilkan Rekap</button>
                                        <button type="button" id="btnDownloadAsuransi" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel Rekap</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="col-md-12 mb-3 px-0" id="chartButtonsAsuransi" style="display:none;">
                        <div class="d-flex flex-wrap gap-2 p-2 bg-white rounded shadow-sm border">
                            <button type="button" class="btn btn-sm btn-primary active metric-btn-asuransi" data-metric="jumlah">
                                <i class="fas fa-users me-1"></i> Jumlah Pasien
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-warning metric-btn-asuransi" data-metric="tarif_rs">
                                <i class="fas fa-hospital me-1"></i> Tarif RS
                            </button>
                            <div class="border-right mx-2 d-none d-md-block"></div>
                            <button type="button" id="btnDetailAsuransi" class="btn btn-sm btn-outline-secondary font-weight-bold">
                                <i class="fas fa-list-alt me-1"></i> Detail Tagihan
                            </button>
                        </div>
                    </div>

                    <div id="resultAsuransi" class="card border-0 shadow-sm mb-4" style="border-radius: 12px; overflow:hidden; display: none;">
                        <div class="card-body p-0 p-md-3">

                            <div id="loadingAsuransi" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                                <p class="text-muted mt-2 font-weight-bold">Memproses data ASURANSI...</p>
                            </div>

                            <div id="chartSectionAsuransi" class="mb-4" style="display: none;">
                                <div class="card border-0">
                                    <div class="card-body pb-0 text-center text-md-left">
                                        <h5 class="card-title text-secondary font-weight-bold mb-4">Grafik Pendapatan & Pasien per DPJP (ASURANSI)</h5>
                                        <div class="daily-chart-wrapper">
                                            <canvas id="dailyChartAsuransi"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="detailContainerAsuransi" class="mb-4" style="display: none;">
                                <div class="card border border-warning shadow-none" style="border-radius: 10px; background-color: #fffaf0;">
                                    <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center flex-wrap detail-header-controls">
                                        <h5 class="mb-0 font-weight-bold text-warning"><i class="fas fa-file-invoice mr-2"></i>Rincian Detail Tagihan (ASURANSI)</h5>
                                        <div class="d-flex align-items-center flex-wrap gap-2">
                                            <label class="mb-0 mr-2 text-muted font-weight-bold small">TIPE BAYAR :</label>
                                            <select id="pembayaranDetailAsuransi" class="form-control form-control-sm mr-2 shadow-sm" style="width: 220px; border-radius: 6px;">
                                                <option value="ASURANSI" selected>ASURANSI</option>
                                            </select>
                                            <button type="button" id="btnDownloadDetailAsuransi" class="btn btn-sm btn-success shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel mr-1"></i> Excel Detail
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body p-0">
                                        <div id="loadingDetailAsuransi" style="display: none;" class="py-5 text-center">
                                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 40px;" />
                                            <p class="text-warning mt-2 small font-weight-bold">Menarik rincian tagihan dari server...</p>
                                        </div>
                                        <div class="table-responsive p-3" id="tableDetailAsuransi" style="display: none;"></div>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-2" id="hrAsuransi" style="border-top: 2px dashed #e9ecef; display:none;">

                            <div class="table-responsive p-3" id="tableRekapAsuransi" style="display: none;"></div>

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

                <div class="tab-pane fade" id="tab-tahunan" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm filter-wrapper">
                        <div class="card-body p-3 p-md-4">
                            <form id="formTahunan">
                                <div class="row g-3 align-items-end">

                                    <div class="col-12 col-md-3">
                                        <label for="tglAwalTahunan" class="form-label fw-bold text-muted small mb-1">PILIH TAHUN</label>
                                        <div class="input-group shadow-sm">
                                            <span class="input-group-text bg-light border-end-0"><i class="far fa-calendar-alt text-primary"></i></span>
                                            <input type="number" id="tglAwalTahunan" name="tanggal_awal"
                                                class="form-control border-start-0 ps-0" placeholder="YYYY"
                                                min="2020" max="2099" value="<?= date('Y') ?>" required />
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-4">
                                        <div class="switch-wrapper">
                                            <div class="d-flex align-items-center">
                                                <label class="switch mb-0">
                                                    <input type="checkbox" id="switchTipePasienTahunan">
                                                    <span class="slider round"></span>
                                                </label>
                                                <span id="labelSwitchTahunan">Mode: Rawat Jalan (Rajal)</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12 col-md-5">
                                        <div class="btn-container d-flex justify-content-md-end mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-4 me-md-2 shadow-sm font-weight-bold">
                                                <i class="fas fa-search me-1"></i> Tampilkan
                                            </button>
                                            <button type="button" id="btnDownloadTahunan" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel me-1"></i> Excel
                                            </button>
                                        </div>
                                    </div>

                                </div>
                            </form>
                        </div>
                    </div>

                    <div id="resultTahunan">
                        <div id="loadingTahunan" style="display: none;" class="py-5 text-center">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            <p class="mt-2 text-muted font-weight-bold">Sedang memuat data asuransi tahunan...</p>
                        </div>

                        <div class="card shadow-sm border-0" id="tableCardContainerTahunan" style="display:none; border-radius: 12px; overflow: hidden;">
                            <div class="card-body p-2 p-md-3">
                                <div id="tableContainerTahunan" style="display: none;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-all" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm filter-wrapper">
                        <div class="card-body p-3 p-md-4">
                            <form id="formAll">
                                <div class="row g-3 align-items-end">
                                    <div class="col-12 col-md-4">
                                        <label for="tglAwalAll" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AWAL</label>
                                        <input type="date" id="tglAwalAll" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <label for="tglAkhirAll" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AKHIR</label>
                                        <input type="date" id="tglAkhirAll" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <div class="btn-group-custom d-flex justify-content-md-left mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-4 me-md-2 shadow-sm font-weight-bold">
                                                <i class="fas fa-search me-1"></i> Tampilkan
                                            </button>
                                            <button type="button" id="btnDownloadAll" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel me-1"></i> Excel
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div id="resultAll">
                        <div id="loadingAll" style="display: none;" class="py-5 text-center">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            <p class="mt-2 text-muted font-weight-bold">Sedang memuat data gabungan...</p>
                        </div>

                        <div class="card shadow-sm border-0" id="tableCardContainerAll" style="display:none; border-radius: 12px; overflow: hidden;">
                            <div class="card-body p-2 p-md-3">
                                <div class="table-responsive p-3" id="tableContainerAll" style="display: none;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-homecare" role="tabpanel">
                    <div class="card mb-4 border-0 shadow-sm filter-wrapper">
                        <div class="card-body p-3 p-md-4">
                            <form id="formHomecare">
                                <div class="row g-3 align-items-end">
                                    <div class="col-12 col-md-3 col-lg-3">
                                        <label for="tglAwalHomecare" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AWAL</label>
                                        <input type="date" id="tglAwalHomecare" class="form-control shadow-sm" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3 col-lg-3">
                                        <label for="tglAkhirHomecare" class="form-label text-muted font-weight-bold small mb-1">TANGGAL AKHIR</label>
                                        <input type="date" id="tglAkhirHomecare" class="form-control shadow-sm" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-6 col-lg-6">
                                        <div class="btn-group-custom d-flex justify-content-md-left mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-4 me-md-2 shadow-sm font-weight-bold">
                                                <i class="fas fa-search me-1"></i> Filter
                                            </button>
                                            <button type="button" id="btnDownloadHomecare" class="btn btn-success px-4 shadow-sm font-weight-bold" style="display: none;">
                                                <i class="fas fa-file-excel me-1"></i> Download Excel
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="row mb-4" id="grafikContainerHomecare" style="display: none;">
                        <div class="col-md-12">
                            <div class="card shadow-sm border-0 border-top border-primary border-4" style="border-top-width: 4px !important; border-top-color: #0d6efd !important;">
                                <div class="card-header bg-white font-weight-bold pt-3 pb-2 d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="fas fa-chart-line me-1 text-primary"></i> Grafik Pendapatan Homecare
                                    </div>
                                    <button class="btn btn-sm btn-outline-primary font-weight-bold shadow-sm" id="btnDownloadChartHomecare">
                                        <i class="fas fa-image me-1"></i> Download Grafik (JPEG)
                                    </button>
                                </div>
                                <div class="card-body bg-white p-3">
                                    <div style="position: relative; height: 350px; width: 100%;">
                                        <canvas id="dailyChartHomecare" style="background-color: #fff;"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="resultHomecare">
                        <div id="loadingHomecare" style="display: none;" class="py-5 text-center">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            <p class="mt-2 text-muted font-weight-bold">Sedang memuat data Homecare...</p>
                        </div>

                        <div class="card shadow-sm border-0" id="tableCardContainerHomecare" style="display:none; border-radius: 12px; overflow: hidden;">
                            <div class="card-body p-2 p-md-3">
                                <div class="table-responsive p-3" id="tableContainerHomecare" style="display: none;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-bpjsksm" role="tabpanel">
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="filter-wrapper">
                                <form id="formBpjsksm">
                                    <div class="row align-items-end">
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="tglAwalBpjsksm" class="form-label text-muted small font-weight-bold mb-1">Tanggal Awal</label>
                                            <input type="date" id="tglAwalBpjsksm" name="tglAwalBpjsksm" class="form-control" value="<?= $tgl_awal ?? '' ?>" required />
                                        </div>
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="tglAkhirBpjsksm" class="form-label text-muted small font-weight-bold mb-1">Tanggal Akhir</label>
                                            <input type="date" id="tglAkhirBpjsksm" name="tglAkhirBpjsksm" class="form-control" value="<?= $tgl_akhir ?? '' ?>" required />
                                        </div>
                                        <div class="col-lg-2 col-md-6 mb-3 mb-lg-0">
                                            <label for="jenisPasienBpjsksm" class="form-label text-muted small font-weight-bold mb-1">Jenis Pasien</label>
                                            <select id="jenisPasienBpjsksm" name="kd_jenis_pasien" class="form-control" required>
                                                <option value="" disabled <?= empty($kd_jenis_pasien) ? 'selected' : '' ?>>Pilih Jenis Pasien</option>
                                                <option value="1" <?= ($kd_jenis_pasien == '1') ? 'selected' : '' ?>>Rawat Jalan</option>
                                                <option value="2" <?= ($kd_jenis_pasien == '2') ? 'selected' : '' ?>>Rawat Inap</option>
                                                <option value="3" <?= ($kd_jenis_pasien == '3') ? 'selected' : '' ?>>IGD</option>
                                            </select>
                                        </div>
                                        <div class="col-lg-6 col-md-12">
                                            <div class="btn-group-custom">
                                                <button type="submit" class="btn btn-primary px-4 shadow-sm">
                                                    <i class="fas fa-search me-1"></i> Submit
                                                </button>
                                                <button id="btnDownloadBpjsksm" type="button" class="btn btn-success ml-2 shadow-sm" style="display: none;">
                                                    <i class="fas fa-file-excel me-1"></i> Unduh Rekap PER-KSM
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- TOMBOL METRIK GRAFIK -->
                    <!-- <div class="col-md-12 mb-3 px-0" id="chartButtonsBpjsksm" style="display:none;">
                        <div class="d-flex flex-wrap gap-2 p-2 bg-white rounded shadow-sm border">
                            <button type="button" class="btn btn-sm btn-primary active metric-btn-bpjsksm" data-metric="jml">
                                <i class="fas fa-users me-1"></i> Jumlah Pasien
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-success metric-btn-bpjsksm" data-metric="tarif_bpjs">
                                <i class="fas fa-file-invoice-dollar me-1"></i> Tarif BPJS
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-warning metric-btn-bpjsksm" data-metric="tarif_rs">
                                <i class="fas fa-hospital me-1"></i> Tarif RS
                            </button>
                        </div>
                    </div> -->

                    <!-- CARD HASIL -->
                    <div id="resultBpjsksm" class="card border-0 shadow-sm mb-4" style="border-radius: 12px; overflow:hidden; display: none;">
                        <div class="card-body p-0 p-md-3">

                            <!-- LOADING -->
                            <div id="loadingBpjsksm" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                                <p class="text-muted mt-2 font-weight-bold">Sedang memuat Rekap BPJS PER-KSM...</p>
                            </div>

                            <!-- SECTION GRAFIK -->
                            <!-- <div id="chartSectionBpjsksm" class="mb-4" style="display: none;">
                                <div class="card border-0">
                                    <div class="card-body pb-0 text-center text-md-left">
                                        <h5 class="card-title text-secondary font-weight-bold mb-4">Grafik Per KSM (BPJS)</h5>
                                        <div class="daily-chart-wrapper">
                                            <canvas id="dailyChartBpjsksm"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div> -->

                            <hr class="my-2" id="hrBpjsksm" style="border-top: 2px dashed #e9ecef; display:none;">

                            <!-- TABEL REKAP -->
                            <div class="table-responsive p-3" id="tableContainerBpjsksm" style="display: none;"></div>

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

    <footer class="py-4 bg-white mt-auto border-top">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small">
                <div class="text-muted font-weight-bold">Copyright &copy; IT RSU Ananda Purwokerto 2024</div>
            </div>
        </div>
    </footer>
</div>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    Chart.register(ChartDataLabels);

    $(document).ready(function() {

        const parseNumericValue = value => {
            if (value === null || value === undefined) return 0;
            const cleaned = String(value).replace(/[^0-9\-\.]/g, '');
            return cleaned === '' ? 0 : parseFloat(cleaned);
        };

        // =====================================================================
        // LOGIKA TAB 1: BPJS (TETAP SAMA 100%)
        // =====================================================================
        let dailyChartBpjs = null;
        let currentListBpjs = [];
        let currentMetricBpjs = 'jumlah';

        const buildDailyChartBpjs = (list, metric = 'jumlah') => {
            const chartContainer = $('#chartSectionBpjs');
            const ctx = document.getElementById('dailyChartBpjs').getContext('2d');
            if (!Array.isArray(list) || list.length === 0) {
                chartContainer.hide();
                return;
            }

            const grouped = {};
            list.forEach(item => {
                const dpjp = item.dpjp || 'Tidak Diketahui';
                if (!grouped[dpjp]) grouped[dpjp] = {
                    count: 0,
                    tarif_bpjs: 0,
                    tarif_rs: 0
                };
                grouped[dpjp].count += parseNumericValue(item.jlm_ri);
                grouped[dpjp].tarif_bpjs += parseNumericValue(item.tarif_bpjs);
                grouped[dpjp].tarif_rs += parseNumericValue(item.tarif_rs);
            });

            const metricConfig = {
                jumlah: {
                    label: 'Jumlah Pasien',
                    field: 'count',
                    color: 'rgba(54, 162, 235, 0.7)',
                    border: 'rgba(54, 162, 235, 1)',
                    yTitle: 'Pasien',
                    fmt: v => v
                },
                tarif_bpjs: {
                    label: 'Tarif BPJS',
                    field: 'tarif_bpjs',
                    color: 'rgba(40, 167, 69, 0.7)',
                    border: 'rgba(40, 167, 69, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
                tarif_rs: {
                    label: 'Tarif RS',
                    field: 'tarif_rs',
                    color: 'rgba(255, 193, 7, 0.7)',
                    border: 'rgba(255, 193, 7, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
            };
            const cfg = metricConfig[metric] || metricConfig['jumlah'];
            const labels = Object.keys(grouped).sort((a, b) => grouped[b][cfg.field] - grouped[a][cfg.field]);
            const values = labels.map(dpjp => grouped[dpjp][cfg.field]);

            if (dailyChartBpjs) dailyChartBpjs.destroy();
            dailyChartBpjs = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [{
                        label: cfg.label,
                        data: values,
                        backgroundColor: cfg.color,
                        borderColor: cfg.border,
                        borderWidth: 1,
                        maxBarThickness: 30,
                        borderRadius: 4
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            offset: 2,
                            font: {
                                size: 9,
                                weight: 'bold'
                            },
                            color: '#555',
                            formatter: (value) => cfg.fmt(value),
                            clip: false
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                autoSkip: false,
                                maxRotation: 45,
                                minRotation: 30,
                                font: {
                                    size: 10
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: metric !== 'jumlah' ? v => `Rp ${Number(v).toLocaleString('id-ID')}` : v => v
                            }
                        }
                    }
                }
            });
            chartContainer.fadeIn();
        };

        $('#formBpjs').on('submit', function(event) {
            event.preventDefault();
            $('#resultBpjs').show();
            $('#detailContainerBpjs').hide();
            $('#chartSectionBpjs').hide();
            $('#tableRekapBpjs').hide();
            $('#hrBpjs').hide();

            $('.metric-btn-bpjs').removeClass('active btn-primary btn-success btn-warning').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_bpjs' ? 'btn-outline-success' : m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $('.metric-btn-bpjs[data-metric="jumlah"]').removeClass('btn-outline-primary').addClass('btn-primary active');
            currentMetricBpjs = 'jumlah';
            $('#btnDetailBpjs').removeClass('btn-secondary active').addClass('btn-outline-secondary');

            $('#loadingBpjs').show();

            $.ajax({
                url: '<?= base_url("billing/tampildatarekapkeubpjs") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalBpjs').val(),
                    TANGGAL_AKHIR: $('#tglAkhirBpjs').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienBpjs').val()
                },
                success: function(tampil) {
                    $('#loadingBpjs').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil)) {
                            const list = data.tampil;
                            if ($.fn.DataTable.isDataTable('#dtRekapBpjs')) $('#dtRekapBpjs').DataTable().destroy();
                            if (list.length > 0) {
                                currentListBpjs = list;
                                buildDailyChartBpjs(list, currentMetricBpjs);
                                $('#chartButtonsBpjs').fadeIn();

                                let html = `<table id="dtRekapBpjs" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-light"><tr><th>DPJP</th><th class="text-center">Jumlah</th><th class="text-right">Tarif BPJS</th><th class="text-right">Tarif RS</th><th class="text-right">BMHP</th></tr></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-primary">${item.jlm_ri}</td><td class="text-right">${parseNumericValue(item.tarif_bpjs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.tarif_rs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.bmhp).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableRekapBpjs').html(html).fadeIn();
                                $('#hrBpjs').fadeIn();
                                $('#dtRekapBpjs').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    language: {
                                        search: "Cari:"
                                    }
                                });
                                $('#btnDownloadBpjs').fadeIn();
                            }
                        }
                    } catch (e) {
                        console.error(e);
                    }
                }
            });
        });

        function loadDetailBpjs() {
            $('#tableDetailBpjs').hide();
            $('#btnDownloadDetailBpjs').hide();
            $('#loadingDetailBpjs').show();
            $.ajax({
                url: '<?= base_url("detialtagihan/tampildata") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalBpjs').val(),
                    TANGGAL_AKHIR: $('#tglAkhirBpjs').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienBpjs').val(),
                    KD_PEMBAYARAN: $('#pembayaranDetailBpjs').val()
                },
                success: function(res) {
                    $('#loadingDetailBpjs').hide();
                    try {
                        const data = JSON.parse(res);
                        if (data && Array.isArray(data.response)) {
                            const list = data.response;
                            if ($.fn.DataTable.isDataTable('#dtTblDetailBpjs')) $('#dtTblDetailBpjs').DataTable().destroy();
                            if (list.length > 0) {
                                let html = `<table id="dtTblDetailBpjs" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-info text-white"><tr><th>DPJP</th><th class="text-center">Jml Pasien</th><th class="text-center">Pasien INACBG</th><th class="text-right">Total Tagihan</th><th class="text-right">Tagihan Pribadi</th><th class="text-right">Tagihan Penjamin</th><th class="text-right">Tarif INACBG</th></tr></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-info">${item.jumlah_pasien}</td><td class="text-center">${item.jumlah_pasien_ada_inacbg}</td><td class="text-right text-danger font-weight-bold">${parseNumericValue(item.total_tagihan).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_pribadi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_penjamin).toLocaleString('id-ID')}</td><td class="text-right text-success font-weight-bold">${parseNumericValue(item.total_tarif_inacbg).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableDetailBpjs').html(html).fadeIn();
                                $('#dtTblDetailBpjs').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    pageLength: 8,
                                    language: {
                                        search: "Cari:"
                                    }
                                });
                                $('#btnDownloadDetailBpjs').fadeIn();
                            } else {
                                $('#tableDetailBpjs').html('<div class="alert alert-info text-center m-4">Tidak ada data detail.</div>').fadeIn();
                            }
                        }
                    } catch (e) {}
                }
            });
        }

        $('#btnDetailBpjs').on('click', function() {
            $('.metric-btn-bpjs').removeClass('btn-primary btn-success btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_bpjs' ? 'btn-outline-success' : m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $(this).removeClass('btn-outline-secondary').addClass('btn-secondary active');
            $('#chartSectionBpjs').hide();
            $('#detailContainerBpjs').fadeIn();
            loadDetailBpjs();
        });

        $('#pembayaranDetailBpjs').on('change', function() {
            loadDetailBpjs();
        });

        $('.metric-btn-bpjs').on('click', function() {
            $('#detailContainerBpjs').hide();
            $('#chartSectionBpjs').fadeIn();
            $('#btnDetailBpjs').removeClass('btn-secondary active').addClass('btn-outline-secondary');
            const metric = $(this).data('metric');
            currentMetricBpjs = metric;
            $('.metric-btn-bpjs').removeClass('btn-primary btn-success btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_bpjs' ? 'btn-outline-success' : m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            if (metric === 'jumlah') $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
            if (metric === 'tarif_bpjs') $(this).removeClass('btn-outline-success').addClass('btn-success active');
            if (metric === 'tarif_rs') $(this).removeClass('btn-outline-warning').addClass('btn-warning active');
            if (currentListBpjs.length > 0) buildDailyChartBpjs(currentListBpjs, metric);
        });

        $('#btnDownloadBpjs').on('click', function() {
            window.location.href = `<?= base_url("billing/unduhrekapkeusirusbpjs") ?>?TANGGAL_AWAL=${$('#tglAwalBpjs').val()}&TANGGAL_AKHIR=${$('#tglAkhirBpjs').val()}&KD_JENIS_PASIEN=${$('#jenisPasienBpjs').val()}`;
        });
        $('#btnDownloadDetailBpjs').on('click', function() {
            window.location.href = `<?= base_url("detialtagihan/unduhdata") ?>?TANGGAL_AWAL=${$('#tglAwalBpjs').val()}&TANGGAL_AKHIR=${$('#tglAkhirBpjs').val()}&KD_JENIS_PASIEN=${$('#jenisPasienBpjs').val()}&KD_PEMBAYARAN=${$('#pembayaranDetailBpjs').val()}`;
        });


        // =====================================================================
        // LOGIKA TAB 2: NON-BPJS (UMUM) - TERINTEGRASI PENUH
        // =====================================================================
        let dailyChartUmum = null;
        let currentListUmum = [];
        let currentMetricUmum = 'jumlah';

        // Fungsi Membangun Chart Khusus UMUM (Tanpa Tarif BPJS)
        const buildDailyChartUmum = (list, metric = 'jumlah') => {
            const chartContainer = $('#chartSectionUmum');
            const ctx = document.getElementById('dailyChartUmum').getContext('2d');
            if (!Array.isArray(list) || list.length === 0) {
                chartContainer.hide();
                return;
            }

            const grouped = {};
            list.forEach(item => {
                const dpjp = item.dpjp || 'Tidak Diketahui';
                if (!grouped[dpjp]) grouped[dpjp] = {
                    count: 0,
                    tarif_rs: 0
                };
                grouped[dpjp].count += parseNumericValue(item.jlm_ri);
                grouped[dpjp].tarif_rs += parseNumericValue(item.tarif_rs);
            });

            const metricConfig = {
                jumlah: {
                    label: 'Jumlah Pasien',
                    field: 'count',
                    color: 'rgba(54, 162, 235, 0.7)',
                    border: 'rgba(54, 162, 235, 1)',
                    yTitle: 'Pasien',
                    fmt: v => v
                },
                tarif_rs: {
                    label: 'Tarif RS',
                    field: 'tarif_rs',
                    color: 'rgba(255, 193, 7, 0.7)',
                    border: 'rgba(255, 193, 7, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
            };
            const cfg = metricConfig[metric] || metricConfig['jumlah'];
            const labels = Object.keys(grouped).sort((a, b) => grouped[b][cfg.field] - grouped[a][cfg.field]);
            const values = labels.map(dpjp => grouped[dpjp][cfg.field]);

            if (dailyChartUmum) dailyChartUmum.destroy();
            dailyChartUmum = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [{
                        label: cfg.label,
                        data: values,
                        backgroundColor: cfg.color,
                        borderColor: cfg.border,
                        borderWidth: 1,
                        maxBarThickness: 30,
                        borderRadius: 4
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            offset: 2,
                            font: {
                                size: 9,
                                weight: 'bold'
                            },
                            color: '#555',
                            formatter: (value) => cfg.fmt(value),
                            clip: false
                        }
                    },
                    layout: {
                        padding: {
                            top: 30
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                autoSkip: false,
                                maxRotation: 45,
                                minRotation: 30,
                                font: {
                                    size: 10
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: metric !== 'jumlah' ? v => `Rp ${Number(v).toLocaleString('id-ID')}` : v => v
                            }
                        }
                    }
                }
            });
            chartContainer.fadeIn();
        };

        // Submit Rekap UMUM
        $('#formUmum').on('submit', function(event) {
            event.preventDefault();

            // Sembunyikan UI saat loading
            $('#resultUmum').show();
            $('#summaryContainerUmum').hide();
            $('#chartSectionUmum').hide();
            $('#tableRekapUmum').hide();
            $('#detailContainerUmum').hide();
            $('#hrUmum').hide();
            $('#chartButtonsUmum').hide();

            $('#btnDownloadUmumBilling').hide();
            $('#btnDownloadUmumDokter').hide();

            // Reset Tombol Detail dan Metrik ke Default (Jumlah)
            $('.metric-btn-umum').removeClass('active btn-primary btn-warning').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $('.metric-btn-umum[data-metric="jumlah"]').removeClass('btn-outline-primary').addClass('btn-primary active');
            currentMetricUmum = 'jumlah';
            $('#btnDetailUmum').removeClass('btn-secondary active').addClass('btn-outline-secondary');

            $('#loadingUmum').show();

            $.ajax({
                url: '<?= base_url("keuangan/tampildatarekapkeunonbpjs_umum") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalUmum').val(),
                    TANGGAL_AKHIR: $('#tglAkhirUmum').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienUmum').val()
                },
                dataType: 'json',
                success: function(data) {
                    $('#loadingUmum').hide();

                    if (data.status === 'error') {
                        Swal.fire('Error', data.message, 'error');
                        return;
                    }

                    // 1. RENDER SUMMARY TABLE
                    if (data.summary && data.summary.length > 0) {
                        let summaryHtml = `
                            <div class="summary-table-container">
                                <table class="table table-sm table-hover mb-0">
                                    <thead>
                                        <tr class="table-title">
                                            <th class="bank-name-column">Nama Dokter</th>
                                            <th class="text-right">Jml Pasien RANAP</th>
                                            <th class="text-right">Jml Pembayar Px UMUM</th>
                                            <th class="text-right">Jml Px Gabung (Tidak Ditagih)</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;
                        data.summary.forEach(item => {
                            summaryHtml += `<tr>
                                                <td class="bank-name-column"><strong>${item.nm_dokter}</strong></td>
                                                <td class="text-right">${item.jlm_ri}</td>
                                                <td class="text-right">${item.pasien_umum_bayar_umum}</td>
                                                <td class="text-right">${item.pasien_umum_gabung_ibu_alias_tidak_di_tagih}</td>
                                            </tr>`;
                        });
                        summaryHtml += '</tbody></table></div>';
                        $('#summaryContainerUmum').html(summaryHtml).fadeIn();
                        $('#btnDownloadUmumDokter').show();
                    } else {
                        $('#summaryContainerUmum').hide();
                        $('#btnDownloadUmumDokter').hide();
                    }

                    // 2. RENDER MAIN RESPONSE (GRAFIK & TABEL)
                    if (data.response && data.response.length > 0) {
                        const list = data.response;
                        currentListUmum = list;

                        // Render Grafik
                        buildDailyChartUmum(list, currentMetricUmum);
                        $('#chartButtonsUmum').fadeIn();

                        // Render Tabel DataTables
                        if ($.fn.DataTable.isDataTable('#dtRekapUmum')) $('#dtRekapUmum').DataTable().destroy();

                        let html = `<table id="dtRekapUmum" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-light"><tr><th>DPJP</th><th class="text-center">Jumlah</th><th class="text-right">Tarif RS</th><th class="text-right">Prosedur Non Bedah</th><th class="text-right">Prosedur Bedah</th><th class="text-right">Konsultasi</th><th class="text-right">Keperawatan</th><th class="text-right">Tenaga Ahli</th><th class="text-right">Laboratorium</th><th class="text-right">Radiologi</th><th class="text-right">Kamar & Akomodasi</th><th class="text-right">Obat</th><th class="text-right">BMHP</th></tr></thead><tbody>`;

                        list.forEach(item => {
                            html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-primary">${item.jlm_ri}</td><td class="text-right">${parseNumericValue(item.tarif_rs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.prosedur_non_bedah).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.prosedur_bedah).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.konsultasi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.keperawatan).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.tenaga_ahli).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.laboratorium).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.radiologi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.kamar_akomodasi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.obat).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.bmhp).toLocaleString('id-ID')}</td></tr>`;
                        });
                        html += '</tbody></table>';
                        $('#tableRekapUmum').html(html).fadeIn();
                        $('#hrUmum').fadeIn();

                        $('#dtRekapUmum').DataTable({
                            responsive: false,
                            autoWidth: false,
                            language: {
                                search: "Cari:"
                            }
                        });
                        $('#btnDownloadUmumBilling').show();
                    } else {
                        $('#tableRekapUmum').html('<div class="alert alert-info text-center m-4">Tidak ada data rekap UMUM.</div>').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingUmum').hide();
                    Swal.fire('Oops...', 'Terjadi kesalahan saat menghubungi server.', 'error');
                }
            });
        });

        // --- LOAD DETAIL UMUM (Default A08) ---
        function loadDetailUmum() {
            $('#tableDetailUmum').hide();
            $('#btnDownloadDetailUmum').hide();
            $('#loadingDetailUmum').show();
            $.ajax({
                url: '<?= base_url("detialtagihan/tampildata") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalUmum').val(),
                    TANGGAL_AKHIR: $('#tglAkhirUmum').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienUmum').val(),
                    KD_PEMBAYARAN: $('#pembayaranDetailUmum').val()
                },
                success: function(res) {
                    $('#loadingDetailUmum').hide();
                    try {
                        const data = JSON.parse(res);
                        if (data && Array.isArray(data.response)) {
                            const list = data.response;
                            if ($.fn.DataTable.isDataTable('#dtTblDetailUmum')) $('#dtTblDetailUmum').DataTable().destroy();
                            if (list.length > 0) {
                                let html = `<table id="dtTblDetailUmum" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-warning text-dark"><tr><th>DPJP</th><th class="text-center">Jml Pasien</th><th class="text-right">Total Tagihan</th><th class="text-right">Tagihan Pribadi</th><th class="text-right">Tagihan Penjamin</th></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-info">${item.jumlah_pasien}</td><td class="text-right text-danger font-weight-bold">${parseNumericValue(item.total_tagihan).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_pribadi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_penjamin).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableDetailUmum').html(html).fadeIn();
                                $('#dtTblDetailUmum').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    pageLength: 8,
                                    language: {
                                        search: "Cari Detail:"
                                    }
                                });
                                $('#btnDownloadDetailUmum').fadeIn();
                            } else {
                                $('#tableDetailUmum').html('<div class="alert alert-info text-center m-4">Tidak ada data detail.</div>').fadeIn();
                            }
                        }
                    } catch (e) {}
                }
            });
        }

        // --- EVENT BUTTONS TOGGLE GRAFIK / DETAIL (UMUM) ---
        $('#btnDetailUmum').on('click', function() {
            $('.metric-btn-umum').removeClass('btn-primary btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $(this).removeClass('btn-outline-secondary').addClass('btn-secondary active');

            $('#chartSectionUmum').hide();
            $('#detailContainerUmum').fadeIn();
            loadDetailUmum();
        });

        $('.metric-btn-umum').on('click', function() {
            $('#detailContainerUmum').hide();
            $('#chartSectionUmum').fadeIn();
            $('#btnDetailUmum').removeClass('btn-secondary active').addClass('btn-outline-secondary');

            const metric = $(this).data('metric');
            currentMetricUmum = metric;
            $('.metric-btn-umum').removeClass('btn-primary btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            if (metric === 'jumlah') $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
            if (metric === 'tarif_rs') $(this).removeClass('btn-outline-warning').addClass('btn-warning active');

            if (currentListUmum.length > 0) buildDailyChartUmum(currentListUmum, metric);
        });

        $('#pembayaranDetailUmum').on('change', function() {
            loadDetailUmum();
        });

        // --- EVENT DOWNLOAD UMUM ---
        $('#btnDownloadUmumBilling').on('click', function() {
            if (!$('#jenisPasienUmum').val()) return Swal.fire('Info', 'Pilih Jenis Pasien.', 'info');
            window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_umumanak1") ?>?TANGGAL_AWAL=${$('#tglAwalUmum').val()}&TANGGAL_AKHIR=${$('#tglAkhirUmum').val()}&KD_JENIS_PASIEN=${$('#jenisPasienUmum').val()}`;
        });

        $('#btnDownloadUmumDokter').on('click', function() {
            if (!$('#jenisPasienUmum').val()) return Swal.fire('Info', 'Pilih Jenis Pasien.', 'info');
            window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_umumanak2") ?>?TANGGAL_AWAL=${$('#tglAwalUmum').val()}&TANGGAL_AKHIR=${$('#tglAkhirUmum').val()}&KD_JENIS_PASIEN=${$('#jenisPasienUmum').val()}`;
        });

        $('#btnDownloadDetailUmum').on('click', function() {
            window.location.href = `<?= base_url("detialtagihan/unduhdata") ?>?TANGGAL_AWAL=${$('#tglAwalUmum').val()}&TANGGAL_AKHIR=${$('#tglAkhirUmum').val()}&KD_JENIS_PASIEN=${$('#jenisPasienUmum').val()}&KD_PEMBAYARAN=${$('#pembayaranDetailUmum').val()}`;
        });


        // =====================================================================
        // LOGIKA TAB 3: NON-BPJS (ASURANSI) DENGAN GRAFIK & DETAIL
        // =====================================================================
        let dailyChartAsuransi = null;
        let currentListAsuransi = [];
        let currentMetricAsuransi = 'jumlah';

        const buildDailyChartAsuransi = (list, metric = 'jumlah') => {
            const chartContainer = $('#chartSectionAsuransi');
            const ctx = document.getElementById('dailyChartAsuransi').getContext('2d');
            if (!Array.isArray(list) || list.length === 0) {
                chartContainer.hide();
                return;
            }

            const grouped = {};
            list.forEach(item => {
                const dpjp = item.dpjp || 'Tidak Diketahui';
                if (!grouped[dpjp]) grouped[dpjp] = {
                    count: 0,
                    tarif_rs: 0
                };
                grouped[dpjp].count += parseNumericValue(item.jlm_ri);
                grouped[dpjp].tarif_rs += parseNumericValue(item.tarif_rs);
            });

            const metricConfig = {
                jumlah: {
                    label: 'Jumlah Pasien',
                    field: 'count',
                    color: 'rgba(54, 162, 235, 0.7)',
                    border: 'rgba(54, 162, 235, 1)',
                    yTitle: 'Pasien',
                    fmt: v => v
                },
                tarif_rs: {
                    label: 'Tarif RS',
                    field: 'tarif_rs',
                    color: 'rgba(255, 193, 7, 0.7)',
                    border: 'rgba(255, 193, 7, 1)',
                    yTitle: 'Rp',
                    fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
                },
            };
            const cfg = metricConfig[metric] || metricConfig['jumlah'];
            const labels = Object.keys(grouped).sort((a, b) => grouped[b][cfg.field] - grouped[a][cfg.field]);
            const values = labels.map(dpjp => grouped[dpjp][cfg.field]);

            if (dailyChartAsuransi) dailyChartAsuransi.destroy();
            dailyChartAsuransi = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [{
                        label: cfg.label,
                        data: values,
                        backgroundColor: cfg.color,
                        borderColor: cfg.border,
                        borderWidth: 1,
                        maxBarThickness: 30,
                        borderRadius: 4
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        datalabels: {
                            anchor: 'end',
                            align: 'end',
                            offset: 2,
                            font: {
                                size: 9,
                                weight: 'bold'
                            },
                            color: '#555',
                            formatter: (value) => cfg.fmt(value),
                            clip: false
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                autoSkip: false,
                                maxRotation: 45,
                                minRotation: 30,
                                font: {
                                    size: 10
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: metric !== 'jumlah' ? v => `Rp ${Number(v).toLocaleString('id-ID')}` : v => v
                            }
                        }
                    }
                }
            });
            chartContainer.fadeIn();
        };

        // Submit Rekap ASURANSI
        $('#formAsuransi').on('submit', function(event) {
            event.preventDefault();
            $('#resultAsuransi').show();
            $('#detailContainerAsuransi').hide();
            $('#chartSectionAsuransi').hide();
            $('#tableRekapAsuransi').hide();
            $('#hrAsuransi').hide();

            $('.metric-btn-asuransi').removeClass('active btn-primary btn-warning').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $('.metric-btn-asuransi[data-metric="jumlah"]').removeClass('btn-outline-primary').addClass('btn-primary active');
            currentMetricAsuransi = 'jumlah';
            $('#btnDetailAsuransi').removeClass('btn-secondary active').addClass('btn-outline-secondary');

            $('#loadingAsuransi').show();

            $.ajax({
                url: '<?= base_url("keuangan/tampildatarekapkeunonbpjs_asuransi") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalAsuransi').val(),
                    TANGGAL_AKHIR: $('#tglAkhirAsuransi').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienAsuransi').val()
                },
                success: function(tampil) {
                    $('#loadingAsuransi').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil)) {
                            const list = data.tampil;
                            if ($.fn.DataTable.isDataTable('#dtRekapAsuransi')) $('#dtRekapAsuransi').DataTable().destroy();
                            if (list.length > 0) {
                                currentListAsuransi = list;
                                buildDailyChartAsuransi(list, currentMetricAsuransi);
                                $('#chartButtonsAsuransi').fadeIn();

                                let html = `<table id="dtRekapAsuransi" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-light"><tr><th>DPJP</th><th class="text-center">Jumlah</th><th class="text-right">Tarif RS</th><th class="text-right">Prosedur Non Bedah</th><th class="text-right">Prosedur Bedah</th><th class="text-right">Konsultasi</th><th class="text-right">Keperawatan</th><th class="text-right">Tenaga Ahli</th><th class="text-right">Laboratorium</th><th class="text-right">Radiologi</th><th class="text-right">Kamar & Akomodasi</th><th class="text-right">Konsultasi</th><th class="text-right">Obat</th><th class="text-right">BMHP</th></tr></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-primary">${item.jlm_ri}</td><td class="text-right">${parseNumericValue(item.tarif_rs).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.prosedur_non_bedah).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.prosedur_bedah).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.konsultasi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.keperawatan).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.tenaga_ahli).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.laboratorium).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.radiologi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.kamar_akomodasi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.konsultasi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.obat).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.bmhp).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableRekapAsuransi').html(html).fadeIn();
                                $('#hrAsuransi').fadeIn();
                                $('#dtRekapAsuransi').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    language: {
                                        search: "Cari:"
                                    }
                                });
                                $('#btnDownloadAsuransi').fadeIn();
                            } else {
                                $('#chartSectionAsuransi').hide();
                                $('#tableRekapAsuransi').html('<div class="alert alert-info text-center m-4">Tidak ada data rekap ASURANSI.</div>').fadeIn();
                            }
                        }
                    } catch (e) {
                        console.error(e);
                    }
                }
            });
        });

        // Load Detail ASURANSI (Default ASURANSI)
        function loadDetailAsuransi() {
            $('#tableDetailAsuransi').hide();
            $('#btnDownloadDetailAsuransi').hide();
            $('#loadingDetailAsuransi').show();
            $.ajax({
                url: '<?= base_url("detialtagihan/tampildataasuransi") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalAsuransi').val(),
                    TANGGAL_AKHIR: $('#tglAkhirAsuransi').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienAsuransi').val(),
                },
                success: function(res) {
                    $('#loadingDetailAsuransi').hide();
                    try {
                        const data = JSON.parse(res);
                        if (data && Array.isArray(data.response)) {
                            const list = data.response;
                            if ($.fn.DataTable.isDataTable('#dtTblDetailAsuransi')) $('#dtTblDetailAsuransi').DataTable().destroy();
                            if (list.length > 0) {
                                let html = `<table id="dtTblDetailAsuransi" class="table table-striped table-hover table-bordered w-100 text-nowrap"><thead class="bg-warning text-dark"><tr><th>DPJP</th><th class="text-center">Jml Pasien</th><th class="text-center">Pasien INACBG</th><th class="text-right">Total Tagihan</th><th class="text-right">Tagihan Pribadi</th><th class="text-right">Tagihan Penjamin</th><th class="text-right">Tarif INACBG</th></tr></thead><tbody>`;
                                list.forEach(item => {
                                    html += `<tr><td><strong>${item.dpjp}</strong></td><td class="text-center font-weight-bold text-info">${item.jumlah_pasien}</td><td class="text-center">${item.jumlah_pasien_ada_inacbg}</td><td class="text-right text-danger font-weight-bold">${parseNumericValue(item.total_tagihan).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_pribadi).toLocaleString('id-ID')}</td><td class="text-right">${parseNumericValue(item.total_tagihan_penjamin).toLocaleString('id-ID')}</td><td class="text-right text-success font-weight-bold">${parseNumericValue(item.total_tarif_inacbg).toLocaleString('id-ID')}</td></tr>`;
                                });
                                html += '</tbody></table>';
                                $('#tableDetailAsuransi').html(html).fadeIn();
                                $('#dtTblDetailAsuransi').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    pageLength: 8,
                                    language: {
                                        search: "Cari Detail:"
                                    }
                                });
                                $('#btnDownloadDetailAsuransi').fadeIn();
                            } else {
                                $('#tableDetailAsuransi').html('<div class="alert alert-info text-center m-4">Tidak ada data detail.</div>').fadeIn();
                            }
                        }
                    } catch (e) {}
                }
            });
        }

        // Toggle Buttons ASURANSI
        $('#btnDetailAsuransi').on('click', function() {
            $('.metric-btn-asuransi').removeClass('btn-primary btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            $(this).removeClass('btn-outline-secondary').addClass('btn-secondary active');
            $('#chartSectionAsuransi').hide();
            $('#detailContainerAsuransi').fadeIn();
            loadDetailAsuransi();
        });

        $('.metric-btn-asuransi').on('click', function() {
            $('#detailContainerAsuransi').hide();
            $('#chartSectionAsuransi').fadeIn();
            $('#btnDetailAsuransi').removeClass('btn-secondary active').addClass('btn-outline-secondary');
            const metric = $(this).data('metric');
            currentMetricAsuransi = metric;
            $('.metric-btn-asuransi').removeClass('btn-primary btn-warning active').addClass(function() {
                const m = $(this).data('metric');
                return m === 'tarif_rs' ? 'btn-outline-warning' : 'btn-outline-primary';
            });
            if (metric === 'jumlah') $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
            if (metric === 'tarif_rs') $(this).removeClass('btn-outline-warning').addClass('btn-warning active');
            if (currentListAsuransi.length > 0) buildDailyChartAsuransi(currentListAsuransi, metric);
        });

        $('#pembayaranDetailAsuransi').on('change', function() {
            loadDetailAsuransi();
        });

        $('#btnDownloadAsuransi').on('click', function() {
            window.location.href = `<?= base_url("keuangan/unduhrekapkeusirusnonbpjs_asuransi") ?>?TANGGAL_AWAL=${$('#tglAwalAsuransi').val()}&TANGGAL_AKHIR=${$('#tglAkhirAsuransi').val()}&KD_JENIS_PASIEN=${$('#jenisPasienAsuransi').val()}`;
        });
        $('#btnDownloadDetailAsuransi').on('click', function() {
            window.location.href = `<?= base_url("detialtagihan/unduhdataasuransi") ?>?TANGGAL_AWAL=${$('#tglAwalAsuransi').val()}&TANGGAL_AKHIR=${$('#tglAkhirAsuransi').val()}&KD_JENIS_PASIEN=${$('#jenisPasienAsuransi').val()}`;
        });
        $('#formAll').on('submit', function(e) {
            e.preventDefault();
            $('#containerAll').html('<div class="alert alert-warning text-center m-4">Kodingan AJAX BPJS & Non-BPJS belum ditambahkan.</div>');
        });
        $('#formHomecare').on('submit', function(e) {
            e.preventDefault();
            $('#containerHomecare').html('<div class="alert alert-warning text-center m-4">Kodingan AJAX Homecare belum ditambahkan.</div>');
        });


        // =====================================================================
        // LOGIKA TAB 4: ASURANSI TAHUNAN (DENGAN SLIDE SWITCH)
        // =====================================================================

        // 1. Logika Ubah Teks & Warna Label Switch
        $('#switchTipePasienTahunan').change(function() {
            if ($(this).is(':checked')) {
                // ON = Ranap
                $('#labelSwitchTahunan').text('Mode: Rawat Inap (Ranap)').css('color', '#dc3545');
            } else {
                // OFF = Rajal
                $('#labelSwitchTahunan').text('Mode: Rawat Jalan (Rajal)').css('color', '#17a2b8');
            }
        });

        // 2. Event Submit Filter
        $('#formTahunan').on('submit', function(e) {
            e.preventDefault();
            $('#loadingTahunan').show();
            $('#tableCardContainerTahunan').hide();
            $('#tableContainerTahunan').hide();

            const isRanap = $('#switchTipePasienTahunan').is(':checked');

            $.ajax({
                url: isRanap ? '<?= base_url("rekapasuransi/tampilrekap2") ?>' : '<?= base_url("rekapasuransi/tampilrekap1") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalTahunan').val()
                },
                success: function(response) {
                    $('#loadingTahunan').hide();

                    try {
                        const data = JSON.parse(response);

                        if (data && Array.isArray(data.response)) {
                            const list = data.response;

                            // Hancurkan DataTable lama jika ada
                            if ($.fn.DataTable.isDataTable('#dtTahunan')) {
                                $('#dtTahunan').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                let html = `
                                <div class="table-responsive w-100">
                                    <table id="dtTahunan" class="table table-striped table-hover mb-0 text-nowrap w-100">
                                `;

                                if (isRanap) {
                                    html += `
                                        <thead class="table-dark">
                                            <tr>
                                                <th>Urut</th>
                                                <th>Bulan</th>
                                                <th>Nama Asuransi</th>
                                                <th>Nama Dokter</th>
                                                <th>Jumlah</th>
                                                <th class="text-end">Tarif (Rp)</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;
                                    list.forEach(item => {
                                        // Pengecekan parseNumericValue (bawaan dari script Anda sebelumnya)
                                        let tarifVal = String(item.tarif).replace(/[^0-9\-\.]/g, '');
                                        tarifVal = tarifVal === '' ? 0 : parseFloat(tarifVal);
                                        let tarifFormat = tarifVal.toLocaleString('id-ID');

                                        html += `
                                            <tr>
                                                <td>${item.urut}</td>
                                                <td>${item.bulan}</td>
                                                <td class="fw-bold text-primary">${item.nama_asuransi}</td>
                                                <td class="fw-bold text-primary">${item.nm_dokter}</td>
                                                <td class="fw-bold text-primary">${item.qty}</td>
                                                <td class="text-end fw-bold">${tarifFormat}</td>
                                            </tr>`;
                                    });
                                } else {
                                    html += `
                                        <thead class="table-info"> 
                                            <tr>
                                                <th>No Urut</th>
                                                <th>Bulan</th>
                                                <th>Nama Asuransi</th>
                                                <th class="text-center">Jumlah (Qty)</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;
                                    list.forEach(item => {
                                        html += `
                                            <tr>
                                                <td>${item.urut}</td>
                                                <td>${item.bulan}</td>
                                                <td class="fw-bold">${item.nama_asuransi}</td>
                                                <td class="text-center"><span class="badge bg-secondary rounded-pill">${item.qty}</span></td>
                                            </tr>`;
                                    });
                                }

                                html += '</tbody></table></div>';

                                $('#tableContainerTahunan').html(html).show();
                                $('#tableCardContainerTahunan').fadeIn();

                                $('#dtTahunan').DataTable({
                                    dom: 'Bfrtip',
                                    responsive: false,
                                    scrollX: false,
                                    autoWidth: false,
                                    buttons: [{
                                            extend: 'excel',
                                            className: 'btn btn-sm btn-outline-success'
                                        },
                                        {
                                            extend: 'pdf',
                                            className: 'btn btn-sm btn-outline-danger'
                                        },
                                        {
                                            extend: 'print',
                                            className: 'btn btn-sm btn-outline-secondary'
                                        }
                                    ],
                                    language: {
                                        search: "_INPUT_",
                                        searchPlaceholder: "Cari data..."
                                    }
                                });

                                $('#btnDownloadTahunan').fadeIn();

                            } else {
                                $('#tableContainerTahunan').html('<div class="alert alert-warning m-3"><i class="fas fa-exclamation-triangle"></i> Tidak ada data ditemukan pada tahun tersebut.</div>').show();
                                $('#tableCardContainerTahunan').fadeIn();
                                $('#btnDownloadTahunan').hide();
                            }
                        } else {
                            $('#tableContainerTahunan').html('<div class="alert alert-warning m-3">Respon data kosong.</div>').show();
                            $('#tableCardContainerTahunan').fadeIn();
                            $('#btnDownloadTahunan').hide();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerTahunan').html('<div class="alert alert-danger m-3">Error: Data bukan JSON valid.</div>').show();
                        $('#tableCardContainerTahunan').fadeIn();
                        $('#btnDownloadTahunan').hide();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingTahunan').hide();
                    $('#tableContainerTahunan').html('<div class="alert alert-danger m-3">Gagal koneksi server.</div>').show();
                    $('#tableCardContainerTahunan').fadeIn();
                }
            });
        });

        // 3. Event Download Tahunan
        $('#btnDownloadTahunan').on('click', function() {
            const tanggalAwal = $('#tglAwalTahunan').val();
            const isRanap = $('#switchTipePasienTahunan').is(':checked');

            let urlDownload = isRanap ? '<?= base_url("rekapasuransi/unduhrekapkeuranap") ?>' : '<?= base_url("rekapasuransi/unduhrekapkeurajal") ?>';
            window.location.href = `${urlDownload}?TANGGAL_AWAL=${tanggalAwal}`;
        });


        // =====================================================================
        // LOGIKA TAB 5: BPJS & NON-BPJS
        // =====================================================================
        $('#formAll').on('submit', function(event) {
            event.preventDefault();
            $('#loadingAll').show();
            $('#tableCardContainerAll').hide();
            $('#tableContainerAll').hide();
            $('#btnDownloadAll').hide();

            $.ajax({
                url: '<?= base_url("billing/tampildatarekapbpjsnonbpjs") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalAll').val(),
                    TANGGAL_AKHIR: $('#tglAkhirAll').val()
                },
                success: function(response) {
                    $('#loadingAll').hide();

                    try {
                        const data = JSON.parse(response);

                        if (data && Array.isArray(data.response)) {
                            const list = data.response;

                            if ($.fn.DataTable.isDataTable('#dtAll')) {
                                $('#dtAll').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                let html = `
                                <table id="dtAll" class="table table-striped table-hover table-bordered w-100">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>Jenis Pasien</th>
                                            <th>Nama Pembayaran</th>
                                            <th class="text-center">Total</th>
                                        </tr>
                                    </thead>
                                <tbody>
                                `;

                                list.forEach(item => {
                                    html += `<tr>
                                        <td>${item.nm_jenis_pasien}</td>
                                        <td><strong>${item.nm_group_bayar}</strong></td>
                                        <td class="text-center fw-bold text-primary">${item.total}</td>
                                    </tr>`;
                                });
                                html += '</tbody></table>';

                                $('#tableContainerAll').html(html).fadeIn();
                                $('#tableCardContainerAll').fadeIn();

                                $('#dtAll').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    language: {
                                        search: "Cari Data:",
                                        lengthMenu: "Tampil _MENU_",
                                        info: "_START_-_END_ dari _TOTAL_"
                                    }
                                });

                                $('#btnDownloadAll').fadeIn();
                            } else {
                                $('#tableContainerAll').html('<div class="alert alert-info text-center m-4">Tidak ada data transaksi yang ditemukan.</div>').fadeIn();
                                $('#tableCardContainerAll').fadeIn();
                            }
                        } else {
                            $('#tableContainerAll').html('<div class="alert alert-warning text-center m-4">Respon data kosong.</div>').fadeIn();
                            $('#tableCardContainerAll').fadeIn();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerAll').html('<div class="alert alert-danger text-center m-4">Terjadi kesalahan saat memproses format data server.</div>').fadeIn();
                        $('#tableCardContainerAll').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingAll').hide();
                    console.error("AJAX Error: ", error);
                    $('#tableContainerAll').html('<div class="alert alert-danger text-center m-4">Koneksi ke server gagal.</div>').fadeIn();
                    $('#tableCardContainerAll').fadeIn();
                }
            });
        });

        $('#btnDownloadAll').on('click', function() {
            const tanggalAwal = $('#tglAwalAll').val();
            const tanggalAkhir = $('#tglAkhirAll').val();
            window.location.href = `<?= base_url("billing/unduhrekapbpjsnonbpjs") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });


        // =====================================================================
        // LOGIKA TAB 6: HOMECARE (DENGAN GRAFIK & DOWNLOAD GAMBAR)
        // =====================================================================
        let chartHomecareInstance = null;

        function renderGrafikHomecare(labels, dataTagihan) {
            const ctx = document.getElementById('dailyChartHomecare');
            if (!ctx) return;

            if (chartHomecareInstance) {
                chartHomecareInstance.destroy();
            }

            chartHomecareInstance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Total Pendapatan (Rp)',
                        data: dataTagihan,
                        backgroundColor: 'rgba(13, 110, 253, 0.8)', // Biru Bootstrap
                        borderColor: '#0b5ed7',
                        borderWidth: 1,
                        borderRadius: 4,
                        maxBarThickness: 50
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    let value = context.parsed.y || 0;
                                    return label + ': Rp ' + value.toLocaleString('id-ID');
                                }
                            }
                        },
                        datalabels: {
                            color: '#444',
                            anchor: 'end',
                            align: 'top',
                            offset: 4,
                            font: {
                                weight: 'bold',
                                size: 11
                            },
                            formatter: (value) => {
                                if (value > 0) return 'Rp ' + value.toLocaleString('id-ID');
                                return '';
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grace: '15%',
                            ticks: {
                                callback: function(value) {
                                    return 'Rp ' + value.toLocaleString('id-ID');
                                }
                            }
                        }
                    }
                }
            });
        }

        $('#formHomecare').on('submit', function(event) {
            event.preventDefault();
            $('#loadingHomecare').show();
            $('#tableContainerHomecare').hide();
            $('#tableCardContainerHomecare').hide();
            $('#grafikContainerHomecare').hide();
            $('#btnDownloadHomecare').hide();

            $.ajax({
                url: '<?= base_url("rekaphomecare/tampildatarekap") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tglAwalHomecare').val(),
                    TANGGAL_AKHIR: $('#tglAkhirHomecare').val()
                },
                success: function(response) {
                    $('#loadingHomecare').hide();

                    try {
                        const data = JSON.parse(response);

                        if (data && Array.isArray(data.response)) {
                            const list = data.response;

                            if ($.fn.DataTable.isDataTable('#dtHomecare')) {
                                $('#dtHomecare').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                let html = `
                                <table id="dtHomecare" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark text-center">
                                        <tr>
                                            <th>Nama Bulan</th>
                                            <th>Tahun</th>
                                            <th>Jumlah Pasien</th>
                                            <th>Total Tagihan</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                                let arrLabels = [];
                                let arrDataTagihan = [];

                                list.forEach(item => {
                                    html += `<tr>
                                        <td class="fw-bold">${item.bulan}</td>
                                        <td class="text-center">${item.tahun}</td>
                                        <td class="text-center">${item.jumlah_pasien}</td>
                                        <td class="text-end fw-bold text-success">${item.total_tagihan}</td>
                                    </tr>`;

                                    // Siapkan data grafik
                                    if (item.bulan && item.tahun) {
                                        arrLabels.push(item.bulan + ' ' + item.tahun);
                                        // Bersihkan format "Rp. 5.000" jadi angka 5000
                                        let rawTagihan = item.total_tagihan ? item.total_tagihan.toString().replace(/[^0-9]/g, '') : 0;
                                        arrDataTagihan.push(parseFloat(rawTagihan));
                                    }
                                });
                                html += '</tbody></table>';

                                $('#tableContainerHomecare').html(html).show();
                                $('#tableCardContainerHomecare').fadeIn();

                                $('#dtHomecare').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    order: [
                                        [1, "asc"]
                                    ],
                                    language: {
                                        search: "Cari Data:",
                                        lengthMenu: "Tampil _MENU_"
                                    }
                                });

                                $('#btnDownloadHomecare').fadeIn();

                                // Render Grafik jika ada data
                                if (arrLabels.length > 0) {
                                    $('#grafikContainerHomecare').fadeIn();
                                    renderGrafikHomecare(arrLabels, arrDataTagihan);
                                }

                            } else {
                                $('#tableContainerHomecare').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Tidak ada data Homecare yang ditemukan.</div>').show();
                                $('#tableCardContainerHomecare').fadeIn();
                            }
                        } else {
                            $('#tableContainerHomecare').html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>').show();
                            $('#tableCardContainerHomecare').fadeIn();
                        }
                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainerHomecare').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>').show();
                        $('#tableCardContainerHomecare').fadeIn();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingHomecare').hide();
                    $('#tableContainerHomecare').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal terhubung ke server.</div>').show();
                    $('#tableCardContainerHomecare').fadeIn();
                }
            });
        });

        // Event Download EXCEL Homecare
        $('#btnDownloadHomecare').on('click', function() {
            const tanggalAwal = $('#tglAwalHomecare').val();
            const tanggalAkhir = $('#tglAkhirHomecare').val();
            window.location.href = `<?= base_url("rekaphomecare/unduhdatarekap") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });

        // Event Download GAMBAR Grafik Homecare
        $('#btnDownloadChartHomecare').on('click', function(e) {
            e.preventDefault();
            const canvas = document.getElementById("dailyChartHomecare");
            if (canvas) {
                const imageURL = canvas.toDataURL("image/jpeg", 1.0); // 1.0 for max quality
                const link = document.createElement("a");
                link.download = "Grafik_Pendapatan_Homecare.jpeg";
                link.href = imageURL;
                link.click();
            } else {
                Swal.fire('Info', 'Grafik belum siap diunduh.', 'info');
            }
        });


        // =====================================================================
        // LOGIKA TAB 7: BPJS PER-KSM
        // =====================================================================
        let dailyChartBpjsksm = null;
        let currentListBpjsksm = [];
        let currentMetricBpjsksm = 'jml';

        const buildDailyChartBpjsksm = (list, metric = 'jml') => {
        const chartContainer = $('#chartSectionBpjsksm');
        const ctx = document.getElementById('dailyChartBpjsksm').getContext('2d');
        if (!Array.isArray(list) || list.length === 0) {
            chartContainer.hide();
            return;
        }

        const metricConfig = {
            jml: {
                label: 'Jumlah Pasien',
                field: 'jml',
                colors: {
                    bg: (ctx) => {
                        const grad = ctx.chart.ctx.createLinearGradient(0, 0, 0, 400);
                        grad.addColorStop(0, 'rgba(54, 162, 235, 0.9)');
                        grad.addColorStop(1, 'rgba(54, 162, 235, 0.3)');
                        return grad;
                    },
                    border: 'rgba(37, 99, 235, 1)',
                    datalabel: '#1d4ed8'
                },
                fmt: v => `${v} pasien`
            },
            tarif_bpjs: {
                label: 'Tarif BPJS',
                field: 'tarif_bpjs',
                colors: {
                    bg: (ctx) => {
                        const grad = ctx.chart.ctx.createLinearGradient(0, 0, 0, 400);
                        grad.addColorStop(0, 'rgba(16, 185, 129, 0.9)');
                        grad.addColorStop(1, 'rgba(16, 185, 129, 0.3)');
                        return grad;
                    },
                    border: 'rgba(5, 150, 105, 1)',
                    datalabel: '#065f46'
                },
                fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
            },
            tarif_rs: {
                label: 'Tarif RS',
                field: 'tarif_rs',
                colors: {
                    bg: (ctx) => {
                        const grad = ctx.chart.ctx.createLinearGradient(0, 0, 0, 400);
                        grad.addColorStop(0, 'rgba(245, 158, 11, 0.9)');
                        grad.addColorStop(1, 'rgba(245, 158, 11, 0.3)');
                        return grad;
                    },
                    border: 'rgba(217, 119, 6, 1)',
                    datalabel: '#92400e'
                },
                fmt: v => `Rp ${Number(v).toLocaleString('id-ID')}`
            },
        };

        const cfg = metricConfig[metric] || metricConfig['jml'];

        const grouped = {};
        list.forEach(item => {
            const ksm = item.nm_spesialis || 'Tidak Diketahui';
            if (!grouped[ksm]) grouped[ksm] = { jml: 0, tarif_bpjs: 0, tarif_rs: 0 };
            grouped[ksm].jml        += parseNumericValue(item.jml);
            grouped[ksm].tarif_bpjs += parseNumericValue(item.tarif_bpjs);
            grouped[ksm].tarif_rs   += parseNumericValue(item.tarif_rs);
        });

        const labels = Object.keys(grouped).sort((a, b) => grouped[b][cfg.field] - grouped[a][cfg.field]);
        const values = labels.map(k => grouped[k][cfg.field]);
        const maxVal = Math.max(...values);

        if (dailyChartBpjsksm) dailyChartBpjsksm.destroy();

        dailyChartBpjsksm = new Chart(ctx, {
            type: 'bar',
            data: {
                labels,
                datasets: [{
                    label: cfg.label,
                    data: values,
                    backgroundColor: cfg.colors.bg,
                    borderColor: cfg.colors.border,
                    borderWidth: 2,
                    borderRadius: 8,
                    borderSkipped: false,
                    maxBarThickness: 45,
                    hoverBackgroundColor: cfg.colors.border,
                    hoverBorderWidth: 2,
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                animation: {
                    duration: 600,
                    easing: 'easeOutQuart'
                },
                layout: {
                    padding: { top: 30, right: 10, bottom: 0, left: 10 }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                        align: 'end',
                        labels: {
                            boxWidth: 12,
                            boxHeight: 12,
                            borderRadius: 4,
                            useBorderRadius: true,
                            font: { size: 12, weight: '600' },
                            color: '#374151'
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(17, 24, 39, 0.92)',
                        titleColor: '#f9fafb',
                        bodyColor: '#d1d5db',
                        padding: 12,
                        cornerRadius: 8,
                        displayColors: true,
                        callbacks: {
                            title: items => items[0].label,
                            label: item => ` ${cfg.label}: ${cfg.fmt(item.raw)}`
                        }
                    },
                    datalabels: {
                        anchor: 'end',
                        align: 'end',
                        offset: 4,
                        font: { size: 10, weight: 'bold' },
                        color: cfg.colors.datalabel,
                        formatter: value => {
                            if (metric === 'jml') return value;
                            // Singkat angka besar: 1.2 Jt, 500 Rb
                            if (value >= 1_000_000_000) return `${(value / 1_000_000_000).toFixed(1)} M`;
                            if (value >= 1_000_000)     return `${(value / 1_000_000).toFixed(1)} Jt`;
                            if (value >= 1_000)         return `${(value / 1_000).toFixed(0)} Rb`;
                            return value;
                        },
                        clip: false
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        border: { display: false },
                        ticks: {
                            autoSkip: false,
                            maxRotation: 40,
                            minRotation: 20,
                            font: { size: 11, weight: '500' },
                            color: '#6b7280',
                            // Potong label panjang agar tidak terlalu penuh
                            callback: function(val) {
                                const label = this.getLabelForValue(val);
                                return label.length > 18 ? label.substring(0, 17) + '…' : label;
                            }
                        }
                    },
                    y: {
                        grid: {
                            color: 'rgba(107, 114, 128, 0.1)',
                            drawBorder: false
                        },
                        border: { display: false, dash: [4, 4] },
                        beginAtZero: true,
                        suggestedMax: maxVal * 1.2,
                        ticks: {
                            font: { size: 11 },
                            color: '#9ca3af',
                            callback: v => {
                                if (metric === 'jml') return v;
                                if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(0)} M`;
                                if (v >= 1_000_000)     return `${(v / 1_000_000).toFixed(0)} Jt`;
                                if (v >= 1_000)         return `${(v / 1_000).toFixed(0)} Rb`;
                                return v;
                            }
                        }
                    }
                }
            }
        });

        chartContainer.fadeIn();
    };
        $('#formBpjsksm').on('submit', function(event) {
            event.preventDefault();

            $('#resultBpjsksm').show();
            $('#chartSectionBpjsksm').hide();
            $('#tableContainerBpjsksm').hide();
            $('#hrBpjsksm').hide();
            $('#chartButtonsBpjsksm').hide();
            $('#btnDownloadBpjsksm').hide();

            $('.metric-btn-bpjsksm')
                .removeClass('active btn-primary btn-success btn-warning')
                .addClass(function() {
                    const m = $(this).data('metric');
                    if (m === 'tarif_bpjs') return 'btn-outline-success';
                    if (m === 'tarif_rs')   return 'btn-outline-warning';
                    return 'btn-outline-primary';
                });
            $('.metric-btn-bpjsksm[data-metric="jml"]')
                .removeClass('btn-outline-primary')
                .addClass('btn-primary active');
            currentMetricBpjsksm = 'jml';

            $('#loadingBpjsksm').show();

            $.ajax({
                url: '<?= base_url("keuangan/tampilrekapbpjsperksm") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL:    $('#tglAwalBpjsksm').val(),
                    TANGGAL_AKHIR:   $('#tglAkhirBpjsksm').val(),
                    KD_JENIS_PASIEN: $('#jenisPasienBpjsksm').val()
                },
                success: function(tampil) {
                    $('#loadingBpjsksm').hide();
                    try {
                        const data = JSON.parse(tampil);

                        if (data && Array.isArray(data.tampil)) {
                            const list = data.tampil;

                            if ($.fn.DataTable.isDataTable('#dtBpjsksm')) {
                                $('#dtBpjsksm').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                //currentListBpjsksm = list;
                                //buildDailyChartBpjsksm(list, currentMetricBpjsksm);
                                //$('#chartButtonsBpjsksm').fadeIn();

                                let html = `
                                <table id="dtBpjsksm" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>Nama Spesialis</th>
                                            <th class="text-center">Jumlah</th>
                                            <th class="text-right">Tarif BPJS</th>
                                            <th class="text-right">Tarif RS</th>
                                            <th class="text-right">Prosedur Non Bedah</th>
                                            <th class="text-right">Prosedur Bedah</th>
                                            <th class="text-right">Konsultasi</th>
                                            <th class="text-right">Tenaga Ahli</th>
                                            <th class="text-right">Keperawatan</th>
                                            <th class="text-right">Penunjang</th>
                                            <th class="text-right">Radiologi</th>
                                            <th class="text-right">Laboratorium</th>
                                            <th class="text-right">Pelayanan Darah</th>
                                            <th class="text-right">Rehabilitasi</th>
                                            <th class="text-right">Kamar Akomodasi</th>
                                            <th class="text-right">Rawat Intensif</th>
                                            <th class="text-right">Obat</th>
                                            <th class="text-right">Alkes</th>
                                            <th class="text-right">BMHP</th>
                                            <th class="text-right">Sewa Alat</th>
                                        </tr>
                                    </thead>
                                    <tbody>`;

                                list.forEach(item => {
                                    html += `<tr>
                                        <td><strong>${item.nm_spesialis}</strong></td>
                                        <td class="text-center font-weight-bold text-primary">${item.jml}</td>
                                        <td class="text-right">${parseNumericValue(item.tarif_bpjs).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.tarif_rs).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.prosedur_non_bedah).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.prosedur_bedah).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.konsultasi).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.tenaga_ahli).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.keperawatan).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.penunjang).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.radiologi).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.laboratorium).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.pelayanan_darah).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.rehabilitasi).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.kamar_akomodasi).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.rawat_intensif).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.obat).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.alkes).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.bmhp).toLocaleString('id-ID')}</td>
                                        <td class="text-right">${parseNumericValue(item.sewa_alat).toLocaleString('id-ID')}</td>
                                    </tr>`;
                                });

                                html += '</tbody></table>';
                                $('#tableContainerBpjsksm').html(html).fadeIn();
                                $('#hrBpjsksm').fadeIn();

                                $('#dtBpjsksm').DataTable({
                                    responsive: false,
                                    autoWidth: false,
                                    language: { search: "Cari:" }
                                });

                                $('#btnDownloadBpjsksm').fadeIn();

                            } else {
                                $('#tableContainerBpjsksm')
                                    .html('<div class="alert alert-info text-center m-4">Tidak ada data rekap BPJS PER-KSM.</div>')
                                    .fadeIn();
                            }

                        } else {
                            $('#tableContainerBpjsksm')
                                .html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>')
                                .fadeIn();
                        }

                    } catch (e) {
                        console.error("Error parsing JSON:", e);
                        $('#tableContainerBpjsksm')
                            .html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>')
                            .fadeIn();
                    }
                },
                error: function() {
                    $('#loadingBpjsksm').hide();
                    $('#tableContainerBpjsksm')
                        .html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal terhubung ke server.</div>')
                        .fadeIn();
                }
            });
        });

        $('.metric-btn-bpjsksm').on('click', function() {
            const metric = $(this).data('metric');
            currentMetricBpjsksm = metric;

            $('.metric-btn-bpjsksm')
                .removeClass('btn-primary btn-success btn-warning active')
                .addClass(function() {
                    const m = $(this).data('metric');
                    if (m === 'tarif_bpjs') return 'btn-outline-success';
                    if (m === 'tarif_rs')   return 'btn-outline-warning';
                    return 'btn-outline-primary';
                });

            if (metric === 'jml')        $(this).removeClass('btn-outline-primary').addClass('btn-primary active');
            if (metric === 'tarif_bpjs') $(this).removeClass('btn-outline-success').addClass('btn-success active');
            if (metric === 'tarif_rs')   $(this).removeClass('btn-outline-warning').addClass('btn-warning active');

            if (currentListBpjsksm.length > 0) buildDailyChartBpjsksm(currentListBpjsksm, metric);
        });

        $('#btnDownloadBpjsksm').on('click', function() {
            window.location.href = `<?= base_url("keuangan/unduhrekapbpjsrekapksm") ?>?TANGGAL_AWAL=${$('#tglAwalBpjsksm').val()}&TANGGAL_AKHIR=${$('#tglAkhirBpjsksm').val()}&KD_JENIS_PASIEN=${$('#jenisPasienBpjsksm').val()}`;
        });

    });
</script>