<style>
    /* ========================================================
       1. CSS CORE RESPONSIVE (ANTI HALAMAN JEBOL)
       ======================================================== */
    body,
    html {
        overflow-x: hidden !important;
        width: 100%;
        max-width: 100vw;
    }

    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
            width: 100% !important;
            max-width: 100vw !important;
        }

        .container-fluid {
            padding-left: 10px !important;
            padding-right: 10px !important;
        }
    }

    #layoutSidenav_content {
        width: 100%;
        max-width: 100vw;
        overflow-x: hidden !important;
    }

    table,
    table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse !important;
    }

    .card {
        width: 100% !important;
        max-width: 100% !important;
        min-width: 0 !important;
        overflow-x: hidden;
    }

    .table-responsive {
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        border: none;
    }

    /* ========================================================
       2. STYLING TAB / PILLS (PERBAIKAN SCROLL HORIZONTAL)
       ======================================================== */
    .nav-pills .nav-link {
        border-radius: 50px;
        padding: 8px 16px;
        font-weight: 500;
        margin-right: 10px;
        margin-bottom: 10px;
        border: 1px solid #e3e6f0;
        color: #5a5c69;
        background-color: #fff;
        white-space: nowrap;
        cursor: pointer;
    }

    .nav-pills .nav-link.active,
    .nav-pills .nav-link:hover {
        background-color: #007bff;
        color: #fff;
        border-color: #007bff;
    }

    .nav-pills {
        flex-wrap: nowrap;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        padding-bottom: 5px;
    }

    .nav-pills::-webkit-scrollbar {
        height: 4px;
    }

    .nav-pills::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .nav-pills::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }

    /* ========================================================
       3. STYLING KOTAK FILTER & SELECT2 (PERBAIKAN UI SEARCH)
       ======================================================== */
    .filter-wrapper {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    /* Modifikasi Select2 Default agar mirip Bootstrap 5 (FIXED) */
    .select2-container .select2-selection--single {
        height: 38px !important;
        border: 1px solid #ced4da !important;
        border-radius: 0.375rem !important;
        background-color: #fff !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 36px !important;
        color: #495057 !important;
        padding-left: 12px !important;
        padding-right: 40px !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 36px !important;
        right: 8px !important;
    }

    .select2-container--default .select2-selection__clear {
        position: absolute !important;
        right: 30px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        margin: 0 !important;
        color: #dc3545 !important;
        font-size: 1.2rem !important;
        font-weight: bold;
        z-index: 10;
    }

    .select2-dropdown {
        border: 1px solid #ced4da !important;
        border-radius: 0.375rem !important;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .select2-search--dropdown .select2-search__field {
        border-radius: 4px !important;
        border: 1px solid #ced4da !important;
        padding: 6px 10px !important;
    }

    @media (max-width: 768px) {
        .filter-wrapper .form-group {
            margin-bottom: 12px;
        }

        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 10px;
        }

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

        div.dataTables_wrapper div.dataTables_filter input {
            width: 140px !important;
        }
    }

    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
            height: 100%;
            padding-bottom: 2px;
        }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 overflow-hidden">
            <h1 class="mt-4 fs-3" id="judulPasien">Data Farmasi</h1>
            <ol class="breadcrumb mb-4 shadow-sm bg-white p-2 rounded">
                <li class="breadcrumb-item"><a href="index.html" class="text-decoration-none text-muted">Dashboard</a></li>
                <li class="breadcrumb-item active">Farmasi</li>
            </ol>

            <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active shadow-sm" id="pills-penjualan-tab" data-bs-toggle="pill" href="#pills-penjualan" role="tab">
                        <i class="fas fa-shopping-cart me-2"></i>Farmasi Penjualan
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="pills-penjualanperobt-tab" data-bs-toggle="pill" href="#pills-penjualanperobt" role="tab">
                        <i class="fas fa-solid fa-file-medical me-2"></i>Farmasi Penjualan Per-obat
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="pills-psikotropik-tab" data-bs-toggle="pill" href="#pills-psikotropik" role="tab">
                        <i class="fas fa-capsules me-2"></i>Data Obat Psikotropik
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="pills-narkotik-tab" data-bs-toggle="pill" href="#pills-narkotik" role="tab">
                        <i class="fas fa-pills me-2"></i>Data Obat Narkotik
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="pills-
                    -tab" data-bs-toggle="pill" href="#pills-OOT" role="tab">
                        <i class="fas fa-pills me-2"></i>Data Obat OOT
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link shadow-sm" id="pills-prekusor-tab" data-bs-toggle="pill" href="#pills-prekusor" role="tab">
                        <i class="fas fa-pills me-2"></i>Data Obat Prekusor
                    </a>
                </li>
            </ul>

            <div class="tab-content" id="pills-tabContent">

                <div class="tab-pane fade show active" id="pills-penjualan" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Penjualan</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormPenjualan">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Jenis Pembayaran</label>
                                        <select id="kd_group_bayar" name="kd_group_bayar" class="form-select" required>
                                            <option value="" disabled selected>Pilih Pembayaran</option>
                                            <option value="1">BPJS</option>
                                            <option value="2">ASURANSI</option>
                                            <option value="0">UMUM</option>
                                        </select>
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-3 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="pills-penjualanperobt" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Penjualan Per-Obat</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormPenjualanperobt">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal_perobat" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir_perobat" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <label class="form-label text-muted small fw-bold mb-1">Pilih Obat</label>
                                        <div style="width: 100%;">
                                            <select id="kd_refobat" name="KD_OBAT" class="form-control" required style="width: 100%;">
                                                <option value="" disabled selected>Memuat Kode Obat...</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-12 col-md-2">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary w-100 shadow-sm"><i class="fas fa-search me-1"></i> Cari</button>
                                        </div>
                                    </div>
                                    <div class="col-12 mt-2">
                                        <button type="button" id="downloadButton_perobat" class="btn btn-success shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download Excel</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon_perobat" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer_perobat" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="pills-narkotik" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Obat Narkotik</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormNarkotik">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal_narko" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir_narko" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-6">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-3 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton_narko" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon_narko" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer_narko" style="display: none;"></div>
                        </div>
                    </div>
                </div>

                <div class="tab-pane fade" id="pills-psikotropik" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Obat Psikotropik</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormPsiokotropik">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal_psiko" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir_psiko" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-6">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-3 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton_psiko" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon_psiko" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer_psiko" style="display: none;"></div>
                        </div>
                    </div>
                </div>


                <div class="tab-pane fade" id="pills-OOT" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Obat OOT</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormOOT">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal_oot" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir_oot" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-6">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-3 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton_oot" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon_oot" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer_oot" style="display: none;"></div>
                        </div>
                    </div>
                </div>


                <div class="tab-pane fade" id="pills-prekusor" role="tabpanel">
                    <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Obat Prekusor</h5>
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body filter-wrapper">
                            <form id="filterFormprekusor">
                                <div class="row g-2 align-items-end">
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                        <input type="date" id="tanggal_awal_prekusor" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                    </div>
                                    <div class="col-12 col-md-3">
                                        <label class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                        <input type="date" id="tanggal_akhir_prekusor" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                                    </div>
                                    <div class="col-12 col-md-6">
                                        <div class="btn-group-custom mt-3 mt-md-0">
                                            <button type="submit" class="btn btn-primary px-3 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                            <button type="button" id="downloadButton_prekusor" class="btn btn-success px-3 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Excel</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm mb-5">
                        <div class="card-body p-2 p-md-3">
                            <div id="loadingIcon_prekusor" style="display: none;" class="py-5 text-center">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            </div>
                            <div id="tableContainer_prekusor" style="display: none;"></div>
                        </div>
                    </div>
                </div>

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

    <div class="modal fade" id="modalDetailObat" tabindex="-1" aria-labelledby="modalDetailLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title font-weight-bold" id="modalDetailLabel">
                        <i class="fas fa-info-circle me-2"></i> Rincian Data Obat
                    </h5>
                    <button type="button" id="btnCloseAtas" class="close text-white border-0 bg-transparent fs-4" data-dismiss="modal" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body p-4">
                    <div class="row mb-3 pb-3 border-bottom">
                        <div class="col-md-6">
                            <p class="mb-1 text-muted small fw-bold">Kode Obat</p>
                            <h6 id="popupKodeObat" class="font-weight-bold text-dark">-</h6>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 text-muted small fw-bold">Nama Obat</p>
                            <h6 id="popupNamaObat" class="font-weight-bold text-primary">-</h6>
                        </div>
                    </div>

                    <div id="popupIsiKonten" class="text-center py-4">
                        <p class="text-muted mb-0">Klik elemen untuk melihat detail di sini.</p>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" id="btnCloseBawah" class="btn btn-secondary px-4" data-dismiss="modal" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>


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

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

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

        // SCRIPTUNTUK TUTUP POP-UP
        $('#btnCloseAtas, #btnCloseBawah').on('click', function(e) {
            e.preventDefault();
            $('#modalDetailObat').modal('hide'); // Memaksa pop up tertutup
        });

        // SETUP SELECT2
        $('#kd_refobat').select2({
            width: '100%',
            allowClear: true
        });

        function loadMasterobat() {
            const grupMasterobtDropdown = $('#kd_refobat');
            $.ajax({
                url: '<?php echo base_url("penjualanperobat/refrensiobat"); ?>',
                type: 'POST',
                dataType: 'json',
                success: function(data) {
                    grupMasterobtDropdown.empty().append('<option value="" disabled selected>Ketik / Cari Nama Obat</option>');
                    if (data && Array.isArray(data.response)) {
                        $.each(data.response, function(index, kodeobat) {
                            const option = new Option(kodeobat.nama_obat, kodeobat.kd_obat);
                            grupMasterobtDropdown.append(option);
                        });
                        grupMasterobtDropdown.trigger('change');
                    }
                },
                error: function() {
                    grupMasterobtDropdown.empty().append('<option value="" disabled selected>Gagal memuat Data</option>');
                }
            })
        }
        loadMasterobat();

        // ==========================================
        // LOGIKA TAB 1: PENJUALAN FARMASI
        // ==========================================
        $('#filterFormPenjualan').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon').show();
            $('#tableContainer').hide();

            var tglAwal = $('#tanggal_awal').val();
            var tglAkhir = $('#tanggal_akhir').val();
            var kdBayar = $('#kd_group_bayar').val();

            $.ajax({
                url: '<?= base_url("farmasi/penjualanfarmasi") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir,
                    KD_GROUP_BAYAR: kdBayar
                },
                success: function(response) {
                    $('#loadingIcon').hide();
                    try {
                        const data = JSON.parse(response);
                        if (data && Array.isArray(data.response) && data.response.length > 0) {

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

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesSimple" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Tanggal</th>
                                            <th>Kode RM</th>
                                            <th>Nama</th>
                                            <th>Jenis Pasien</th>
                                            <th>Penjamin</th>
                                            <th>Nama Obat</th>
                                            <th class="text-center">Jumlah</th>
                                            <th>Nama Grup Bayar</th>
                                            <th class="text-end">Total</th>
                                        </tr>
                                    </thead>
                            <tbody>`;

                            data.response.forEach(item => {
                                html += `<tr>
                                    <td>${item.tgl_jual}</td>
                                    <td>${item.kd_rekam_medis}</td>
                                    <td class="text-wrap" style="min-width:150px;">${item.nama}</td>
                                    <td>${item.nm_jenis_pasien}</td>
                                    <td>${item.nm_pembayaran}</td>
                                    <td class="text-wrap" style="min-width:200px;">${item.nama_obat}</td>
                                    <td class="text-center fw-bold">${item.qty_jual}</td>
                                    <td>${item.nm_group_bayar}</td>
                                    <td class="text-end fw-bold text-success">${parseFloat(item.total||0).toLocaleString('id-ID')}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer').html(html).show();
                            $('#datatablesSimple').DataTable({
                                "order": [
                                    [0, "asc"]
                                ],
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                                language: {
                                    search: "Cari Data:",
                                    lengthMenu: "Tampil _MENU_"
                                }
                            });
                            $('#downloadButton').show();
                        } else {
                            $('#tableContainer').html('<div class="alert alert-info small m-3">Tidak ada data.</div>').show();
                            $('#downloadButton').hide();
                        }
                    } catch (e) {
                        $('#tableContainer').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                        $('#loadingIcon').hide();
                    }
                },
                error: function() {
                    $('#loadingIcon').hide();
                    alert("Gagal koneksi server.");
                }
            });
        });

        $('#downloadButton').on('click', function() {
            const ta = $('#tanggal_awal').val();
            const tak = $('#tanggal_akhir').val();
            const kb = $('#kd_group_bayar').val();
            window.location.href = `<?= base_url("farmasi/unduhpenjualanfarmasi") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}&KD_GROUP_BAYAR=${kb}`;
        });

        // ==========================================
        // LOGIKA TAB 2: PENJUALAN PER OBAT
        // ==========================================
        $('#filterFormPenjualanperobt').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon_perobat').show();
            $('#tableContainer_perobat').hide();

            var tglAwal = $('#tanggal_awal_perobat').val();
            var tglAkhir = $('#tanggal_akhir_perobat').val();
            var kdObat = $('#kd_refobat').val();

            $.ajax({
                url: '<?= base_url("penjualanperobat/tampildataobt") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir,
                    KD_OBAT: kdObat
                },
                success: function(response) {
                    $('#loadingIcon_perobat').hide();
                    try {
                        const data = JSON.parse(response);
                        if (data && Array.isArray(data.response) && data.response.length > 0) {

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

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesPerObat" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Tanggal</th>
                                            <th>KD Registrasi</th>
                                            <th>Kode RM</th>
                                            <th>Nama</th>
                                            <th>Jenis Pasien</th>
                                            <th>Penjamin</th>
                                            <th>Kode Obat</th>
                                            <th>Nama Obat</th>
                                            <th class="text-center">Jumlah</th>
                                            <th>Nama Grup Bayar</th>
                                            <th class="text-end">Total</th>
                                        </tr>
                                    </thead>
                            <tbody>`;

                            data.response.forEach(item => {
                                html += `<tr>
                                    <td>${item.tgl_jual}</td>
                                    <td>${item.kd_registrasi}</td>
                                    <td>${item.kd_rekam_medis}</td>
                                    <td class="text-wrap" style="min-width:150px;">${item.nama}</td>
                                    <td>${item.nm_jenis_pasien}</td>
                                    <td>${item.nm_pembayaran}</td>
                                    <td>${item.kd_obat}</td>
                                    <td class="text-wrap" style="min-width:200px;">${item.nama_obat}</td>
                                    <td class="text-center fw-bold">${item.qty_jual}</td>
                                    <td>${item.nm_group_bayar}</td>
                                    <td class="text-end fw-bold text-success">${parseFloat(item.total||0).toLocaleString('id-ID')}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer_perobat').html(html).show();
                            $('#datatablesPerObat').DataTable({
                                "order": [
                                    [0, "asc"]
                                ],
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                                language: {
                                    search: "Cari Data:",
                                    lengthMenu: "Tampil _MENU_"
                                }
                            });
                            $('#downloadButton_perobat').show();
                        } else {
                            $('#tableContainer_perobat').html('<div class="alert alert-info small m-3">Tidak ada data.</div>').show();
                            $('#downloadButton_perobat').hide();
                        }
                    } catch (e) {
                        $('#tableContainer_perobat').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                        $('#loadingIcon_perobat').hide();
                    }
                },
                error: function() {
                    $('#loadingIcon_perobat').hide();
                    alert("Gagal koneksi server.");
                }
            });
        });

        $('#downloadButton_perobat').on('click', function() {
            const ta = $('#tanggal_awal_perobat').val();
            const tak = $('#tanggal_akhir_perobat').val();
            const kdf = $('#kd_refobat').val();
            window.location.href = `<?= base_url("penjualanperobat/unduhdataobt") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}&KD_OBAT=${kdf}`;
        });

        // ==========================================
        // LOGIKA TAB 3: NARKOTIK 
        // ==========================================
        $('#filterFormNarkotik').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon_narko').show();
            $('#tableContainer_narko').hide();

            var tglAwal = $('#tanggal_awal_narko').val();
            var tglAkhir = $('#tanggal_akhir_narko').val();

            $.ajax({
                url: '<?= base_url("farmasi/tampildatanarkotika") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir
                },
                success: function(tampil) {
                    $('#loadingIcon_narko').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil) && data.tampil.length > 0) {
                            if ($.fn.DataTable.isDataTable('#datatablesNarkotik')) {
                                $('#datatablesNarkotik').DataTable().destroy();
                            }

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesNarkotik" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Kode Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Satuan</th>
                                            <th class="text-center">Jml Masuk</th>
                                            <th class="text-center">Jml Keluar</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                            data.tampil.forEach(item => {
                                html += `<tr>
                                    <td>${item.kd_obat}</td>
                                    
                                    <td class="text-primary font-weight-bold btn-popup-detail text-wrap" 
                                        style="cursor: pointer; text-decoration: underline; min-width:200px;" 
                                        data-jenis="Detail Obat" 
                                        data-kode="${item.kd_obat}" 
                                        data-nama="${item.nama_obat}">
                                        ${item.nama_obat}
                                    </td>
                                    
                                    <td>${item.nm_satuan}</td>
                                    
                                    <td class="text-center fw-bold text-success btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Masuk" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_masuk}</td>
                                    <td class="text-center fw-bold text-danger btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Keluar" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_keluar}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer_narko').html(html).show();
                            $('#datatablesNarkotik').DataTable({
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
                            });
                            $('#downloadButton_narko').show();
                        } else {
                            $('#tableContainer_narko').html('<div class="alert alert-info small m-3">Tidak ada data narkotik.</div>').show();
                            $('#downloadButton_narko').hide();
                        }
                    } catch (e) {
                        $('#tableContainer_narko').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                    }
                },
                error: function() {
                    $('#loadingIcon_narko').hide();
                    alert("Gagal koneksi server.");
                }
            });
        });

        $('#downloadButton_narko').on('click', function() {
            const ta = $('#tanggal_awal_narko').val();
            const tak = $('#tanggal_akhir_narko').val();
            window.location.href = `<?= base_url("farmasi/unduhdatanarkotika") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
        });

        // ==========================================
        // LOGIKA TAB 4: PSIKOTROPIK
        // ==========================================
        $('#filterFormPsiokotropik').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon_psiko').show();
            $('#tableContainer_psiko').hide();

            var tglAwal = $('#tanggal_awal_psiko').val();
            var tglAkhir = $('#tanggal_akhir_psiko').val();

            $.ajax({
                url: '<?= base_url("farmasi/tampildatapsiko") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir
                },
                success: function(tampil) {
                    $('#loadingIcon_psiko').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil) && data.tampil.length > 0) {

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

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesPsikotropik" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Kode Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Satuan</th>
                                            <th class="text-center">Jml Masuk</th>
                                            <th class="text-center">Jml Keluar</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                            data.tampil.forEach(item => {
                                html += `<tr>
                                    <td>${item.kd_obat}</td>
                                    <td class="text-primary font-weight-bold btn-popup-detail text-wrap" 
                                        style="cursor: pointer; text-decoration: underline; min-width:200px;" 
                                        data-jenis="Detail Obat" 
                                        data-kode="${item.kd_obat}" 
                                        data-nama="${item.nama_obat}">
                                        ${item.nama_obat}
                                    </td>
                                    <td>${item.nm_satuan}</td>
                                    <td class="text-center fw-bold text-success btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Masuk" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_masuk}</td>
                                    <td class="text-center fw-bold text-danger btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Keluar" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_keluar}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer_psiko').html(html).show();
                            $('#datatablesPsikotropik').DataTable({
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
                            });
                            $('#downloadButton_psiko').show();
                        } else {
                            $('#tableContainer_psiko').html('<div class="alert alert-info small m-3">Tidak ada data Psikotropik.</div>').show();
                            $('#downloadButton_psiko').hide();
                        }
                    } catch (e) {
                        $('#tableContainer_psiko').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                    }
                },
                error: function() {
                    $('#loadingIcon_psiko').hide();
                    alert("Gagal koneksi server.");
                }
            });

            $('#downloadButton_narko').on('click', function() {
                const ta = $('#tanggal_awal_psiko').val();
                const tak = $('#tanggal_akhir_psiko').val();
                window.location.href = `<?= base_url("farmasi/unduhdatapsiko") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
            });

        });


        // TAB OBAT OOT TAMPIL DATA 
        // ==========================================
        $('#filterFormOOT').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon_oot').show();
            $('#tableContainer_oot').hide();

            var tglAwal = $('#tanggal_awal_oot').val();
            var tglAkhir = $('#tanggal_akhir_oot').val();

            $.ajax({
                url: '<?= base_url("farmasi/tampildataOOT") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir
                },
                success: function(tampil) {
                    $('#loadingIcon_oot').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil) && data.tampil.length > 0) {
                            if ($.fn.DataTable.isDataTable('#datatablesOOT')) {
                                $('#datatablesOOT').DataTable().destroy();
                            }

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesOOT" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Kode Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Satuan</th>
                                            <th class="text-center">Jml Masuk</th>
                                            <th class="text-center">Jml Keluar</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                            data.tampil.forEach(item => {
                                html += `<tr>
                                    <td>${item.kd_obat}</td>
                                    
                                    <td class="text-primary font-weight-bold btn-popup-detail text-wrap" 
                                        style="cursor: pointer; text-decoration: underline; min-width:200px;" 
                                        data-jenis="Detail Obat" 
                                        data-kode="${item.kd_obat}" 
                                        data-nama="${item.nama_obat}">
                                        ${item.nama_obat}
                                    </td>
                                    
                                    <td>${item.nm_satuan}</td>
                                    
                                    <td class="text-center fw-bold text-success btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Masuk" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_masuk}</td>
                                    <td class="text-center fw-bold text-danger btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Keluar" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_keluar}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer_oot').html(html).show();
                            $('#datatablesOOT').DataTable({
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
                            });
                            $('#downloadButton_oot').show();
                        } else {
                            $('#tableContainer_oot').html('<div class="alert alert-info small m-3">Tidak ada data narkotik.</div>').show();
                            $('#downloadButton_oot').hide();
                        }
                    } catch (e) {
                        $('#tableContainer_oot').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                    }
                },
                error: function() {
                    $('#loadingIcon_oot').hide();
                    alert("Gagal koneksi server.");
                }
            });
        });

        $('#downloadButton_oot').on('click', function() {
            const ta = $('#tanggal_awal_oot').val();
            const tak = $('#tanggal_akhir_oot').val();
            window.location.href = `<?= base_url("farmasi/unduhdataOOT") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
        });

        // TAB OBAT PREKUSOR TAMPIL DATA 
        // ==========================================
        $('#filterFormprekusor').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon_prekusor').show();
            $('#tableContainer_prekusor').hide();

            var tglAwal = $('#tanggal_awal_prekusor').val();
            var tglAkhir = $('#tanggal_akhir_prekusor').val();

            $.ajax({
                url: '<?= base_url("farmasi/tampildataprekusor") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: tglAwal,
                    TANGGAL_AKHIR: tglAkhir
                },
                success: function(tampil) {
                    $('#loadingIcon_prekusor').hide();
                    try {
                        const data = JSON.parse(tampil);
                        if (data && Array.isArray(data.tampil) && data.tampil.length > 0) {
                            if ($.fn.DataTable.isDataTable('#datatablesprekusor')) {
                                $('#datatablesprekusor').DataTable().destroy();
                            }

                            let html = `
                            <div class="table-responsive w-100">
                                <table id="datatablesprekusor" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Kode Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Satuan</th>
                                            <th class="text-center">Jml Masuk</th>
                                            <th class="text-center">Jml Keluar</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                            data.tampil.forEach(item => {
                                html += `<tr>
                                    <td>${item.kd_obat}</td>
                                    
                                    <td class="text-primary font-weight-bold btn-popup-detail text-wrap" 
                                        style="cursor: pointer; text-decoration: underline; min-width:200px;" 
                                        data-jenis="Detail Obat" 
                                        data-kode="${item.kd_obat}" 
                                        data-nama="${item.nama_obat}">
                                        ${item.nama_obat}
                                    </td>
                                    
                                    <td>${item.nm_satuan}</td>
                                    
                                    <td class="text-center fw-bold text-success btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Masuk" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_masuk}</td>
                                    <td class="text-center fw-bold text-danger btn-popup-detail" style="cursor: pointer; text-decoration: underline;" data-jenis="Jumlah Keluar" data-kode="${item.kd_obat}" data-nama="${item.nama_obat}">${item.jumlah_keluar}</td>
                                </tr>`;
                            });
                            html += '</tbody></table></div>';

                            $('#tableContainer_prekusor').html(html).show();
                            $('#datatablesprekusor').DataTable({
                                responsive: false,
                                scrollX: false,
                                autoWidth: false,
                                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                    '<"row"<"col-sm-12"tr>>' +
                                    '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
                            });
                            $('#downloadButton_prekusor').show();
                        } else {
                            $('#tableContainer_prekusor').html('<div class="alert alert-info small m-3">Tidak ada data narkotik.</div>').show();
                            $('#downloadButton_prekusor').hide();
                        }
                    } catch (e) {
                        $('#tableContainer_prekusor').html('<div class="alert alert-danger m-3">Error Parsing JSON</div>').show();
                    }
                },
                error: function() {
                    $('#loadingIcon_prekusor').hide();
                    alert("Gagal koneksi server.");
                }
            });
        });

        $('#downloadButton_prekusor').on('click', function() {
            const ta = $('#tanggal_awal_prekusor').val();
            const tak = $('#tanggal_akhir_prekusor').val();
            window.location.href = `<?= base_url("farmasi/unduhdataprekusor") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
        });

        // ==========================================
            // LOGIKA KLIK UNTUK MEMUNCULKAN POP UP DETAIL
            // ==========================================
            $(document).on('click', '.btn-popup-detail', function() {
                let kodeObat = $(this).data('kode');
                let namaObat = $(this).data('nama');
                let jenisKlik = $(this).data('jenis');
                let satuanObat = $(this).data('satuan') || '';

                // Deteksi tanggal berdasarkan Tab Pane yang sedang terlihat
                let tglAwal = '';
                let tglAkhir = '';

                if ($('#pills-narkotik').is(':visible')) {
                    tglAwal = $('#tanggal_awal_narko').val();
                    tglAkhir = $('#tanggal_akhir_narko').val();
                } else if ($('#pills-psikotropik').is(':visible')) {
                    tglAwal = $('#tanggal_awal_psiko').val();
                    tglAkhir = $('#tanggal_akhir_psiko').val();
                } else if ($('#pills-prekusor').is(':visible')) {
                    tglAwal = $('#tanggal_awal_prekusor').val();
                    tglAkhir = $('#tanggal_akhir_prekusor').val();
                } else if ($('#pills-OOT').is(':visible')) {
                    tglAwal = $('#tanggal_awal_oot').val();
                    tglAkhir = $('#tanggal_akhir_oot').val();
                }

                // Set Data ke Modal
                $('#popupKodeObat').text(kodeObat);
                $('#popupNamaObat').text(namaObat);

                // Tampilkan Modal
                $('#modalDetailObat').modal('show');

                // ----------------------------------------------------
                // 1. JIKA KLIK "JUMLAH KELUAR" (PENJUALAN)
                // ----------------------------------------------------
                if (jenisKlik === 'Jumlah Keluar') {
                    $('#modalDetailLabel').html(`<i class="fas fa-shopping-cart me-2"></i> Rincian Penjualan Obat`);
                    $('#popupIsiKonten').html(`
                    <div class="text-center py-5">
                        <div class="spinner-border text-danger" role="status"></div>
                        <p class="mt-2 text-muted fw-bold">Menarik rincian data penjualan...</p>
                    </div>
                `);

                    $.ajax({
                        url: '<?= base_url("penjualanperobat/tampildataobt") ?>',
                        type: 'POST',
                        data: {
                            TANGGAL_AWAL: tglAwal,
                            TANGGAL_AKHIR: tglAkhir,
                            KD_OBAT: kodeObat
                        },
                        success: function(response) {
                            try {
                                const data = JSON.parse(response);
                                const listData = data.response || data.tampil || [];

                                if (Array.isArray(listData) && listData.length > 0) {
                                    let htmlTable = `
                                <div class="table-responsive w-100">
                                    <table id="dtPopupDetail" class="table table-striped table-hover table-bordered text-nowrap w-100" style="font-size: 0.85rem;">
                                        <thead class="table-dark text-center">
                                            <tr>
                                                <th>Tanggal</th>
                                                <th>KD Registrasi</th>
                                                <th>Kode RM</th>
                                                <th>Nama Pasien</th>
                                                <th>Jenis Pasien</th>
                                                <th>Penjamin</th>
                                                <th>Nama Obat</th>
                                                <th>Jumlah</th>
                                                <th>Total (Rp)</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;

                                    listData.forEach(item => {
                                        htmlTable += `<tr>
                                        <td>${item.tgl_jual}</td>
                                        <td>${item.kd_registrasi}</td>
                                        <td>${item.kd_rekam_medis}</td>
                                        <td class="text-wrap">${item.nama}</td>
                                        <td>${item.nm_jenis_pasien}</td>
                                        <td>${item.nm_pembayaran}</td>
                                        <td class="text-wrap">${item.nama_obat}</td>
                                        <td class="text-center fw-bold text-danger">${item.qty_jual}</td>
                                        <td class="text-end fw-bold text-success">${parseFloat(item.total||0).toLocaleString('id-ID')}</td>
                                    </tr>`;
                                    });

                                    htmlTable += `</tbody></table></div>`;
                                    $('#popupIsiKonten').html(htmlTable);
                                    $('#dtPopupDetail').DataTable({
                                        responsive: false,
                                        autoWidth: false,
                                        language: {
                                            search: "Cari:",
                                            lengthMenu: "_MENU_"
                                        }
                                    });
                                } else {
                                    $('#popupIsiKonten').html('<div class="alert alert-info text-center m-3">Data penjualan tidak ditemukan.</div>');
                                }
                            } catch (e) {
                                $('#popupIsiKonten').html('<div class="alert alert-danger text-center">Gagal memproses JSON.</div>');
                            }
                        },
                        error: function() {
                            $('#popupIsiKonten').html('<div class="alert alert-danger text-center">Koneksi gagal.</div>');
                        }
                    });
                }
                // ----------------------------------------------------
                // 2. JIKA KLIK "JUMLAH MASUK" (PEMBELIAN)
                // ----------------------------------------------------
                else if (jenisKlik === 'Jumlah Masuk') {
                    $('#modalDetailLabel').html(`<i class="fas fa-truck-loading me-2"></i> Rincian Pembelian Obat`);
                    $('#popupIsiKonten').html(`
                    <div class="text-center py-5">
                        <div class="spinner-border text-success" role="status"></div>
                        <p class="mt-2 text-muted fw-bold">Menarik rincian data pembelian...</p>
                    </div>
                `);

                    $.ajax({
                        url: '<?= base_url("farmasipemblianobt/tampildatapembelianobt") ?>',
                        type: 'POST',
                        data: {
                            TANGGAL_AWAL: tglAwal,
                            TANGGAL_AKHIR: tglAkhir,
                            KD_OBAT: kodeObat
                        },
                        success: function(response) {
                            try {
                                const data = JSON.parse(response);
                                const listData = data.response || data.tampil || [];

                                if (Array.isArray(listData) && listData.length > 0) {
                                    let htmlTable = `
                                <div class="table-responsive w-100">
                                    <table id="dtPopupDetail" class="table table-striped table-hover table-bordered text-nowrap w-100" style="font-size: 0.85rem;">
                                        <thead class="table-dark text-center align-middle">
                                            <tr>
                                                <th>Tanggal Beli</th>
                                                <th>Nama Obat</th>   
                                                <th>Qty</th>
                                                <th>Harga Satuan</th>
                                                <th>SubTotal</th>
                                                <th>Persentase Disc</th>
                                                <th>Nilai Disc</th>
                                                <th>Total(HNA)</th>
                                                <th>Pajak</th>
                                                <th>Total Pembelian</th>
                                                <th>Harga Beli Satuan Terkecil</th>
                                                <th>Supplier</th>
                                                <th>Nama Pabrik</th>
                                            </tr>
                                        </thead>
                                        <tbody>`;

                                    listData.forEach(item => {
                                        const formatUang = (val) => parseFloat(val || 0).toLocaleString('id-ID');
                                        htmlTable += `<tr>
                                            <td>${item.tgl_beli}</td>
                                            <td>${item.nama_obat}</td>
                                            <td>${item.qty}</td>
                                            <td>${parseFloat(item.harga_satuan).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.sub_total).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.prosen_disc).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.nilai_disc).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.total).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.pajak).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.hna).toLocaleString('id-ID')}</td>
                                            <td>${parseFloat(item.harga_beli_terakhir).toLocaleString('id-ID')}</td>
                                            <td>${item.nm_suplier}</td>
                                            <td>${item.nm_pabrik}</td>
                                    </tr>`;
                                    });

                                    htmlTable += `</tbody></table></div>`;
                                    $('#popupIsiKonten').html(htmlTable);
                                    $('#dtPopupDetail').DataTable({
                                        responsive: false,
                                        autoWidth: false,
                                        language: {
                                            search: "Cari:",
                                            lengthMenu: "_MENU_"
                                        }
                                    });
                                } else {
                                    $('#popupIsiKonten').html('<div class="alert alert-info text-center m-3">Data pembelian tidak ditemukan.</div>');
                                }
                            } catch (e) {
                                $('#popupIsiKonten').html('<div class="alert alert-danger text-center">Gagal memproses JSON.</div>');
                            }
                        },
                        error: function() {
                            $('#popupIsiKonten').html('<div class="alert alert-danger text-center">Koneksi gagal.</div>');
                        }
                    });
                }
                // ----------------------------------------------------
                // 3. JIKA KLIK "NAMA OBAT" (STOK PER GUDANG & TOTAL ALL)
                // ----------------------------------------------------
                else if (jenisKlik === 'Detail Obat') {
                    $('#modalDetailLabel').html(`<i class="fas fa-boxes me-2"></i> Rincian Stok Obat`);

                    $('#popupIsiKonten').html(`
                    <div class="d-flex justify-content-end align-items-center mb-3">
                        <label class="form-label text-muted small fw-bold mb-0 mr-2"><i class="fas fa-filter mr-1"></i> Pilih Gudang:</label>
                        <select id="dropdownGudangModal" class="form-control form-control-sm border-primary shadow-sm font-weight-bold text-primary" style="width: auto; cursor: pointer;">
                            <option value="0">FARMASI GUDANG</option>
                            <option value="1">RAWAT JALAN</option>
                            <option value="2">RAWAT INAP</option>
                        </select>
                    </div>

                    <div class="row mb-4">
                        <div class="col-12 col-md-6 mb-3 mb-md-0">
                            <div class="p-3 rounded shadow-sm h-100 d-flex flex-column justify-content-center align-items-center text-center" style="background-color: #fff3cd; border: 1px solid #ffe69c;">
                                <h6 class="font-weight-bold text-dark mb-2 text-uppercase">TOTAL QTY ALL</h6>
                                <h4 class="font-weight-bold text-danger mb-0">
                                    <span id="totalQtyAllLabel"><i class="fas fa-spinner fa-spin"></i></span> 
                                    <span class="text-dark" style="font-size: 1.1rem;">${satuanObat.toUpperCase()}</span>
                                </h4>
                            </div>
                        </div>
                        
                        <div class="col-12 col-md-6">
                            <div class="p-3 rounded shadow-sm h-100 d-flex flex-column justify-content-center align-items-center text-center" style="background-color: #e0f7fa; border: 1px solid #b2ebf2;">
                                <h6 class="font-weight-bold text-dark mb-2 text-uppercase">TOTAL QTY DI <span id="namaGudangLabel" class="text-primary">FARMASI GUDANG</span></h6>
                                <h4 class="font-weight-bold text-danger mb-0">
                                    <span id="totalQtyGudangLabel"><i class="fas fa-spinner fa-spin"></i></span> 
                                    <span class="text-dark" style="font-size: 1.1rem;">${satuanObat.toUpperCase()}</span>
                                </h4>
                            </div>
                        </div>
                    </div>
                    
                    <div id="wadahTabelStokModal"></div>
                `);

                    // AJAX 1: Mengambil Total Qty All dari route baru
                    $.ajax({
                        url: '<?= base_url("stokrekapperobat/tampildata") ?>',
                        type: 'POST',
                        data: {
                            KD_OBAT: kodeObat
                        },
                        success: function(res) {
                            try {
                                const dataTotal = JSON.parse(res);
                                let totalAll = 0;
                                // Menyesuaikan dengan standar array response API Anda
                                if (dataTotal.response && dataTotal.response.length > 0) {
                                    totalAll = dataTotal.response[0].total_sisa || 0;
                                } else if (dataTotal.tampil && dataTotal.tampil.length > 0) {
                                    totalAll = dataTotal.tampil[0].total_sisa || 0;
                                } else if (dataTotal.total_sisa !== undefined) {
                                    totalAll = dataTotal.total_sisa;
                                }
                                $('#totalQtyAllLabel').text(totalAll);
                            } catch (e) {
                                $('#totalQtyAllLabel').text('-');
                            }
                        },
                        error: function() {
                            $('#totalQtyAllLabel').text('-');
                        }
                    });

                    // AJAX 2: Fungsi untuk merender tabel stok berdasarkan Gudang terpilih & Hitung Total QTY Gudang
                    const loadStokModal = (gudangVal, gudangText) => {
                        $('#wadahTabelStokModal').html(`
                        <div class="text-center py-4">
                            <div class="spinner-border text-info" role="status"></div>
                            <p class="mt-2 text-muted fw-bold">Memuat stok...</p>
                        </div>
                    `);

                        // Update label nama gudang di kotak biru muda dan kembalikan spinner
                        $('#namaGudangLabel').text(gudangText);
                        $('#totalQtyGudangLabel').html('<i class="fas fa-spinner fa-spin"></i>');

                        $.ajax({
                            url: '<?= base_url("farmasidatastok/tampildatastokperobat") ?>',
                            type: 'POST',
                            data: {
                                KD_GUDANG: gudangVal,
                                KD_OBAT: kodeObat
                            },
                            success: function(res) {
                                try {
                                    const data = JSON.parse(res);
                                    let sumSisaGudang = 0; // Penampung hitung manual Qty Sisa

                                    if (data.response && data.response.length > 0) {
                                        let htmlStok = `
                                    <div class="table-responsive w-100">
                                        <table id="dtPopupStok" class="table table-striped table-hover table-bordered text-nowrap w-100" style="font-size: 0.85rem;">
                                            <thead class="table-dark text-center">
                                                <tr>
                                                    <th>KD Stok</th>
                                                    <th>Tgl Masuk</th>
                                                    <th>Expired</th>
                                                    <th>Kode Produksi</th>
                                                    <th>Pabrik</th>
                                                    <th>Obat</th>
                                                    <th>Awal</th>
                                                    <th>Terpakai</th>
                                                    <th>Sisa</th>
                                                </tr>
                                            </thead>
                                        <tbody>`;

                                        data.response.forEach(i => {
                                            // Menghitung total sisa secara realtime
                                            sumSisaGudang += parseInt(i.qty_sisa) || 0;

                                            htmlStok += `<tr>
                                            <td class="fw-bold">${i.kd_stock}</td>
                                            <td>${i.tgl_masuk}</td>
                                            <td>${i.expired_date}</td>
                                            <td>${i.kode_produksi}</td>
                                            <td>${i.nama_pabrik}</td>
                                            <td class="text-wrap" style="min-width:200px;">${i.nama_obat}</td>
                                            <td class="text-center">${i.qty_hitung}</td>
                                            <td class="text-center text-danger">${i.qty_terpakai}</td>
                                            <td class="text-center fw-bold text-success">${i.qty_sisa}</td>
                                        </tr>`;
                                        });

                                        htmlStok += `</tbody></table></div>`;
                                        $('#wadahTabelStokModal').html(htmlStok);

                                        $('#dtPopupStok').DataTable({
                                            responsive: false,
                                            autoWidth: false,
                                            language: {
                                                search: "Cari Data:",
                                                lengthMenu: "_MENU_"
                                            }
                                        });
                                    } else {
                                        $('#wadahTabelStokModal').html('<div class="alert alert-warning text-center m-3">Stok kosong di gudang ini.</div>');
                                    }

                                    // Tampilkan hasil hitungan ke label
                                    $('#totalQtyGudangLabel').text(sumSisaGudang);

                                } catch (e) {
                                    $('#wadahTabelStokModal').html('<div class="alert alert-danger text-center m-3">Gagal membaca data stok.</div>');
                                    $('#totalQtyGudangLabel').text('-');
                                }
                            },
                            error: function() {
                                $('#wadahTabelStokModal').html('<div class="alert alert-danger text-center m-3">Koneksi server gagal.</div>');
                                $('#totalQtyGudangLabel').text('-');
                            }
                        });
                    };

                    // Panggil pertama kali dengan default Gudang 0
                    loadStokModal('0', 'FARMASI GUDANG');

                    // Listener untuk mendeteksi perubahan Dropdown Gudang
                    $('#dropdownGudangModal').on('change', function() {
                        let selectedText = $(this).find("option:selected").text(); // Ambil nama teks dropdown
                        loadStokModal($(this).val(), selectedText);
                    });
                }
            });

            // ==========================================
            // SCRIPT PEMBERSIH KETIKA POP UP DITUTUP
            // ==========================================
            $('#modalDetailObat').on('hidden.bs.modal', function() {
                // Hancurkan DataTables agar tidak error saat pop-up dibuka kembali
                if ($.fn.DataTable.isDataTable('#dtPopupDetail')) {
                    $('#dtPopupDetail').DataTable().destroy();
                }
                $('#popupIsiKonten').empty();
            });
       
    });
</script>