<style>
    /* ========================================================
       1. CSS CORE RESPONSIVE (ANTI HALAMAN JEBOL)
       ======================================================== */
    body,
    html {
        overflow-x: hidden !important;
        width: 100%;
        max-width: 100vw;
    }

    @media (max-width: 991.98px) {
        #layoutSidenav_content {
            padding-left: 0 !important;
            margin-left: 0 !important;
            width: 100% !important;
            max-width: 100vw !important;
        }

        .container-fluid {
            padding-left: 10px !important;
            padding-right: 10px !important;
        }
    }

    #layoutSidenav_content {
        width: 100%;
        max-width: 100vw;
        overflow-x: hidden !important;
    }

    /* Memaksa Tabel agar menyesuaikan layar */
    table,
    table.dataTable {
        min-width: 0 !important;
        width: 100% !important;
        border-collapse: collapse !important;
    }

    .card {
        width: 100% !important;
        max-width: 100% !important;
        min-width: 0 !important;
        overflow-x: hidden;
    }

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

    /* ========================================================
       2. STYLING KOTAK FILTER & TOMBOL
       ======================================================== */
    .filter-wrapper {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    /* Responsif Form */
    @media (max-width: 768px) {
        .filter-wrapper .form-group {
            margin-bottom: 12px;
        }

        .btn-group-custom {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            margin-top: 10px;
        }

        .btn-group-custom button {
            width: 100%;
            margin-left: 0 !important;
        }

        div.dataTables_wrapper div.dataTables_filter input {
            width: 140px !important;
        }
    }

    @media (min-width: 769px) {
        .btn-group-custom {
            display: flex;
            gap: 10px;
            align-items: flex-end;
            height: 100%;
            padding-bottom: 2px;
        }
    }
</style>

<div id="layoutSidenav_content">
    <main>
        <div class="container-fluid px-3 px-md-4 overflow-hidden">
            <h1 class="mt-4 fs-3" id="judulPasien">Data Rekap Keuangan Homecare</h1>
            <ol class="breadcrumb mb-4 shadow-sm bg-white p-2 rounded">
                <li class="breadcrumb-item"><a href="index.html" class="text-decoration-none text-muted">Dashboard</a></li>
                <li class="breadcrumb-item active">Tampil Data Rekap Keuangan Homecare</li>
            </ol>

            <div class="card mb-4 border-0 shadow-sm">
                <div class="card-body filter-wrapper">
                    <form id="filterForm">
                        <div class="row g-2 align-items-end">
                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_awal" class="form-label text-muted small fw-bold mb-1">Tanggal Awal</label>
                                <input type="date" id="tanggal_awal" name="tanggal_awal" class="form-control" value="<?= $tgl_awal ?>" required />
                            </div>
                            <div class="col-12 col-md-3 col-lg-2">
                                <label for="tanggal_akhir" class="form-label text-muted small fw-bold mb-1">Tanggal Akhir</label>
                                <input type="date" id="tanggal_akhir" name="tanggal_akhir" class="form-control" value="<?= $tgl_akhir ?>" required />
                            </div>
                            <div class="col-12 col-md-6 col-lg-8">
                                <div class="btn-group-custom mt-3 mt-md-0">
                                    <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="fas fa-search me-1"></i> Filter</button>
                                    <button type="button" id="downloadButton" class="btn btn-success px-4 shadow-sm" style="display: none;"><i class="fas fa-file-excel me-1"></i> Download Excel</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="row mb-4" id="grafikContainer" style="display: none;">
                <div class="col-md-12">
                    <div class="card shadow-sm border-0 border-top border-primary border-4">
                        <div class="card-header bg-white font-weight-bold pt-3 pb-2 d-flex justify-content-between align-items-center">
                            <div>
                                <i class="fas fa-chart-line me-1 text-primary"></i> Grafik Pendapatan Homecare
                            </div>
                            <button class="btn btn-sm btn-outline-primary" id="btnDownloadChart">
                                <i class="fas fa-image me-1"></i> Download Grafik (JPEG)
                            </button>
                        </div>
                        <div class="card-body bg-white">
                            <div style="position: relative; height: 350px; width: 100%; max-width:100%; background-color: #fff;">
                                <canvas id="keuanganChart" style="background-color: #fff;"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card border-0 shadow-sm mb-5">
                <div class="card-body p-2 p-md-3">
                    <div id="result">
                        <div id="loadingIcon" style="display: none;" class="py-5 text-center">
                            <img src="<?= base_url('assets_/assets/img/loading-new.gif') ?>" alt="Loading..." style="width: 50px;" />
                            <p class="mt-2 text-muted small fw-bold">Mengambil Data...</p>
                        </div>
                        <div id="tableContainer" style="display: none;">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </main>

    <footer class="py-4 bg-light mt-auto border-top">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small text-muted">
                <div>Copyright &copy; IT RSU Ananda Purwokerto 2024</div>
            </div>
        </div>
    </footer>
</div>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    Chart.register(ChartDataLabels);
    let chartKeuangan = null;

    // =========================================================
    // FUNGSI RENDER GRAFIK KEUANGAN
    // =========================================================
    function renderGrafikKeuangan(labels, dataTagihan) {
        const ctx = document.getElementById('keuanganChart');
        if (!ctx) return;

        if (chartKeuangan) {
            chartKeuangan.destroy();
        }

        chartKeuangan = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Total Pendapatan (Rp)',
                    data: dataTagihan,
                    backgroundColor: '#0d6efd', // Warna biru bootstrap
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                let value = context.parsed.y || 0;
                                return label + ': Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    },
                    datalabels: {
                        color: '#444',
                        anchor: 'end',
                        align: 'top',
                        offset: 4,
                        font: {
                            weight: 'bold',
                            size: 11
                        },
                        formatter: (value, ctx) => {
                            if (value > 0) {
                                // Format angka jadi format ribuan agar rapi
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                            return '';
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grace: '15%',
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    }
                }
            }
        });
    }

    $(document).ready(function() {
        $('#filterForm').on('submit', function(event) {
            event.preventDefault();
            $('#loadingIcon').show();
            $('#tableContainer').hide();
            $('#grafikContainer').hide();

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

            // ===============================================================
            // AJAX TUNGGAL UNTUK MENGAMBIL DATA TABEL DAN GRAFIK
            // ===============================================================
            $.ajax({
                url: '<?= base_url("rekaphomecare/tampildatarekap") ?>',
                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)) {
                            const list = data.response;

                            // 1. PROSES TABEL
                            if ($.fn.DataTable.isDataTable('#datatablesSimple')) {
                                $('#datatablesSimple').DataTable().destroy();
                            }

                            if (list.length > 0) {
                                let html = `
                                <div class="table-responsive w-100">
                                    <table id="datatablesSimple" class="table table-striped table-hover table-bordered text-nowrap w-100">
                                        <thead class="table-dark text-center">
                                            <tr>
                                                <th>Nama Bulan</th>
                                                <th>Tahun</th>
                                                <th>Jumlah Pasien</th>
                                                <th>Total Tagihan</th>
                                            </tr>
                                        </thead>
                                    <tbody>`;

                                // Array untuk menampung data Grafik
                                let arrLabels = [];
                                let arrDataTagihan = [];

                                list.forEach(item => {
                                    // Membuat Table Row
                                    html += `<tr>
                                        <td class="fw-bold">${item.bulan}</td>
                                        <td class="text-center">${item.tahun}</td>
                                        <td class="text-center">${item.jumlah_pasien}</td>
                                        <td class="text-end fw-bold text-success">${item.total_tagihan}</td>
                                    </tr>`;

                                    // Mempersiapkan Data Grafik
                                    // Cek apakah item.bulan tidak kosong, jika kosong gunakan default
                                    if (item.bulan && item.tahun) {
                                        arrLabels.push(item.bulan + ' ' + item.tahun);

                                        // Membersihkan format "Rp. 5.000" menjadi angka 5000 agar bisa dibaca grafik
                                        let rawTagihan = item.total_tagihan ? item.total_tagihan.toString().replace(/[^0-9]/g, '') : 0;
                                        arrDataTagihan.push(parseFloat(rawTagihan));
                                    }
                                });
                                html += '</tbody></table></div>';

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

                                // INISIALISASI DATATABLES
                                $('#datatablesSimple').DataTable({
                                    responsive: false,
                                    scrollX: false,
                                    autoWidth: false,
                                    order: [
                                        [1, "asc"]
                                    ],
                                    dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                                        '<"row"<"col-sm-12"tr>>' +
                                        '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                                    language: {
                                        search: "Cari Data:",
                                        lengthMenu: "Tampil _MENU_"
                                    }
                                });

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

                                // 2. PROSES RENDER GRAFIK JIKA DATA TERSEDIA
                                if (arrLabels.length > 0) {
                                    $('#grafikContainer').show();
                                    renderGrafikKeuangan(arrLabels, arrDataTagihan);
                                }

                            } else {
                                $('#tableContainer').html('<div class="alert alert-info text-center m-3 small"><i class="fas fa-info-circle me-1"></i> Tidak ada data yang ditemukan.</div>').show();
                                $('#downloadButton').hide();
                            }
                        } else {
                            $('#tableContainer').html('<div class="alert alert-warning text-center m-3 small">Respons data kosong atau format salah.</div>').show();
                            $('#downloadButton').hide();
                        }

                    } catch (e) {
                        console.error("Error parsing JSON: ", e);
                        $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small">Terjadi kesalahan format data dari server.</div>').show();
                        $('#downloadButton').hide();
                    }
                },
                error: function(xhr, status, error) {
                    $('#loadingIcon').hide();
                    console.error("AJAX Error: ", error);
                    $('#tableContainer').html('<div class="alert alert-danger text-center m-3 small"><i class="fas fa-exclamation-triangle me-1"></i> Gagal terhubung ke server. Silakan coba lagi.</div>').show();
                }
            });
        });

        // Event untuk tombol download EXCEL
        $('#downloadButton').on('click', function() {
            const tanggalAwal = $('#tanggal_awal').val();
            const tanggalAkhir = $('#tanggal_akhir').val();
            window.location.href = `<?= base_url("rekaphomecare/unduhdatarekap") ?>?TANGGAL_AWAL=${tanggalAwal}&TANGGAL_AKHIR=${tanggalAkhir}`;
        });

        // Event untuk tombol download GRAFIK (PNG)
        $('#btnDownloadChart').on('click', function(e) {
            e.preventDefault();
            // Ambil element canvas
            const canvas = document.getElementById("keuanganChart");
            if (canvas) {
                // Buat link download
                const imageURL = canvas.toDataURL("image/jpeg");
                const link = document.createElement("a");
                link.download = "Grafik_Pendapatan_Homecare.jpeg";
                link.href = imageURL;
                link.click();
            } else {
                alert("Grafik belum siap diunduh.");
            }
        });
    });
</script>