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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Farmasi Pembelian</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" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">

    <style>
        .nav-pills .nav-link {
            border-radius: 50px;
            padding: 10px 20px;
            font-weight: 500;
            margin-right: 10px;
            margin-bottom: 10px;
            border: 1px solid #e3e6f0;
            color: #5a5c69;
            background-color: #fff;
        }

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

        .select2-results__options {
            max-height: 250px !important;
            overflow-y: auto;
        }

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

        .select2-container .select2-selection--single {
            height: 38px !important;
        }

        .select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered {
            line-height: 36px !important;
        }

        @media (max-width: 768px) {
            .container {
                width: 100%;
            }
        }

        /* Style Tambahan untuk tombol detail di tabel */
        .btn-detail-supplier {
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4" id="judulPasien">Data Farmasi</h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="index.html">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" id="pills-penjualan-tab" data-toggle="pill" href="#pills-penjualan" role="tab">
                            <i class="fas fa-shopping-cart mr-2"></i>Farmasi Pembelian
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="pills-penjualanperobt-tab" data-toggle="pill" href="#pills-penjualanperobt" role="tab">
                            <i class="fas fa-solid fa-file-medical mr-2"></i>Farmasi Pembelian Per-obat
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="pills-penjualanperpbk-tab" data-toggle="pill" href="#pills-penjualanperpbk" role="tab">
                            <i class="fas fa-solid fa-industry mr-2"></i>Farmasi Pembelian Per-Pabrik
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="pills-pembelianpersp-tab" data-toggle="pill" href="#pills-pembelianpersp" role="tab">
                            <i class="fas fa-solid fa-industry mr-2"></i>Farmasi Pembelian Per-Suplier
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="pills-rekappersp-tab" data-toggle="pill" href="#pills-rekappersp" role="tab">
                            <i class="fas fa-solid fa-industry mr-2"></i>Rekap Pembelian Supplier
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="pills-rekapperpb-tab" data-toggle="pill" href="#pills-rekapperpb" role="tab">
                            <i class="fas fa-solid fa-industry mr-2"></i>Rekap Pembelian Per-Pabrik
                        </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">Data Farmasi Pembelian</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormPembelian">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label>Tanggal Awal</label>
                                                <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                            </div>
                                        </div>
                                        <div class="col-md-10">
                                            <div class="form-group">
                                                <label>Tanggal Akhir</label>
                                                <div class="input-group">
                                                    <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required style="max-width: 200px;" />
                                                    <button type="submit" class="btn btn-primary ml-2">Submit</button>
                                                    <button type="button" id="downloadButton" class="btn btn-success ml-3" style="display: none;">Download Excel</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result" class="table-responsive">
                            <div id="loadingIcon" style="display: none; text-align:center;">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                            </div>
                            <div id="tableContainer" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-penjualanperobt" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2">Data Farmasi Pembelian Per-Obat</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormPembelianperobat">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label>Tanggal Awal</label>
                                                <input type="date" id="tanggal_awal_perobat" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                            </div>
                                        </div>
                                        <div class="col-md-10">
                                            <div class="form-group">
                                                <label>Tanggal Akhir</label>
                                                <div class="input-group">
                                                    <input type="date" id="tanggal_akhir_perobat" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required style="max-width: 200px;" />

                                                    <div class="ml-3" style="min-width: 300px; max-width: 400px;">
                                                        <select id="kd_refobat" name="KD_OBAT" class="form-control" required>
                                                            <option value="" disabled selected>Memuat Kode Obat...</option>
                                                        </select>
                                                    </div>

                                                    <button type="submit" class="btn btn-primary ml-2">Submit</button>
                                                    <button type="button" id="downloadButton_perobat" class="btn btn-success ml-3" style="display: none;">Download Excel</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result_perobat" class="table-responsive">
                            <div id="loadingIcon_perobat" style="display: none; text-align:center;">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                            </div>
                            <div id="tableContainer_perobat" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-penjualanperpbk" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2">Data Farmasi Pembelian Per-Pabrik</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormPembelianperpabrik">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label>Tanggal Awal</label>
                                                <input type="date" id="tanggal_awal_perpabrik" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                                            </div>
                                        </div>
                                        <div class="col-md-10">
                                            <div class="form-group">
                                                <label>Tanggal Akhir</label>
                                                <div class="input-group">
                                                    <input type="date" id="tanggal_akhir_perpabrik" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required style="max-width: 200px;" />
                                                    <div class="ml-3" style="min-width: 300px; max-width: 400px;">
                                                        <select id="kd_refpabrik" name="KD_PABRIK" class="form-control" required>
                                                            <option value="" disabled selected>Memuat Nama Pabrik...</option>
                                                        </select>
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ml-2">Submit</button>
                                                    <button type="button" id="downloadButton_perpabrik" class="btn btn-success ml-3" style="display: none;">Download Excel</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result_pabrik" class="table-responsive">
                            <div id="loadingIcon_perpabrik" style="display: none; text-align:center;">
                                <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." />
                            </div>
                            <div id="tableContainer_perpabrik" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-pembelianpersp" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2">Data Farmasi Pembelian Per-Suplier</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormPembelianperpsuplier" method="POST">
                                    <div class="row align-items-end">
                                        <div class="col-md-3">
                                            <div class="form-group mb-0"><label>Tanggal Awal</label><input type="date" id="tanggal_awal_persuplier" name="TANGGAL_AWAL" class="form-control form-control-sm" value="<?= $tgl_awal ?>" required /></div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group mb-0"><label>Tanggal Akhir</label><input type="date" id="tanggal_akhir_persuplier" name="TANGGAL_AKHIR" class="form-control form-control-sm" value="<?= $tgl_akhir ?>" required /></div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group mb-0"><label>Supplier</label><select id="kd_refsuplier" name="KD_SUPLIER" class="form-control form-control-sm" required></select></div>
                                        </div>
                                        <div class="col-12 mt-3">
                                            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i> Tampilkan</button>
                                            <button type="button" id="downloadButton_suplierk" class="btn btn-success btn-sm ml-2" style="display: none;">Download Rekap</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result_suplier" class="table-responsive">
                            <div id="loadingIcon_persuplier" style="display: none; text-align:center;"><img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" width="50" /></div>
                            <div id="tableContainer_persuplier" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-rekappersp" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2">Rekap Pembelian Supplier</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormRekapPersp">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group"><label>Tanggal Awal</label><input type="date" id="tanggal_awal_rekappersp" class="form-control" value="<?= $tgl_awal ?>" required /></div>
                                        </div>
                                        <div class="col-md-10">
                                            <div class="form-group">
                                                <label>Tanggal Akhir</label>
                                                <div class="input-group">
                                                    <input type="date" id="tanggal_akhir_rekappersp" class="form-control" value="<?= $tgl_akhir ?>" required style="max-width: 200px;" />
                                                    <button type="submit" class="btn btn-primary ml-2">Submit</button>
                                                    <button type="button" id="downloadButton_rekappersp" class="btn btn-success ml-3" style="display: none;">Download Excel</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result_rekapsupplier" class="table-responsive">
                            <div id="loadingIcon_rekappersp" style="display: none; text-align:center;"><img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." /></div>
                            <div id="tableContainer_rekappersp" style="display: none;"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-rekapperpb" role="tabpanel">
                        <h5 class="mb-3 border-bottom pb-2">Rekap Pembelian Per-Pabrik</h5>
                        <div class="card mb-4">
                            <div class="card-body">
                                <form id="filterFormRekapperpb">
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group"><label>Tanggal Awal</label><input type="date" id="tanggal_awal_rekapperpb" class="form-control" value="<?= $tgl_awal ?>" required /></div>
                                        </div>
                                        <div class="col-md-10">
                                            <div class="form-group">
                                                <label>Tanggal Akhir</label>
                                                <div class="input-group">
                                                    <input type="date" id="tanggal_akhir_rekapperpb" class="form-control" value="<?= $tgl_akhir ?>" required style="max-width: 200px;" />
                                                    <button type="submit" class="btn btn-primary ml-2">Submit</button>
                                                    <button type="button" id="downloadButton_rekapperpb" class="btn btn-success ml-3" style="display: none;">Download Excel</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div id="result_rekappabrik" class="table-responsive">
                            <div id="loadingIcon_rekapperpb" style="display: none; text-align:center;"><img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." /></div>
                            <div id="tableContainer_rekapperpb" style="display: none;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <footer class="py-4 bg-light mt-auto">
            <div class="container-fluid px-4">
                <div class="text-muted">Copyright &copy; By IT RSU Ananda Purwokerto 2024</div>
            </div>
        </footer>
    </div>

    <form id="formDetailSupplier" action="<?= base_url('farmasipemblianspl/tampiltabdetail') ?>" method="POST" target="_blank" style="display:none;">
        <input type="hidden" name="TANGGAL_AWAL" id="hidden_tgl_awal">
        <input type="hidden" name="TANGGAL_AKHIR" id="hidden_tgl_akhir">
        <input type="hidden" name="KD_SUPLIER" id="hidden_kd_suplier">
        <input type="hidden" name="NO_NOTA" id="hidden_no_nota">
    </form>

    <script src="https://code.jquery.com/jquery-3.5.1.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/sweetalert2@11"></script>

    <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 pada Dropdown Obat
            // Ini akan mengubah tampilan select biasa menjadi Searchable Dropdown yang rapi
            $('#kd_refobat').select2({
                theme: 'bootstrap4',
                width: '100%', // Mengikuti lebar container induknya (div.ml-3)
                placeholder: "Pilih atau Cari Nama Obat",
                allowClear: true
            });

            $('#kd_refpabrik').select2({
                theme: 'bootstrap4',
                width: '100%', // Mengikuti lebar container induknya (div.ml-3)
                placeholder: "Pilih atau Cari Nama Pabrik",
                allowClear: true
            });

            $('#kd_refsuplier').select2({
                theme: 'bootstrap4',
                width: '100%', // Mengikuti lebar container induknya (div.ml-3)
                placeholder: "Pilih atau Cari Nama Suplier",
                allowClear: true
            });

            // Load data master obat 
            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>Pilih 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);
                            });

                            // TAMBAHAN PENTING: Trigger change agar Select2 mendeteksi perubahan data
                            grupMasterobtDropdown.trigger('change');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX Error:", status, error);
                        grupMasterobtDropdown.empty().append('<option value="" disabled selected>Gagal memuat Data Master Obat</option>');
                    }
                })
            }
            loadMasterobat();

            // Load data master nama pabrik 
            function loadMasterpabrik() {
                const grupMasterpbkDropdown = $('#kd_refpabrik');
                $.ajax({
                    url: '<?php echo base_url("farmasipemblianpbk/refrensipabrik"); ?>',
                    type: 'POST',
                    dataType: 'json',
                    success: function(data) {
                        grupMasterpbkDropdown.empty().append('<option value="" disabled selected>Pilih Nama Obat</option>');
                        if (data && Array.isArray(data.response)) {
                            $.each(data.response, function(index, kodeobat) {
                                const option = new Option(kodeobat.nm_pabrik, kodeobat.kd_pabrik);
                                grupMasterpbkDropdown.append(option);
                            });

                            // TAMBAHAN PENTING: Trigger change agar Select2 mendeteksi perubahan data
                            grupMasterpbkDropdown.trigger('change');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX Error:", status, error);
                        grupMasterpbkDropdown.empty().append('<option value="" disabled selected>Gagal memuat Data Master Pabrik</option>');
                    }
                })
            }
            loadMasterpabrik();


            // Load data master nama Suplier 
            function loadMastersuplier() {
                const grupMastersplDropdown = $('#kd_refsuplier');
                $.ajax({
                    url: '<?php echo base_url("farmasipemblianspl/refsuplier"); ?>',
                    type: 'POST',
                    dataType: 'json',
                    success: function(data) {
                        grupMastersplDropdown.empty().append('<option value="" disabled selected>Pilih Nama Obat</option>');
                        if (data && Array.isArray(data.response)) {
                            $.each(data.response, function(index, kodeobat) {
                                const option = new Option(kodeobat.nm_suplier, kodeobat.kd_suplier);
                                grupMastersplDropdown.append(option);
                            });

                            // TAMBAHAN PENTING: Trigger change agar Select2 mendeteksi perubahan data
                            grupMastersplDropdown.trigger('change');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("AJAX Error:", status, error);
                        grupMastersplDropdown.empty().append('<option value="" disabled selected>Gagal memuat Data Master Suplier</option>');
                    }
                })
            }
            loadMastersuplier();

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

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


                $.ajax({
                    url: '<?= base_url("farmasipemblianobt/pembelianobatall") ?>',
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: tglAwal,
                        TANGGAL_AKHIR: tglAkhir
                    },
                    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 = `<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>Qty</th>   
                                    <th>Qty Vol Satuan</th>
                                    <th>Harga Satuan</th>   
                                    <th>SubTotal</th>
                                    <th>Nilai Disc</th>
                                    <th>Persentase Disc</th>
                                    <th>Total</th>
                                    <th>Nama Obat Alias</th>
                                    <th>Harga Beli Terakhir</th>
                                    <th>Harga Jual</th>
                                    <th>Tanggal Exp</th>
                                    <th>Supplier</th>
                                    <th>Nama Pabrik</th>
                                    <th>Harga Faktur Terakhir</th>
                                </tr>
                            </thead>
                            <tbody>`;

                                data.response.forEach(item => {
                                    html += `<tr>
                                    <td>${item.tgl_beli}</td>
                                    <td>${item.nama_obat}</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.nilai_disc).toLocaleString('id-ID')}</td>
                                    <td>${parseFloat(item.prosen_disc).toLocaleString('id-ID')}</td>
                                    <td>${parseFloat(item.total).toLocaleString('id-ID')}</td>
                                    <td>${item.nama_obat_alias}</td>
                                    <td>${parseFloat(item.harga_beli_terakhir).toLocaleString('id-ID')}</td>
                                    <td>${parseFloat(item.harga_jual).toLocaleString('id-ID')}</td>
                                    <td>${item.expired_date}</td>
                                    <td>${item.nm_suplier}</td>
                                    <td>${item.nm_pabrik}</td>
                                    <td>${parseFloat(item.harga_faktur_terakhir).toLocaleString('id-ID')}</td>
                                </tr>`;
                                });
                                html += '</tbody></table>';

                                $('#tableContainer').html(html).show();
                                $('#datatablesSimple').DataTable({
                                    "order": [
                                        [0, "asc"]
                                    ]
                                });
                                $('#downloadButton').show();
                            } else {
                                $('#tableContainer').html('<div class="alert alert-info">Tidak ada data.</div>').show();
                                $('#downloadButton').hide();
                            }
                        } catch (e) {
                            $('#tableContainer').html('<div class="alert alert-danger">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();
                window.location.href = `<?= base_url("farmasipemblianobt/unduhpembelianall") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
            });

            // ==========================================
            // LOGIKA TAB 2: PEMBELIAN PER OBAT (FIXED)
            // ==========================================
            $('#filterFormPembelianperobat').on('submit', function(event) {
                event.preventDefault();
                // Update selector ke ID _perobat
                $('#loadingIcon_perobat').show();
                $('#tableContainer_perobat').hide();

                // Ambil value dari ID input yang baru
                var tglAwal = $('#tanggal_awal_perobat').val();
                var tglAkhir = $('#tanggal_akhir_perobat').val();
                var kdObat = $('#kd_refobat').val();

                $.ajax({
                    url: '<?= base_url("farmasipemblianobt/tampildatapembelianobt") ?>',
                    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) {

                                // Gunakan ID Table Unik: datatablesPerObat (Jangan datatablesSimple lagi)
                                if ($.fn.DataTable.isDataTable('#datatablesPerObat')) {
                                    $('#datatablesPerObat').DataTable().destroy();
                                }

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

                                data.response.forEach(item => {
                                    html += `<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>`;
                                });
                                html += '</tbody></table>';

                                // Render ke Container _perobat
                                $('#tableContainer_perobat').html(html).show();
                                // Init Datatable yang baru
                                $('#datatablesPerObat').DataTable({
                                    "order": [
                                        [0, "asc"]
                                    ]
                                });
                                $('#downloadButton_perobat').show();
                            } else {
                                $('#tableContainer_perobat').html('<div class="alert alert-info">Tidak ada data.</div>').show();
                                $('#downloadButton_perobat').hide();
                            }
                        } catch (e) {
                            $('#tableContainer_perobat').html('<div class="alert alert-danger">Error Parsing JSON</div>').show();
                            $('#loadingIcon_perobat').hide();
                            console.log(e);
                        }
                    },
                    error: function() {
                        $('#loadingIcon_perobat').hide();
                        alert("Gagal koneksi server.");
                    }
                });
            });

            // Download Tab 2
            $('#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("farmasipemblianobt/unduhdataobtpembelian") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}&KD_OBAT=${kdf}`;
            });


            // ==========================================
            // LOGIKA TAB 3 : PEMBELIAN PER PABRIK (DENGAN TOTAL)
            // ==========================================
            $('#filterFormPembelianperpabrik').on('submit', function(event) {
                event.preventDefault();
                $('#loadingIcon_perpabrik').show();
                $('#tableContainer_perpabrik').hide();

                var tglAwal = $('#tanggal_awal_perpabrik').val();
                var tglAkhir = $('#tanggal_akhir_perpabrik').val();
                var kdPabrik = $('#kd_refpabrik').val();

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

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

                                // 1. Siapkan variabel penampung total
                                let grandTotal = 0;

                                let html = `<table id="datatablesPerPabrik" class="table table-striped table-bordered table-sm w-100">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Tanggal Masuk</th>
                                    <th>Nama Pabrik</th>   
                                    <th>Nama Supplier</th>   
                                    <th>Nama Obat</th>
                                    <th>Jumlah</th>
                                    <th>Sub Total</th>
                                    <th>Prosentase Disc</th>
                                    <th>Nilai Disc</th>
                                    <th>Pajak</th>
                                    <th>Total</th>  
                                </tr>
                            </thead>
                            <tbody>`;

                                data.response.forEach(item => {
                                    // 2. Akumulasi (Jumlahkan) Total per baris ke Grand Total
                                    // Menggunakan parseFloat untuk memastikan data dibaca sebagai angka
                                    grandTotal += parseFloat(item.total) || 0;

                                    html += `<tr>
                                    <td>${item.tgl_masuk}</td>
                                    <td>${item.nm_pabrik}</td>
                                    <td>${item.nm_suplier}</td>
                                    <td>${item.nama_obat}</td>
                                    <td>${item.qty}</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.pajak).toLocaleString('id-ID')}</td>
                                    <td>${parseFloat(item.total).toLocaleString('id-ID')}</td>
                                </tr>`;
                                });

                                html += '</tbody>';

                                // 3. Tambahkan Bagian Footer untuk Menampilkan Total
                                // colspan="9" artinya menggabungkan 9 kolom pertama untuk label "TOTAL PEMBELIAN"
                                html += `<tfoot class="bg-secondary text-white font-weight-bold">
                                <tr>
                                    <td colspan="9" class="text-right" style="text-align:right;">TOTAL PEMBELIAN :</td>
                                    <td>${grandTotal.toLocaleString('id-ID')}</td>
                                </tr>
                                </tfoot>`;

                                html += '</table>';

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

                                $('#datatablesPerPabrik').DataTable({
                                    "order": [
                                        [0, "asc"]
                                    ],
                                    // Opsi ini mencegah DataTables mengurutkan footer ikut naik ke atas
                                    "fixedHeader": true
                                });

                                $('#downloadButton_perpabrik').show();
                            } else {
                                $('#tableContainer_perpabrik').html('<div class="alert alert-info">Tidak ada data.</div>').show();
                                $('#downloadButton_perpabrik').hide();
                            }
                        } catch (e) {
                            $('#tableContainer_perpabrik').html('<div class="alert alert-danger">Error Parsing JSON</div>').show();
                            $('#loadingIcon_perpabrik').hide();
                            console.log(e);
                        }
                    },
                    error: function() {
                        $('#loadingIcon_perpabrik').hide();
                        alert("Gagal koneksi server.");
                    }
                });
            });

            // Download Tab 3
            $('#downloadButton_perpabrik').on('click', function() {
                const ta = $('#tanggal_awal_perpabrik').val();
                const tak = $('#tanggal_akhir_perpabrik').val();
                const pbkf = $('#kd_refpabrik').val();
                window.location.href = `<?= base_url("farmasipemblianpbk/unduhdatpbkpembelian") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}&KD_PABRIK=${pbkf}`;
            });


            // ==========================================
            // LOGIKA TAB 4 : PEMBELIAN PER SUPLIER
            // ==========================================

            // 1. Handle Submit Filter (Hanya Tampilkan Tabel Rekap)
            $('#filterFormPembelianperpsuplier').on('submit', function(event) {
                event.preventDefault();

                // UI Loading
                $('#loadingIcon_persuplier').show();
                $('#tableContainer_persuplier').hide();
                $('#downloadButton_suplierk').hide();

                // Ambil value
                var tglAwal = $('#tanggal_awal_persuplier').val();
                var tglAkhir = $('#tanggal_akhir_persuplier').val();
                var kdSuplier = $('#kd_refsuplier').val();

                // AJAX Request (Khusus Rekap)
                $.ajax({
                    url: '<?= base_url("farmasipemblianspl/tampildata") ?>', // Endpoint JSON Rekap
                    type: 'POST',
                    data: {
                        TANGGAL_AWAL: tglAwal,
                        TANGGAL_AKHIR: tglAkhir,
                        KD_SUPLIER: kdSuplier
                    },
                    dataType: 'json',
                    success: function(response) {
                        $('#loadingIcon_persuplier').hide();

                        let grandTotal = 0;

                        let dataArr = (response.response) ? response.response : response;

                        try {
                            if (dataArr && Array.isArray(dataArr) && dataArr.length > 0) {

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

                                // PERUBAHAN 1: Tambahkan Kolom Header "Aksi"
                                let html = `<table id="datatablesPerSuplier" class="table table-striped table-bordered table-sm w-100">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Tanggal Masuk</th>
                                        <th>No NOTA</th> 
                                        <th>Nama Suplier</th>   
                                        <th>Sub Total</th>
                                        <th>Pajak</th>
                                        <th>Total</th>
                                        <th class="text-center" style="width: 80px;">Detail Suplier</th> </tr>
                                </thead>
                                <tbody>`;

                                dataArr.forEach(item => {
                                    grandTotal += parseFloat(item.total) || 0;
                                  
                                    html += `<tr>
                                    <td>${item.tgl_masuk}</td>
                                    <td class="font-weight-bold">${item.no_nota}</td> <td>${item.nm_suplier}</td>
                                    <td class="text-right">${parseFloat(item.sub_total || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-right">${parseFloat(item.pajak || 0).toLocaleString('id-ID')}</td>
                                    <td class="text-right font-weight-bold">${parseFloat(item.total || 0).toLocaleString('id-ID')}</td>
                                    
                                    <td class="text-center">
                                        <button type="button" class="btn btn-info btn-sm btn-detail-supplier" 
                                            data-nota="${item.no_nota}" 
                                            title="Lihat Detail di Tab Baru">
                                            <i class="fas fa-search-plus"></i> Detail Data Suplier
                                        </button>
                                    </td>
                                </tr>`;
                                });

                                html += '</tbody>';

                                // 3. Tambahkan Bagian Footer untuk Menampilkan Total
                                // colspan="9" artinya menggabungkan 9 kolom pertama untuk label "TOTAL PEMBELIAN"
                                html += `<tfoot class="bg-secondary text-white font-weight-bold">
                                <tr>
                                    <td colspan="5" class="text-right" style="text-align:right;">TOTAL PEMBELIAN :</td>
                                    <td>${grandTotal.toLocaleString('id-ID')}</td>
                                </tr>
                                </tfoot>`;

                                html += '</table>';

                                $('#tableContainer_persuplier').html(html).show();
                                $('#downloadButton_suplierk').show();

                                $('#datatablesPerSuplier').DataTable({
                                    "order": [
                                        [0, "asc"]
                                    ],
                                    "pageLength": 10
                                });

                            } else {
                                $('#tableContainer_persuplier').html('<div class="alert alert-info text-center">Tidak ada data ditemukan.</div>').show();
                            }
                        } catch (e) {
                            console.error("Parsing Error:", e);
                            $('#tableContainer_persuplier').html('<div class="alert alert-danger">Terjadi kesalahan format data server.</div>').show();
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#loadingIcon_persuplier').hide();
                        console.error("AJAX Error:", error);
                        $('#tableContainer_persuplier').html(`<div class="alert alert-danger text-center">Gagal koneksi server.</div>`).show();
                    }
                });
            });

            // 2. Event Handler untuk Klik Tombol Detail di Tabel
            $(document).on('click', '.btn-detail-supplier', function(e) {
                e.preventDefault();

                // Ambil No Nota dari tombol yang diklik
                let noNota = $(this).data('nota');

                // Ambil Data Lain dari Form Filter Utama (Karena Detail butuh Tgl & Supplier juga)
                let tglAwal = $('#tanggal_awal_persuplier').val();
                let tglAkhir = $('#tanggal_akhir_persuplier').val();
                let kdSuplier = $('#kd_refsuplier').val();

                // Isi Form Hidden
                $('#hidden_tgl_awal').val(tglAwal);
                $('#hidden_tgl_akhir').val(tglAkhir);
                $('#hidden_kd_suplier').val(kdSuplier);
                $('#hidden_no_nota').val(noNota);

                // Submit Form Hidden ke Tab Baru
                $('#formDetailSupplier').submit();
            });


            // Download Tab 4
            // Event Handler untuk masing-masing tombol download
            $('#downloadButton_suplierk').on('click', function() {
                const ta = $('#tanggal_awal_persuplier').val();
                const tak = $('#tanggal_akhir_persuplier').val();
                const spl = $('#kd_refsuplier').val();
                window.location.href = `<?= base_url("farmasipemblianspl/unduhdata") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}&KD_SUPLIER=${spl}`;
            });

            // ==========================================
            // LOGIKA TAB 5: REKAP PEMBELIAN SUPPLIER 
            // ==========================================
            $('#filterFormRekapPersp').on('submit', function(event) {
                event.preventDefault();
                $('#loadingIcon_rekappersp').show();
                $('#tableContainer_rekappersp').hide();

                var tglAwal = $('#tanggal_awal_rekappersp').val();
                var tglAkhir = $('#tanggal_akhir_rekappersp').val();

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

                                let html = `<table id="datatablesRekappersp" class="table table-striped table-bordered table-sm w-100">
                            <thead class="thead-dark">
                                 <tr>
                                    <th>Nama Supplier</th> 
                                    <th>Total Sub Total</th>
                                    <th>Total Diskon</th>
                                    <th>Total Pajak</th>
                                    <th>Total Pembelian</th>
                                    <th>Ranking</th>
                                    <th>Persentase</th>
                                    <th>Urutan</th>
                                </tr>
                            </thead>
                            <tbody>`;

                                data.response.forEach(item => {
                                    const formatRupiah = (value) => {
                                        const num = parseFloat(value);
                                        return isNaN(num) ? '0' : num.toLocaleString('id-ID');
                                    };

                                    html += `<tr>
                                <td>${item.nm_suplier}</td>
                                <td>${formatRupiah(item.total_sub_total)}</td>
                                <td>${formatRupiah(item.total_diskon)}</td>
                                <td>${formatRupiah(item.total_pajak)}</td>
                                <td>${formatRupiah(item.total_pembelian)}</td>
                                <td>${item.ranking}</td>
                                <td>${item.persentase}</td>
                                <td>${item.urutan}</td>
                                </tr>`;
                                });
                                html += '</tbody></table>';

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

                                // ===== PERBAIKAN DI SINI =====
                                $('#datatablesRekappersp').DataTable({
                                    "order": [
                                        [7, "asc"]
                                    ] // Mengurutkan berdasarkan kolom Urutan (Index 7)
                                });
                                // =============================

                                $('#downloadButton_rekappersp').show();
                            } else {
                                $('#tableContainer_rekappersp').html('<div class="alert alert-info">Tidak ada data Rekap Supplier.</div>').show();
                                $('#downloadButton_rekappersp').hide();
                            }
                        } catch (e) {
                            $('#tableContainer_rekappersp').html('<div class="alert alert-danger">Error Parsing JSON</div>').show();
                        }
                    },
                    error: function() {
                        $('#loadingIcon_rekappersp').hide();
                        alert("Gagal koneksi server.");
                    }
                });
            });

            $('#downloadButton_rekappersp').on('click', function() {
                const sp1 = $('#tanggal_awal_rekappersp').val();
                const sp2 = $('#tanggal_akhir_rekappersp').val();
                window.location.href = `<?= base_url("farmasirekappbl/unduhrekap") ?>?TANGGAL_AWAL=${sp1}&TANGGAL_AKHIR=${sp2}`;
            });

            // ==========================================
            // LOGIKA TAB 6: REKAP PEMBELIAN PER-PABRIK
            // ==========================================
            $('#filterFormRekapperpb').on('submit', function(event) {
                event.preventDefault();
                $('#loadingIcon_rekapperpb').show();
                $('#tableContainer_rekapperpb').hide();

                var tglAwal = $('#tanggal_awal_rekapperpb').val();
                var tglAkhir = $('#tanggal_akhir_rekapperpb').val();

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

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

                                let html = `<table id="datatablesRekapperpb" class="table table-striped table-bordered table-sm w-100">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Nama Pabrik</th>
                                    <th>Total Qty</th>   
                                    <th>Total Sub Total</th>
                                    <th>Total Diskon</th>
                                    <th>Total Pajak</th>
                                    <th>Total Pembelian</th>
                                    <th>Presentase</th>
                                    <th>Urutan</th>
                                    <th>Ranking</th>
                                </tr>
                            </thead>
                            <tbody>`;

                                data.response.forEach(item => {
                                    html += `<tr>
                                <td>${item.nm_pabrik}</td>
                                <td>${parseFloat(item.total_qty).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.total_sub_total).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.total_diskon).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.total_pajak).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.total_pembelian).toLocaleString('id-ID')}</td>
                                <td>${parseFloat(item.persentase).toLocaleString('id-ID')}</td>
                                <td>${item.urutan}</td>
                                <td>${item.ranking}</td>
                                </tr>`;
                                });
                                html += '</tbody></table>';

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

                                // Inisialisasi DataTable dengan pengaturan urutan
                                $('#datatablesRekapperpb').DataTable({
                                    "order": [
                                        [8, "asc"]
                                    ], // Indeks 7 adalah kolom 'Urutan'
                                    "pageLength": 10
                                });

                                $('#downloadButton_rekapperpb').show();
                            } else {
                                $('#tableContainer_rekapperpb').html('<div class="alert alert-info">Tidak ada data Rekap Pembelian Farmasi Per-pabrik.</div>').show();
                                $('#downloadButton_rekapperpb').hide();
                            }
                        } catch (e) {
                            $('#tableContainer_rekapperpb').html('<div class="alert alert-danger">Error Parsing JSON</div>').show();
                            console.log(e);
                        }
                    },
                    error: function() {
                        $('#loadingIcon_rekapperpb').hide();
                        alert("Gagal koneksi server.");
                    }
                });
            });
            $('#downloadButton_rekapperpb').on('click', function() {
                const pb1 = $('#tanggal_awal_rekapperpb').val();
                const pb2 = $('#tanggal_akhir_rekapperpb').val();
                window.location.href = `<?= base_url("farmasirekappbl/unduhrekappbk") ?>?TANGGAL_AWAL=${pb1}&TANGGAL_AKHIR=${pb2}`;
            });
        });
    </script>
</body>

</html>