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

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


    @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 KOTAK FILTER & SELECT2
       ======================================================== */
    /* Modifikasi Select2 Default agar rapi dan tombol 'x' di kanan */
    .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;
    }

    /* Responsive untuk tombol filter */
    @media (max-width: 768px) {
        .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">Data Farmasi Stok Opname</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 Opname</li>
            </ol>

            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-header bg-white font-weight-bold border-bottom-0 pb-0 pt-3">
                    <i class="fas fa-boxes me-1 text-primary"></i> Filter Data Stok Opname
                </div>
                <div class="card-body mt-2 bg-light rounded-bottom">
                    <form id="filterFormStokSO">
                        <div class="row g-2 align-items-end">
                            <div class="col-12 col-md-6 col-lg-5">
                                <label class="form-label text-muted small fw-bold mb-1">Pilih Data Opname (Ketik untuk mencari)</label>
                                <div style="width: 100%;">
                                    <select id="kd_opname" class="form-control" required style="width: 100%;">
                                        </select>
                                </div>
                            </div>
                            
                            <div class="col-12 col-md-6 col-lg-7">
                                <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> Tampilkan Data
                                    </button>
                                    <button type="button" id="downloadSO" class="btn btn-success px-3 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 mb-5 border-0 shadow-sm border-top border-primary border-4">
                <div class="card-body p-2 p-md-3">
                    <div id="result_so">
                        <div id="loadingIcon_so" style="display: none; text-align:center; padding: 20px;">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" width="50" alt="Loading..."/>
                            <p class="mt-2 text-muted small fw-bold">Mengambil Data...</p>
                        </div>
                        <div id="tableContainer_so" style="display: none;"></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://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() {
        
        // 1. Inisialisasi Select2
        $('#kd_opname').select2({
            width: '100%',
            placeholder: "Cari Nama Opname...",
            allowClear: true
        });

        // 2. Load Master Opname ke Dropdown
        function loadMasterSO() {
            $.ajax({
                url: '<?= base_url("farmasidataSO/refmasterSO") ?>',
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    $('#kd_opname').empty().append('<option value="" disabled selected>Pilih Data Opname</option>');
                    
                    let dataArray = data.response ? data.response : data;
                    
                    if(dataArray && Array.isArray(dataArray)){
                        $.each(dataArray, function(i, item) {
                            $('#kd_opname').append(new Option(item.nm_opname, item.kd_opname));
                        });
                        $('#kd_opname').trigger('change');
                    }
                },
                error: function() {
                    $('#kd_opname').empty().append('<option value="" disabled selected>Gagal memuat data master</option>');
                }
            });
        }
        loadMasterSO();

        // 3. Tampilkan Data SO berdasarkan KD_OPNAME
        $('#filterFormStokSO').on('submit', function(e) {
            e.preventDefault();
            
            let kdOpnameVal = $('#kd_opname').val();
            if(!kdOpnameVal) {
                alert('Silakan pilih data Opname terlebih dahulu!');
                return;
            }

            $('#loadingIcon_so').show();
            $('#tableContainer_so').hide();
            $('#downloadSO').hide();
            
            $.ajax({
                url: '<?= base_url("farmasidataSO/tampildataSO") ?>',
                type: 'POST',
                data: { KD_OPNAME: kdOpnameVal },
                success: function(res) {
                    $('#loadingIcon_so').hide();
                    
                    let data;
                    try {
                        data = (typeof res === 'string') ? JSON.parse(res) : res;
                    } catch(e) {
                        alert("Format data balasan tidak valid.");
                        return;
                    }
                    
                    let dataArray = data.response ? data.response : data;

                    if(dataArray && dataArray.length > 0) {
                        if ($.fn.DataTable.isDataTable('#dtSO')) { 
                            $('#dtSO').DataTable().destroy(); 
                        }
                        
                        // KUNCI: Bungkus tabel dengan div responsive dan gunakan text-nowrap
                        let html = `
                        <div class="table-responsive w-100">
                            <table id="dtSO" class="table table-striped table-hover table-bordered table-sm w-100 text-nowrap">
                                <thead class="table-dark text-center">
                                    <tr>
                                        <th>KD Opname</th>
                                        <th>Gudang</th>
                                        <th>KD Obat</th>
                                        <th>Nama Obat</th>
                                        <th>Satuan</th>
                                        <th>Qty Asal</th>
                                        <th>Qty Opname</th>
                                        <th>Qty Koreksi</th>
                                        <th class="text-end">Harga Beli Terakhir</th>
                                        <th class="text-end">Total HPP Koreksi</th>
                                        <th class="text-end">Harga Satuan Terakhir</th>
                                    </tr>
                                </thead>
                            <tbody>`;
                        
                        dataArray.forEach(i => {
                            html += `<tr>
                                <td>${i.kd_opname || '-'}</td>
                                <td>${i.nm_gudang || '-'}</td>
                                <td>${i.kd_obat || '-'}</td>
                                <td class="text-wrap" style="min-width: 250px;">${i.nama_obat || '-'}</td>
                                <td class="text-center">${i.nm_satuan_volume || '-'}</td>
                                <td class="text-center">${i.qty_asal || '0'}</td>
                                <td class="text-center fw-bold text-primary">${i.qty_opname || '0'}</td>
                                <td class="text-center fw-bold text-danger">${i.qty_koreksi || '0'}</td>
                                <td class="text-end">${parseFloat(i.harga_beli_terakhir || 0).toLocaleString('id-ID')}</td>
                                <td class="text-end fw-bold text-success">${parseFloat(i.tot_hpp_koreksi || 0).toLocaleString('id-ID')}</td>
                                <td class="text-end">${parseFloat(i.harga_satuan_terakhir || 0).toLocaleString('id-ID')}</td>
                            </tr>`;
                        });
                        
                        html += '</tbody></table></div>';

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

                        // KUNCI PERBAIKAN: Matikan scrollX, gunakan DOM layout mobile friendly
                        $('#dtSO').DataTable({ 
                            pageLength: 10,
                            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:",
                                lengthMenu: "Tampil _MENU_",
                                info: "_START_-_END_ dari _TOTAL_"
                            }
                        });
                        
                        $('#downloadSO').fadeIn();
                    } else {
                        $('#tableContainer_so').html('<div class="alert alert-info text-center small m-3"><i class="fas fa-info-circle me-1"></i>Data tidak ditemukan untuk Opname yang dipilih.</div>').show();
                    }
                },
                error: function() {
                    $('#loadingIcon_so').hide();
                    $('#tableContainer_so').html('<div class="alert alert-danger text-center small m-3"><i class="fas fa-exclamation-triangle me-1"></i>Gagal terhubung ke server. Silakan coba lagi.</div>').show();
                }
            });
        });

        // 4. Event Download Excel
        $('#downloadSO').click(function() {
            let kdOpnameVal = $('#kd_opname').val();
            if(kdOpnameVal) {
                window.location.href = `<?= base_url("farmasidataSO/unduhdataSO") ?>?KD_OPNAME=${kdOpnameVal}`;
            }
        });

    });
</script>