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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Farmasi Stok</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <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;
        }

        /* Memaksa Tabel agar menyesuaikan layar */
        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;
        }

        /* Scroll Horizontal Halus untuk Tabel di HP */
        .table-responsive {
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: auto !important;
            -webkit-overflow-scrolling: touch;
            border: none;
        }

        /* ========================================================
           2. STYLING TAB / PILLS (Dapat di-scroll di HP)
           ======================================================== */
        .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: #0d6efd;
            color: #fff;
            border-color: #0d6efd;
        }

        .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
           ======================================================== */
        .filter-wrapper {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        /* Modifikasi Select2 agar tinggi sejajar dan tombol X rapi */
        .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);
        }

        /* Responsif Form */
        @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%;
                margin-left: 0 !important;
            }

            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>
</head>

<body>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-3 px-md-4 overflow-hidden">
                <h1 class="mt-4 fs-3">Data Farmasi Stok</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 Stok</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-stok-tab" data-bs-toggle="pill" href="#pills-stok" role="tab">
                            <i class="fas fa-boxes me-2"></i>Farmasi Data Stok
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link shadow-sm" id="pills-stokperobt-tab" data-bs-toggle="pill" href="#pills-stokperobt" role="tab">
                            <i class="fas fa-capsules me-2"></i>Data Stok Per-Obat
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link shadow-sm" id="pills-rekapstok-tab" data-bs-toggle="pill" href="#pills-rekapstok" role="tab">
                            <i class="fas fa-file-invoice me-2"></i>Rekap Data Stok
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link shadow-sm" id="pills-stokall-tab" data-bs-toggle="pill" href="#pills-stokall" role="tab">
                            <i class="fas fa-layer-group me-2"></i>Farmasi Stok All
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link shadow-sm" id="pills-stokallsum-tab" data-bs-toggle="pill" href="#pills-stokallsum" role="tab">
                            <i class="fas fa-box-archive me-2"></i>Farmasi Stok All SUM Perpabrik
                        </a>
                    </li>
                </ul>

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

                    <div class="tab-pane fade show active" id="pills-stok" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Stok</h5>
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-body filter-wrapper">
                                <form id="filterFormStok">
                                    <div class="row g-2 align-items-end">
                                        <div class="col-12 col-md-4">
                                            <label class="form-label text-muted small fw-bold mb-1">Pilih Gudang</label>
                                            <select id="kd_gudang_stok" class="form-select" required>
                                                <option value="0">FARMASI GUDANG</option>
                                                <option value="1">RAWAT JALAN</option>
                                                <option value="2">RAWAT INAP</option>
                                            </select>
                                        </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-4 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                                <button type="button" id="downloadStok" class="btn btn-success px-4 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download 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_stok" 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_stok" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-stokperobt" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Stok Per-Obat</h5>
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-body filter-wrapper">
                                <form id="filterFormStokPerObat">
                                    <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">Pilih Gudang</label>
                                            <select id="kd_gudang_perobat" class="form-select" required>
                                                <option value="0">FARMASI GUDANG</option>
                                                <option value="1">RAWAT JALAN</option>
                                                <option value="2">RAWAT INAP</option>
                                            </select>
                                        </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" class="form-control" required style="width: 100%;"></select>
                                            </div>
                                        </div>
                                        <div class="col-12 col-md-5">
                                            <div class="btn-group-custom mt-3 mt-md-0">
                                                <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                                <button type="button" id="downloadStokPerObat" class="btn btn-success px-4 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download 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_stokperobat" 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_stokperobat" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-rekapstok" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Rekap Data Farmasi Stok</h5>
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-body filter-wrapper">
                                <form id="filterFormRekapStok">
                                    <div class="row g-2 align-items-end">
                                        <div class="col-12 col-md-4">
                                            <label class="form-label text-muted small fw-bold mb-1">Pilih Gudang</label>
                                            <select id="kd_gudang_rekap" class="form-select" required>
                                                <option value="0">FARMASI GUDANG</option>
                                                <option value="1">RAWAT JALAN</option>
                                                <option value="2">RAWAT INAP</option>
                                            </select>
                                        </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-4 shadow-sm"><i class="fas fa-search me-1"></i> Submit</button>
                                                <button type="button" id="downloadRekapStok" class="btn btn-success px-4 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download 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_rekapstok" 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_rekapstok" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-stokall" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Stok ALL (Keseluruhan)</h5>
                        <div class="card mb-4 border-0 shadow-sm border-left-success">
                            <div class="card-body filter-wrapper d-flex flex-column flex-md-row justify-content-between align-items-md-center">
                                <div class="mb-3 mb-md-0">
                                    <p class="mb-0 text-muted small">Menampilkan rekapitulasi data persediaan obat dari semua gudang.</p>
                                </div>
                                <div class="btn-group-custom">
                                    <button type="button" id="btnLoadStokAll" class="btn btn-primary px-4 shadow-sm">
                                        <i class="fas fa-sync-alt me-1"></i> Tampilkan Data
                                    </button>
                                    <button type="button" id="btnDownloadStokAll" class="btn btn-success px-4 shadow-sm" style="display: none;">
                                        <i class="fas fa-file-excel me-1"></i> Download Excel
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="card border-0 shadow-sm mb-5">
                            <div class="card-body p-2 p-md-3">
                                <div id="loadingIcon_stokall" 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 small fw-bold">Menarik Data Keseluruhan...</p>
                                </div>
                                <div id="tableContainer_stokall" style="display: none;"></div>
                            </div>
                        </div>
                    </div>


                    <div class="tab-pane fade" id="pills-stokallsum" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2 text-muted fw-bold">Data Farmasi Stok ALL SUM-PERPABRIK</h5>
                        <div class="card mb-4 border-0 shadow-sm border-left-success">
                            <div class="card-body filter-wrapper d-flex flex-column flex-md-row justify-content-between align-items-md-center">
                                <div class="mb-3 mb-md-0">
                                    <p class="mb-0 text-muted small">Menampilkan rekapitulasi data persediaan obat dari semua gudang.</p>
                                </div>
                                <div class="btn-group-custom">
                                    <button type="button" id="btnLoadStokAllSum" class="btn btn-primary px-4 shadow-sm">
                                        <i class="fas fa-sync-alt me-1"></i> Tampilkan Data
                                    </button>
                                    <button type="button" id="btnDownloadStokAllSum" class="btn btn-success px-4 shadow-sm" style="display: none;">
                                        <i class="fas fa-file-excel me-1"></i> Download Excel
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="card border-0 shadow-sm mb-5">
                            <div class="card-body p-2 p-md-3">
                                <div id="loadingIcon_stokallsum" 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 small fw-bold">Menarik Data Keseluruhan...</p>
                                </div>
                                <div id="tableContainer_stokallsum" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

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

        <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://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

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

            // ==========================================
            // INISIALISASI AWAL (SELECT 2 & MASTER OBAT)
            // ==========================================
            $('#kd_refobat').select2({
                width: '100%',
                placeholder: "Cari Nama Obat",
                allowClear: true
            });

            function loadMasterObat() {
                $.ajax({
                    url: '<?= base_url("penjualanperobat/refrensiobat") ?>',
                    type: 'POST',
                    dataType: 'json',
                    success: function(data) {
                        $('#kd_refobat').empty().append('<option value="" disabled selected>Pilih Nama Obat</option>');
                        if (data && Array.isArray(data.response)) {
                            $.each(data.response, function(i, item) {
                                $('#kd_refobat').append(new Option(item.nama_obat, item.kd_obat));
                            });
                            $('#kd_refobat').trigger('change');
                        }
                    }
                });
            }
            loadMasterObat();

            // ==========================================
            // TAB 1: DATA STOK
            // ==========================================
            $('#filterFormStok').on('submit', function(e) {
                e.preventDefault();
                $('#loadingIcon_stok').show();
                $('#tableContainer_stok').hide();

                $.ajax({
                    url: '<?= base_url("farmasidatastok/tampildatastok") ?>',
                    type: 'POST',
                    data: {
                        KD_GUDANG: $('#kd_gudang_stok').val()
                    },
                    success: function(res) {
                        $('#loadingIcon_stok').hide();
                        const data = JSON.parse(res);
                        if (data.response && data.response.length > 0) {
                            if ($.fn.DataTable.isDataTable('#dtStok')) {
                                $('#dtStok').DataTable().destroy();
                            }

                            let html = `
                        <div class="table-responsive w-100">
                            <table id="dtStok" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                <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 => {
                                html += `<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>`;
                            });

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

                            $('#dtStok').DataTable({
                                "order": [
                                    [1, "desc"]
                                ],
                                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>>'
                            });
                            $('#downloadStok').fadeIn();
                        } else {
                            $('#tableContainer_stok').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Data Kosong</div>').show();
                            $('#downloadStok').hide();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_stok').hide();
                        $('#tableContainer_stok').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal koneksi server.</div>').show();
                    }
                });
            });

            // ==========================================
            // TAB 2: STOK PER OBAT
            // ==========================================
            $('#filterFormStokPerObat').on('submit', function(e) {
                e.preventDefault();
                $('#loadingIcon_stokperobat').show();
                $('#tableContainer_stokperobat').hide();

                $.ajax({
                    url: '<?= base_url("farmasidatastok/tampildatastokperobat") ?>',
                    type: 'POST',
                    data: {
                        KD_GUDANG: $('#kd_gudang_perobat').val(),
                        KD_OBAT: $('#kd_refobat').val()
                    },
                    success: function(res) {
                        $('#loadingIcon_stokperobat').hide();
                        const data = JSON.parse(res);
                        if (data.response && data.response.length > 0) {
                            if ($.fn.DataTable.isDataTable('#dtStokPerObat')) {
                                $('#dtStokPerObat').DataTable().destroy();
                            }

                            let html = `
                        <div class="table-responsive w-100">
                            <table id="dtStokPerObat" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                <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 => {
                                html += `<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>`;
                            });

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

                            $('#dtStokPerObat').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>>'
                            });
                            $('#downloadStokPerObat').fadeIn();
                        } else {
                            $('#tableContainer_stokperobat').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Data Kosong</div>').show();
                            $('#downloadStokPerObat').hide();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_stokperobat').hide();
                        $('#tableContainer_stokperobat').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal koneksi server.</div>').show();
                    }
                });
            });

            // ==========================================
            // TAB 3: REKAP STOK (TIDAK DIUBAH)
            // ==========================================
            $('#filterFormRekapStok').on('submit', function(e) {
                e.preventDefault();
                $('#loadingIcon_rekapstok').show();
                $('#tableContainer_rekapstok').hide();

                $.ajax({
                    url: '<?= base_url("farmasidatastok/tampildatastokrekap") ?>',
                    type: 'POST',
                    data: {
                        KD_GUDANG: $('#kd_gudang_rekap').val()
                    },
                    success: function(res) {
                        $('#loadingIcon_rekapstok').hide();
                        const data = JSON.parse(res);
                        if (data.response && data.response.length > 0) {
                            if ($.fn.DataTable.isDataTable('#dtRekapStok')) {
                                $('#dtRekapStok').DataTable().destroy();
                            }

                            let html = `
                        <div class="table-responsive w-100">
                            <table id="dtRekapStok" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                <thead class="table-dark text-center">
                                    <tr>
                                        <th>Kode Obat</th>
                                        <th class="text-start">Nama Obat</th>
                                        <th>Total Sisa</th>
                                    </tr>
                                </thead>
                            <tbody>`;

                            data.response.forEach(i => {
                                html += `<tr>
                                <td class="text-center">${i.kd_obat}</td>
                                <td class="text-wrap" style="min-width:200px;">${i.nama_obat}</td>
                                <td class="text-center fw-bold text-success">${i.total_sisa}</td>
                            </tr>`;
                            });

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

                            $('#dtRekapStok').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>>'
                            });
                            $('#downloadRekapStok').fadeIn();
                        } else {
                            $('#tableContainer_rekapstok').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Data Kosong</div>').show();
                            $('#downloadRekapStok').hide();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_rekapstok').hide();
                        $('#tableContainer_rekapstok').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal koneksi server.</div>').show();
                    }
                });
            });


            // ==========================================
            // TAB 4 (BARU): STOK ALL
            // ==========================================
            $('#btnLoadStokAll').on('click', function(e) {
                e.preventDefault();
                $('#loadingIcon_stokall').show();
                $('#tableContainer_stokall').hide();
                $('#btnDownloadStokAll').hide();

                // Karena tidak ada input, body POST kosong
                $.ajax({
                    url: '<?= base_url("farmasistokall/tampildataall") ?>',
                    type: 'POST',
                    success: function(res) {
                        $('#loadingIcon_stokall').hide();
                        try {
                            const data = JSON.parse(res);

                            if (data && Array.isArray(data.response) && data.response.length > 0) {
                                if ($.fn.DataTable.isDataTable('#dtStokAll')) {
                                    $('#dtStokAll').DataTable().destroy();
                                }

                                let html = `
                            <div class="table-responsive w-100">
                                <table id="dtStokAll" class="table table-striped table-hover table-bordered text-nowrap w-100" style="font-size: 0.85rem;">
                                    <thead class="table-success text-center align-middle">
                                        <tr>
                                            <th>KD Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Pabrik</th>
                                            <th>Stok Gudang</th>
                                            <th>Stok Rajal</th>
                                            <th>Stok Ranap</th>
                                            <th class="bg-warning">Total Stok</th>
                                            <th>Qty Ideal</th>
                                            <th>Qty Vol.</th>
                                            <th>Standar Ideal</th>
                                            <th>Qty Min</th>
                                            <th>Standar Min</th>
                                            <th>Selisih</th>
                                            <th>% Pemenuhan</th>
                                            <th>Stat Gudang</th>
                                            <th>Stat Rajal</th>
                                            <th>Stat Ranap</th>
                                            <th>Stat Total</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                                // Fungsi Bantuan Pembuat Badge Status
                                const getStatusBadge = (status) => {
                                    if (status === 'KOSONG') return `<span class="badge badge-danger">KOSONG</span>`;
                                    if (status === 'IDEAL') return `<span class="badge badge-success">IDEAL</span>`;
                                    if (status === 'KURANG') return `<span class="badge badge-warning text-dark">KURANG</span>`;
                                    if (status === 'OVERSTOCK') return `<span class="badge badge-primary">OVERSTOCK</span>`; // Biru
                                    if (status === 'KRITIS') return `<span class="badge badge-dark">KRITIS</span>`; // Hitam
                                    return `<span class="badge badge-secondary">${status}</span>`;
                                };

                                data.response.forEach(i => {
                                    html += `<tr>
                                    <td class="text-center font-weight-bold">${i.kd_obat}</td>
                                    <td class="text-wrap" style="min-width: 250px; font-weight: 500;">${i.nama_obat}</td>
                                    <td class="text-wrap" style="min-width: 150px;">${i.nama_pabrik}</td>
                                    <td class="text-center">${i.stock_gudang_utama}</td>
                                    <td class="text-center">${i.stock_rawat_jalan}</td>
                                    <td class="text-center">${i.stock_rawat_inap}</td>
                                    <td class="text-center font-weight-bold text-primary" style="background-color: #fff3cd;">${i.total_stock}</td>
                                    <td class="text-center">${i.qty_ideal}</td>
                                    <td class="text-center">${i.qty_vol_satuan}</td>
                                    <td class="text-center text-success">${i.standar_ideal_total}</td>
                                    <td class="text-center">${i.qty_minimal}</td>
                                    <td class="text-center text-danger">${i.standar_minimal_total}</td>
                                    <td class="text-center">${i.selisih_dari_ideal}</td>
                                    <td class="text-center fw-bold">${i.persen_pemenuhan_ideal}%</td>
                                    <td class="text-center">${getStatusBadge(i.status_gudang_utama)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_rawat_jalan)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_rawat_inap)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_total)}</td>
                                </tr>`;
                                });

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

                                $('#tableContainer_stokall').html(html).show();

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

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

                            } else {
                                $('#tableContainer_stokall').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Data Stok All Kosong</div>').show();
                            }
                        } catch (e) {
                            $('#tableContainer_stokall').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Terjadi kesalahan memproses data (Bukan JSON Valid).</div>').show();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_stokall').hide();
                        $('#tableContainer_stokall').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal koneksi ke server.</div>').show();
                    }
                });
            });


            // ==========================================
            // TAB 5 : STOK ALL SUM PERAPBRIK
            // ==========================================
            $('#btnLoadStokAllSum').on('click', function(e) {
                e.preventDefault();
                $('#loadingIcon_stokallsum').show();
                $('#tableContainer_stokallsum').hide();
                $('#btnDownloadStokAllSum').hide();

                // Karena tidak ada input, body POST kosong
                $.ajax({
                    url: '<?= base_url("farmasistokallsum/tampildataall") ?>',
                    type: 'POST',
                    success: function(res) {
                        $('#loadingIcon_stokallsum').hide();
                        try {
                            const data = JSON.parse(res);

                            if (data && Array.isArray(data.response) && data.response.length > 0) {
                                if ($.fn.DataTable.isDataTable('#dtStokAllSum')) {
                                    $('#dtStokAllSum').DataTable().destroy();
                                }

                                let html = `
                            <div class="table-responsive w-100">
                                <table id="dtStokAllSum" class="table table-striped table-hover table-bordered text-nowrap w-100" style="font-size: 0.85rem;">
                                    <thead class="table-success text-center align-middle">
                                        <tr>
                                            <th>KD Obat</th>
                                            <th>Nama Obat</th>
                                            <th>Stok Gudang</th>
                                            <th>Stok Rajal</th>
                                            <th>Stok Ranap</th>
                                            <th class="bg-warning">Total Stok</th>
                                            <th>Qty Ideal</th>
                                            <th>Qty Vol.</th>
                                            <th>Standar Ideal</th>
                                            <th>Qty Min</th>
                                            <th>Standar Min</th>
                                            <th>Selisih</th>
                                            <th>% Pemenuhan</th>
                                            <th>Stat Gudang</th>
                                            <th>Stat Rajal</th>
                                            <th>Stat Ranap</th>
                                            <th>Stat Total</th>
                                        </tr>
                                    </thead>
                                <tbody>`;

                                // Fungsi Bantuan Pembuat Badge Status
                                const getStatusBadge = (status) => {
                                    if (status === 'KOSONG') return `<span class="badge badge-danger">KOSONG</span>`;
                                    if (status === 'IDEAL') return `<span class="badge badge-success">IDEAL</span>`;
                                    if (status === 'KURANG') return `<span class="badge badge-warning text-dark">KURANG</span>`;
                                    if (status === 'OVERSTOCK') return `<span class="badge badge-primary">OVERSTOCK</span>`; // Biru
                                    if (status === 'KRITIS') return `<span class="badge badge-dark">KRITIS</span>`; // Hitam
                                    return `<span class="badge badge-secondary">${status}</span>`;
                                };

                                data.response.forEach(i => {
                                    html += `<tr>
                                    <td class="text-center font-weight-bold">${i.kd_obat}</td>
                                    <td class="text-wrap" style="min-width: 250px; font-weight: 500;">${i.nama_obat}</td>
                                    <td class="text-center">${i.stock_gudang_utama}</td>
                                    <td class="text-center">${i.stock_rawat_jalan}</td>
                                    <td class="text-center">${i.stock_rawat_inap}</td>
                                    <td class="text-center font-weight-bold text-primary" style="background-color: #fff3cd;">${i.total_stock}</td>
                                    <td class="text-center">${i.qty_ideal}</td>
                                    <td class="text-center">${i.qty_vol_satuan}</td>
                                    <td class="text-center text-success">${i.standar_ideal_total}</td>
                                    <td class="text-center">${i.qty_minimal}</td>
                                    <td class="text-center text-danger">${i.standar_minimal_total}</td>
                                    <td class="text-center">${i.selisih_dari_ideal}</td>
                                    <td class="text-center fw-bold">${i.persen_pemenuhan_ideal}%</td>
                                    <td class="text-center">${getStatusBadge(i.status_gudang_utama)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_rawat_jalan)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_rawat_inap)}</td>
                                    <td class="text-center">${getStatusBadge(i.status_total)}</td>
                                </tr>`;
                                });

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

                                $('#tableContainer_stokallsum').html(html).show();

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

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

                            } else {
                                $('#tableContainer_stokallsum').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Data Stok All Kosong</div>').show();
                            }
                        } catch (e) {
                            $('#tableContainer_stokallsum').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Terjadi kesalahan memproses data (Bukan JSON Valid).</div>').show();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_stokallsum').hide();
                        $('#tableContainer_stokallsum').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal koneksi ke server.</div>').show();
                    }
                });
            });


            // ==========================================
            // DOWNLOAD EXCEL EVENT HANDLERS
            // ==========================================
            $('#downloadStok').click(function() {
                window.location.href = `<?= base_url("farmasidatastok/unduhdatastok") ?>?KD_GUDANG=${$('#kd_gudang_stok').val()}`;
            });
            $('#downloadStokPerObat').click(function() {
                window.location.href = `<?= base_url("farmasidatastok/unduhdatastokperobat") ?>?KD_GUDANG=${$('#kd_gudang_perobat').val()}&KD_OBAT=${$('#kd_refobat').val()}`;
            });
            $('#downloadRekapStok').click(function() {
                window.location.href = `<?= base_url("farmasidatastok/unduhdatastokrekap") ?>?KD_GUDANG=${$('#kd_gudang_rekap').val()}`;
            });

            // Download Tab Baru (Stok All)
            $('#btnDownloadStokAll').click(function() {
                window.location.href = `<?= base_url("farmasistokall/unduhdataall") ?>`;
            });
            // Download Tab Baru (Stok All SUM PERPABRIK)
            $('#btnDownloadStokAllSum').click(function() {
                window.location.href = `<?= base_url("farmasistokallsum/unduhdataall") ?>`;
            });
        });
    </script>
</body>

</html>