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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Farmasi Data Obat Kronis</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/dataTables.bootstrap4.min.css" rel="stylesheet">
    
    <style>
        body, html { overflow-x: hidden !important; width: 100%; max-width: 100vw; }
        .card { border: 1px solid #e3e6f0; border-radius: 8px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15); width: 100%; overflow-x: hidden; }
        .form-control-sm { height: calc(1.5em + 0.5rem + 2px); padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
        th, td { white-space: nowrap; vertical-align: middle !important; }
        
        .table-responsive { width: 100% !important; max-width: 100% !important; overflow-x: auto !important; -webkit-overflow-scrolling: touch; border: none; }

        /* Styling Nav Pills agar rapi dan bisa 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; }
    </style>
</head>

<body class="bg-light">
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4 mt-4 overflow-hidden">
                <h1 class="h3 mb-2 text-gray-800">Farmasi Data Obat Kronis</h1>
                <ol class="breadcrumb mb-4 shadow-sm bg-white p-2 rounded">
                    <li class="breadcrumb-item"><a href="#" class="text-decoration-none text-muted">Dashboard</a></li>
                    <li class="breadcrumb-item active">Data Obat Kronis</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-kronis-tab" data-toggle="pill" href="#pills-kronis" role="tab">
                            <i class="fas fa-pills mr-2"></i>Data Obat Kronis
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link shadow-sm" id="pills-detail-tab" data-toggle="pill" href="#pills-detail" role="tab">
                            <i class="fas fa-list-alt mr-2"></i>Detail Obat Kronis
                        </a>
                    </li>
                </ul>

                <div class="tab-content" id="pills-tabContent">
                    
                    <div class="tab-pane fade show active" id="pills-kronis" role="tabpanel">
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-header py-3 bg-white">
                                <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-filter mr-1"></i> Filter Data Obat Kronis</h6>
                            </div>
                            <div class="card-body bg-light">
                                <form id="filterFormKronis"> 
                                    <div class="row align-items-end">
                                        <div class="col-12 col-md-4 mb-2 mb-md-0">
                                            <label class="small mb-1 font-weight-bold">Tanggal Awal</label>
                                            <input type="date" id="tgl_awal" name="TANGGAL_AWAL" class="form-control form-control-sm" value="<?= $tgl_awal ?>" required>
                                        </div>
                                        <div class="col-12 col-md-4 mb-2 mb-md-0">
                                            <label class="small mb-1 font-weight-bold">Tanggal Akhir</label>
                                            <input type="date" id="tgl_akhir" name="TANGGAL_AKHIR" class="form-control form-control-sm" value="<?= $tgl_akhir ?>" required>
                                        </div>
                                        <div class="col-12 col-md-4">
                                            <div class="d-flex">
                                                <button type="submit" class="btn btn-primary btn-sm mr-2 flex-fill shadow-sm">
                                                    <i class="fas fa-search"></i> Tampilkan
                                                </button>
                                                <button type="button" id="btnDownloadKronis" class="btn btn-success btn-sm flex-fill shadow-sm" style="display: none;">
                                                    <i class="fas fa-file-excel"></i> Download
                                                </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="loadingIconKronis" style="display: none;" class="py-5 text-center">
                                    <div class="spinner-border text-primary" role="status"></div>
                                    <div class="mt-2 font-weight-bold text-primary small">Memuat Data...</div>
                                </div>
                                <div id="tableContainerKronis" class="table-responsive">
                                    <div class="text-center text-muted py-5">Silakan filter data terlebih dahulu.</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-detail" role="tabpanel">
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-header py-3 bg-white">
                                <h6 class="m-0 font-weight-bold text-info"><i class="fas fa-search mr-1"></i> Filter Detail Obat Kronis</h6>
                            </div>
                            <div class="card-body bg-light">
                                <form id="filterFormDetail"> 
                                    <div class="row align-items-end">
                                        <div class="col-12 col-md-4 mb-2 mb-md-0">
                                            <label class="small mb-1 font-weight-bold">Tanggal Awal</label>
                                            <input type="date" id="tgl_awal_detail" name="TANGGAL_AWAL" class="form-control form-control-sm" value="<?= $tgl_awal ?>" required>
                                        </div>
                                        <div class="col-12 col-md-4 mb-2 mb-md-0">
                                            <label class="small mb-1 font-weight-bold">Tanggal Akhir</label>
                                            <input type="date" id="tgl_akhir_detail" name="TANGGAL_AKHIR" class="form-control form-control-sm" value="<?= $tgl_akhir ?>" required>
                                        </div>
                                        <div class="col-12 col-md-4">
                                            <div class="d-flex">
                                                <button type="submit" class="btn btn-info btn-sm mr-2 flex-fill shadow-sm text-white">
                                                    <i class="fas fa-search"></i> Tampilkan
                                                </button>
                                                <button type="button" id="btnDownloadDetail" class="btn btn-success btn-sm flex-fill shadow-sm" style="display: none;">
                                                    <i class="fas fa-file-excel"></i> Download
                                                </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="loadingIconDetail" style="display: none;" class="py-5 text-center">
                                    <div class="spinner-border text-info" role="status"></div>
                                    <div class="mt-2 font-weight-bold text-info small">Memuat Data Detail...</div>
                                </div>
                                <div id="tableContainerDetail" class="table-responsive">
                                    <div class="text-center text-muted py-5">Silakan filter data detail terlebih dahulu.</div>
                                </div>
                            </div>
                        </div>
                    </div>

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

        <footer class="py-4 bg-white mt-auto border-top">
            <div class="container-fluid px-4">
                <div class="small text-muted text-center">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.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>

    <script>
        $(document).ready(function() {
            
            // Set Default Date
            const today = new Date().toISOString().split('T')[0];
            if(!$('#tgl_akhir').val()) $('#tgl_akhir').val(today);
            if(!$('#tgl_akhir_detail').val()) $('#tgl_akhir_detail').val(today);

            // Fungsi Helper Uang
            const formatUang = (val) => parseFloat(val || 0).toLocaleString('id-ID');

            // ==============================================================
            // TAB 1: LOGIKA OBAT KRONIS
            // ==============================================================
            $('#filterFormKronis').on('submit', function(e) {
                e.preventDefault();
                let tglAwal = $('#tgl_awal').val();
                let tglAkhir = $('#tgl_akhir').val();

                $('#loadingIconKronis').show();
                $('#tableContainerKronis').hide();
                $('#btnDownloadKronis').hide();

                $.ajax({
                    url: '<?= base_url("farmasiobatkronis/tampildata") ?>', 
                    type: 'POST',
                    data: { TANGGAL_AWAL: tglAwal, TANGGAL_AKHIR: tglAkhir },
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIconKronis').hide();
                        
                        if (data && data.response && Array.isArray(data.response) && data.response.length > 0) {
                            let html = `<table id="dataTableKronis" class="table table-bordered table-striped table-sm w-100" style="white-space: nowrap;">
                                <thead class="thead-dark text-center">
                                    <tr>
                                        <th>Kode Registrasi</th>
                                        <th>Nama Pasien</th>
                                        <th>No SJP</th>
                                        <th>No SEP</th>
                                        <th>Kd Obat</th>
                                        <th>Nama Obat</th>
                                        <th>Nama Obat BPJS</th>
                                        <th>Qty Jual</th>
                                        <th>Sub Total</th>
                                        <th>Total</th>
                                        <th>Total Harga Jual</th>
                                        <th>Harga Satuan</th>
                                        <th>Nama Pabrik</th>
                                        <th>Total Harga Beli</th>
                                        <th>Total Harga BPJS</th>
                                    </tr>
                                </thead>
                                <tbody>`;

                            data.response.forEach(item => {
                                html += `<tr>
                                    <td>${item.kd_registrasi}</td>
                                    <td class="text-wrap" style="min-width: 150px;">${item.nm_pasien}</td>
                                    <td>${item.nosjp || '-'}</td>
                                    <td>${item.no_sep || '-'}</td>
                                    <td>${item.kd_obat}</td>
                                    <td class="text-wrap" style="min-width: 200px;">${item.nama_obat}</td>
                                    <td class="text-wrap" style="min-width: 200px;">${item.nm_obat_bpjs || '-'}</td>
                                    <td class="text-center font-weight-bold text-primary">${item.qty_jual}</td>
                                    <td class="text-right">${formatUang(item.sub_total)}</td>
                                    <td class="text-right">${formatUang(item.total)}</td>
                                    <td class="text-right font-weight-bold">${formatUang(item.total_harga_jual)}</td>
                                    <td class="text-right">${formatUang(item.harga_satuan)}</td>
                                    <td class="text-wrap" style="min-width: 150px;">${item.nama_pabrik || '-'}</td>
                                    <td class="text-right text-danger">${formatUang(item.total_harga_beli)}</td>
                                    <td class="text-right text-success">${formatUang(item.total_harga_bpjs)}</td>
                                </tr>`;
                            });

                            html += `</tbody></table>`;
                            $('#tableContainerKronis').html(html).show();
                            $('#dataTableKronis').DataTable({
                                "language": { "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Indonesian.json" },
                                "pageLength": 10, "scrollX": true 
                            });
                            $('#btnDownloadKronis').show();
                        } else {
                            $('#tableContainerKronis').html('<div class="alert alert-info text-center m-3">Tidak ada data ditemukan.</div>').show();
                        }
                    },
                    error: function() {
                        $('#loadingIconKronis').hide();
                        $('#tableContainerKronis').html(`<div class="alert alert-danger text-center m-3">Gagal mengambil data dari server.</div>`).show();
                    }
                });
            });

            $('#btnDownloadKronis').on('click', function() {
                let ta = $('#tgl_awal').val();
                let tak = $('#tgl_akhir').val();
                window.location.href = `<?= base_url("farmasiobatkronis/unduhdata") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
            });


            // ==============================================================
            // TAB 2: LOGIKA DETAIL OBAT 
            // ==============================================================
            $('#filterFormDetail').on('submit', function(e) {
                e.preventDefault();
                let tglAwal = $('#tgl_awal_detail').val();
                let tglAkhir = $('#tgl_akhir_detail').val();

                $('#loadingIconDetail').show();
                $('#tableContainerDetail').hide();
                $('#btnDownloadDetail').hide();

                $.ajax({
                    url: '<?= base_url("farmasiobatkronis/tampildetail") ?>', 
                    type: 'POST',
                    data: { TANGGAL_AWAL: tglAwal, TANGGAL_AKHIR: tglAkhir },
                    dataType: 'json',
                    success: function(data) {
                        $('#loadingIconDetail').hide();
                        
                        // Menyesuaikan dengan standar array response API Anda
                        let arrData = data.response || data.tampil || data;

                        if (Array.isArray(arrData) && arrData.length > 0) {
                            let html = `<table id="dataTableDetail" class="table table-bordered table-striped table-hover table-sm w-100" style="white-space: nowrap; font-size: 0.85rem;">
                                <thead class="thead-dark text-center">
                                    <tr>
                                        <th>KD Registrasi</th>
                                        <th>KD Jual</th>
                                        <th>No SJP</th>
                                        <th>Nama Pasien</th>
                                        <th>No Kartu</th>
                                        <th>KD Obat</th>
                                        <th>Nama Obat</th>
                                        <th class="bg-warning">Qty Jual</th>
                                        <th>Harga Jual</th>
                                        <th>Harga Beli</th>
                                        <th>NM Obat</th>
                                        <th>Jml Obat</th>
                                        <th>Jenis Obat</th>
                                        <th>Harga BPJS</th>
                                        <th>Selisih</th>
                                        <th>Total Qty Jual</th>
                                        <th>Total Qty BPJS Jual</th>
                                        <th>Total Qty Beli</th>
                                        <th>Total Qty BPJS</th>
                                    </tr>
                                </thead>
                                <tbody>`;

                            arrData.forEach(item => {
                                html += `<tr>
                                    <td class="font-weight-bold text-primary">${item.kd_registrasi || '-'}</td>
                                    <td class="font-weight-bold">${item.kd_jual || '-'}</td>
                                    <td>${item.nosjp || '-'}</td>
                                    <td class="text-wrap" style="min-width: 150px;">${item.nama || '-'}</td>
                                    <td>${item.no_kartu || '-'}</td>
                                    <td>${item.kd_obat || '-'}</td>
                                    <td class="text-wrap" style="min-width: 200px;">${item.nama_obat || '-'}</td>
                                    <td class="text-center font-weight-bold text-danger bg-light">${item.qty_jual || '0'}</td>
                                    <td class="text-right text-success font-weight-bold">${formatUang(item.harga_jual)}</td>
                                    <td class="text-right text-primary">${formatUang(item.harga_beli)}</td>
                                    <td>${item.nm_obat || '-'}</td>
                                    <td class="text-center">${item.jml_obat || '0'}</td>
                                    <td>${item.jenis_obat || '-'}</td>
                                    <td class="text-right text-info">${formatUang(item.harga_bpjs)}</td>
                                    <td class="text-right font-weight-bold">${formatUang(item.selisih)}</td>
                                    <td class="text-center font-weight-bold">${item.total_qty_jual || '0'}</td>
                                    <td class="text-center">${item.total_qty_bpjs_jual || '0'}</td>
                                    <td class="text-center">${item.total_qty_beli || '0'}</td>
                                    <td class="text-center">${item.total_qty_bpjs || '0'}</td>
                                </tr>`;
                            });

                            html += `</tbody></table>`;
                            $('#tableContainerDetail').html(html).show();
                            $('#dataTableDetail').DataTable({
                                "language": { "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Indonesian.json" },
                                "pageLength": 10, "scrollX": true 
                            });
                            $('#btnDownloadDetail').show();
                        } else {
                            $('#tableContainerDetail').html('<div class="alert alert-info text-center m-3">Tidak ada data detail ditemukan.</div>').show();
                        }
                    },
                    error: function() {
                        $('#loadingIconDetail').hide();
                        $('#tableContainerDetail').html(`<div class="alert alert-danger text-center m-3">Gagal mengambil data dari server.</div>`).show();
                    }
                });
            });

            $('#btnDownloadDetail').on('click', function() {
                let ta = $('#tgl_awal_detail').val();
                let tak = $('#tgl_akhir_detail').val();
                window.location.href = `<?= base_url("farmasiobatkronis/unduhdetail") ?>?TANGGAL_AWAL=${ta}&TANGGAL_AKHIR=${tak}`;
            });

        });
    </script>
</body>
</html>