<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Farmasi Pembelian Per-obat</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@1.5.2/dist/select2-bootstrap4.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    
    <style>
        /* Perbaikan agar dropdown tidak terlalu panjang ke bawah */
        .select2-results__options {
            max-height: 250px !important; 
            overflow-y: auto;
        }

        /* Memberikan border kotak yang jelas pada filter */
        .filter-container {
            background: #f8f9fc;
            border: 1px solid #e3e6f0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .select2-container--bootstrap4 .select2-selection--single {
            height: calc(1.5em + 0.75rem + 2px) !important;
        }
    </style>
</head>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-4">
            <h1 class="mt-4">Data Farmasi Pembelian Per-obat</h1>
            <ol class="breadcrumb mb-4">
                <li class="breadcrumb-item"><a href="#">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Data</li>
            </ol>

            <div class="filter-container shadow-sm">
                <form id="filterFormPembelianperobat">
                    <div class="form-row align-items-end">
                        <div class="col-md-2 form-group">
                            <label class="small font-weight-bold">Tanggal Awal</label>
                            <input type="date" id="tanggal_awal_perobat" class="form-control" value="<?= $tgl_awal ?>" required />
                        </div>
                        <div class="col-md-2 form-group">
                            <label class="small font-weight-bold">Tanggal Akhir</label>
                            <input type="date" id="tanggal_akhir_perobat" class="form-control" value="<?= $tgl_akhir ?>" required />
                        </div>
                        <div class="col-md-5 form-group">
                            <label class="small font-weight-bold">Pilih Obat</label>
                            <select id="kd_refobat" name="KD_OBAT" class="form-control select2" required>
                                <option value="" disabled selected>Memuat Nama Obat...</option>
                            </select>
                        </div>
                        <div class="col-md-3 form-group">
                            <button type="submit" class="btn btn-primary px-4">
                                <i class="fas fa-search"></i> Submit
                            </button>
                            <button type="button" id="downloadButton_pembalianperobat" class="btn btn-success ml-2" style="display: none;">
                                <i class="fas fa-file-excel"></i> Excel
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <div id="result">
                <div id="loadingIcon" style="display: none;" class="text-center my-4">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p>Mohon tunggu...</p>
                </div>
                <div class="table-responsive" id="tableContainer" style="display: none;">
                    </div>
            </div>
        </div>
    </main>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

<script>
    $(document).ready(function() {
        // Inisialisasi Select2 dengan tema Bootstrap 4
        $('#kd_refobat').select2({
            theme: 'bootstrap4',
            placeholder: "Cari Nama Obat...",
            allowClear: true,
            width: '100%'
        });

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

        // Submit Form
        $('#filterFormPembelianperobat').on('submit', function(e) {
            e.preventDefault();
            $('#loadingIcon').show();
            $('#tableContainer').hide();

            $.ajax({
                url: '<?= base_url("farmasipemblianobt/tampildatapembelianobt") ?>',
                type: 'POST',
                data: {
                    TANGGAL_AWAL: $('#tanggal_awal_perobat').val(),
                    TANGGAL_AKHIR: $('#tanggal_akhir_perobat').val(),
                    KD_OBAT: $('#kd_refobat').val()
                },
            success: function(response) {
                $('#loadingIcon').hide();
                try {
                    const data = JSON.parse(response);
                    if (data && data.response && data.response.length > 0) {
                        let html = `<table id="datatablesSimple" class="table table-striped table-bordered table-sm w-100">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Tanggal Beli</th>
                                    <th>Nama Obat</th>
                                    <th>Obat Fornas</th>
                                    <th>Obat FOI</th>
                                    <th>Obat RKO</th>
                                    <th>Obat High Alert</th>
                                    <th>No Nota</th>
                                    <th>Qty</th>
                                    <th>Qty Vol Satuan</th>
                                    <th>Harga Satuan</th>
                                    <th>SubTotal</th>
                                    <th>Harga Beli Terakhir</th>
                                    <th>Supplier</th>
                                    <th>Nama Pabrik</th>
                                </tr>
                            </thead>
                            <tbody>`;

                        data.response.forEach(item => {
                            // Tambahkan logika Ya/Tidak di sini
                            let fornas = item.is_obat_fornas === 'T' ? 'Ya' : (item.is_obat_fornas === 'F' ? 'Tidak' : '-');
                            let foi = item.is_obat_foi === 'T' ? 'Ya' : (item.is_obat_foi === 'F' ? 'Tidak' : '-');
                            let rko = item.is_obat_rko === 'T' ? 'Ya' : (item.is_obat_rko === 'F' ? 'Tidak' : '-');
                            let highAlert = item.is_high_alert === 'T' ? 'Ya' : (item.is_high_alert === 'F' ? 'Tidak' : '-');

                            html += `<tr>
                                <td>${item.tgl_beli}</td>
                                <td>${item.nama_obat}</td>
                                <td>${fornas}</td>
                                <td>${foi}</td>
                                <td>${rko}</td>
                                <td>${highAlert}</td>
                                <td>${item.no_nota}</td>
                                <td>${item.qty}</td>
                                <td>${item.qty_vol_satuan}</td>
                                <td>${parseFloat(item.harga_satuan).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.sub_total).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>`;
                        });

                        html += '</tbody></table>';
                        $('#tableContainer').html(html).fadeIn();
                        $('#datatablesSimple').DataTable();
                        $('#downloadButton_pembalianperobat').show();
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning">Data tidak ditemukan.</div>').show();
                        }
                    } catch (e) {
                        alert('Gagal memproses data');
                    }
                }
            });
        });

        // Download Excel
        $('#downloadButton_pembalianperobat').on('click', function() {
            const tgl1 = $('#tanggal_awal_perobat').val();
            const tgl2 = $('#tanggal_akhir_perobat').val();
            const obat = $('#kd_refobat').val();
            window.location.href = `<?= base_url("farmasipemblianobt/unduhdataobtpembelian") ?>?TANGGAL_AWAL=${tgl1}&TANGGAL_AKHIR=${tgl2}&KD_OBAT=${obat}`;
        });
    });
</script>
</body>
</html>