<?php

defined('BASEPATH') or exit('No direct script access allowed');



class Rekapkeutahunan extends CI_Controller

{
    public function tampildatarekapkeurajal() // Nama fungsi sesuai URL di JavaScript
    {
        if ($this->input->post('TANGGAL_AWAL')) {

            $tahun_input = $this->input->post('TANGGAL_AWAL'); // Dapat angka misal: 2024

            $tanggal_kirim = $tahun_input;

            // URL API Rajal
            $url_api = 'https://103.255.241.146/api/service_rs/rekap_sirus_asuransi_rajal';


            echo $this->_kirim_permintaan_api($url_api, $tanggal_kirim);
        }
    }

    public function tampildatarekapkeuranap() // Nama fungsi sesuai URL di JavaScript
    {
        if ($this->input->post('TANGGAL_AWAL')) {

            $tahun_input = $this->input->post('TANGGAL_AWAL');

            $tanggal_kirim = $tahun_input;

            // URL API Ranap
            $url_api = 'https://103.255.241.146/api/service_rs/rekap_sirus_asuransi_inap';

            echo $this->_kirim_permintaan_api($url_api, $tanggal_kirim);
        }
    }

    private function _kirim_permintaan_api($url, $tanggal)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL' => $tanggal,
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            return json_encode(['error' => "cURL Error: " . $err]);
        } else {

            return $response;
        }
    }


    public function unduhrekapkeu_tahunan_rajal()

    {
        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        // Ubah format tanggal jika diperlukan
        $tahun_input = $this->input->get('TANGGAL_AWAL'); // Dapat angka misal: 2024

        // Validasi jika tahun kosong (mencegah error API)
        if (empty($tahun_input)) {
            $tahun_input = date('Y');
        }

        // [PERBAIKAN 2] Tambahkan http:// pada URL
        $url_api = 'http://103.255.241.146/api/service_rs/rekap_sirus_asuransi_rajal';



        // Memanggil API menggunakan cURL

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url_api,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL' => $tahun_input,

            ),

        ));


        $response = curl_exec($curl);
        curl_close($curl);

        //log harian download
        $datai = [

            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download Data Rekap KEU Tahunan Rajal."

        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $datai,

        ]);

        $responsee = curl_exec($curl);
        curl_close($curl);

        if ($response) {
            $data = json_decode($response, true)['response'];
            // Load library PhpSpreadsheet

            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';
            // Load library PhpSpreadsheet

            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // Set header kolom

            $sheet->setCellValue('A1', 'Bulan');
            $sheet->setCellValue('B1', 'Nama Asuransi'); // **Tambahkan kelas hanya jika Rawat Inap**
            $sheet->setCellValue('C1', 'Jumlah');
            $row = 2;

            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['bulan']);
                $sheet->setCellValue('B' . $row, $item['nama_asuransi']);
                $sheet->setCellValue('C' . $row, $item['qty']);
                $row++;
            }

            if (ob_get_contents()) ob_end_clean();
            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="rekap_keu_tahunan_rajal.xlsx"');
            header('Cache-Control: max-age=0');
            header('Expires: 0');
            header('Pragma: public');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {

            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }


    public function unduhrekapkeu_tahunan_ranap()

    {
        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        // Ubah format tanggal jika diperlukan
        $tahun_input = $this->input->get('TANGGAL_AWAL'); // Dapat angka misal: 2024


        // Validasi jika tahun kosong (mencegah error API)
        if (empty($tahun_input)) {
            $tahun_input = date('Y');
        }

        $url_api_inap = 'http://103.255.241.146/api/service_rs/rekap_sirus_asuransi_inap';



        // Memanggil API menggunakan cURL

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url_api_inap,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL' => $tahun_input,

            ),

        ));


        $response = curl_exec($curl);
        curl_close($curl);

        //log harian download
        $datai = [

            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download Data Rekap KEU Tahunan Ranap."

        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $datai,

        ]);

        $responsee = curl_exec($curl);
        curl_close($curl);

        if ($response) {
            $data = json_decode($response, true)['response'];
            // Load library PhpSpreadsheet

            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';
            // Load library PhpSpreadsheet

            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // Set header kolom

            $sheet->setCellValue('A1', 'Bulan');
            $sheet->setCellValue('B1', 'Nama Asuransi'); // **Tambahkan kelas hanya jika Rawat Inap**
            $sheet->setCellValue('C1', 'Jumlah');
            $sheet->setCellValue('D1', 'Tarif');
            $row = 2;

            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['bulan']);
                $sheet->setCellValue('B' . $row, $item['nama_asuransi']);
                $sheet->setCellValue('C' . $row, $item['qty']);
                $sheet->setCellValue('D' . $row, $item['tarif']);
                $row++;
            }

            if (ob_get_contents()) ob_end_clean();
            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="rekap_keu_tahunan_ranap.xlsx"');
            header('Cache-Control: max-age=0');
            header('Expires: 0');
            header('Pragma: public');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {

            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }

    // =========================================================================
    // 1. FUNGSI TAMPILKAN DATA TABEL DETAIL TAGIHAN
    // =========================================================================
    public function tampildetailtagihbpjs()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AKHIR']) && isset($_POST['KD_PEMBAYARAN']) && isset($_POST['KD_JENIS_PASIEN'])) {
            $tanggalawal   = $_POST['TANGGAL_AWAL'];
            $tanggalakhir  = $_POST['TANGGAL_AKHIR'];
            $kdjenispasien = $_POST['KD_JENIS_PASIEN'];
            $kdpembayaran  = $_POST['KD_PEMBAYARAN'];

            $api_awal  = date('d/m/Y', strtotime($tanggalawal));
            $api_akhir = date('d/m/Y', strtotime($tanggalakhir));

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_rekap_tagihan',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 60,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => array(
                    'TANGGAL_AWAL'    => $api_awal,
                    'TANGGAL_AKHIR'   => $api_akhir,
                    'KD_PEMBAYARAN'   => $kdpembayaran,
                    'KD_JENIS_PASIEN' => $kdjenispasien
                ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);

            $all_data = [];
            if ($response) {
                $parsed = json_decode($response, true);
                if (json_last_error() === JSON_ERROR_NONE && isset($parsed['response']) && is_array($parsed['response'])) {
                    $all_data = $parsed['response'];
                }
            }

            if (!empty($all_data)) {
                $numeric_cols = [
                    'jumlah_pasien',
                    'jumlah_pasien_ada_inacbg',
                    'total_tagihan',
                    'total_tagihan_pribadi',
                    'total_tagihan_penjamin',
                    'total_tarif_inacbg'
                ];

                $grouped = [];
                foreach ($all_data as $row) {
                    $raw_dpjp = isset($row['dpjp']) ? $row['dpjp'] : 'Tidak Diketahui';
                    $key = strtoupper(trim(preg_replace('/\s+/u', ' ', $raw_dpjp)));

                    if (!isset($grouped[$key])) {
                        $grouped[$key] = ['dpjp' => trim(preg_replace('/\s+/u', ' ', $raw_dpjp))];
                        foreach ($numeric_cols as $col) {
                            $grouped[$key][$col] = 0;
                        }
                    }

                    foreach ($numeric_cols as $col) {
                        $val = isset($row[$col]) ? $row[$col] : 0;
                        $grouped[$key][$col] += is_numeric($val) ? (float)$val : 0;
                    }
                }
                // === PERBAIKAN: Ubah 'tampil' menjadi 'response' ===
                echo json_encode(['response' => array_values($grouped)]);
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
            }
        }
    }


    // =========================================================================
    // 2. FUNGSI DOWNLOAD EXCEL DETAIL TAGIHAN
    // =========================================================================
    public function unduhdetailtagihbpjs()
    {
        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');
        $tanggal_awal  = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');
        $kdjenispasien = $this->input->get('KD_JENIS_PASIEN');
        $kdpembayaran  = $this->input->get('KD_PEMBAYARAN');

        $tanggal_awali = date('d/m/Y', strtotime($tanggal_awal));
        $tanggal_akhiri = date('d/m/Y', strtotime($tanggal_akhir));

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_rekap_tagihan',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL'    => $tanggal_awali,
                'TANGGAL_AKHIR'   => $tanggal_akhiri,
                'KD_PEMBAYARAN'   => $kdpembayaran,
                'KD_JENIS_PASIEN' => $kdjenispasien
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);

        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download Data Detail Tagihan Pasien BPJS-UMUM."
        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 3,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $datai,
        ]);
        curl_exec($curl);
        curl_close($curl);

        if ($response) {
            $parsed = json_decode($response, true);
            // === PERBAIKAN: Ubah 'tampil' menjadi 'response' ===
            $data = isset($parsed['response']) ? $parsed['response'] : [];

            error_reporting(E_ERROR | E_PARSE);
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            $sheet->setCellValue('A1', 'DPJP');
            $sheet->setCellValue('B1', 'Jumlah Pasien');
            $sheet->setCellValue('C1', 'Jumlah Pasien Ada INACBG');
            $sheet->setCellValue('D1', 'Total Tagihan');
            $sheet->setCellValue('E1', 'Total Tagihan Pribadi');
            $sheet->setCellValue('F1', 'Total Tagihan Penjamin');
            $sheet->setCellValue('G1', 'Total Tarif INACBG');

            $row = 2;
            if (!empty($data) && is_array($data)) {
                $numeric_cols = [
                    'jumlah_pasien',
                    'jumlah_pasien_ada_inacbg',
                    'total_tagihan',
                    'total_tagihan_pribadi',
                    'total_tagihan_penjamin',
                    'total_tarif_inacbg'
                ];

                $grouped = [];
                foreach ($data as $item) {
                    $raw_dpjp = isset($item['dpjp']) ? $item['dpjp'] : 'Tidak Diketahui';
                    $key = strtoupper(trim(preg_replace('/\s+/u', ' ', $raw_dpjp)));

                    if (!isset($grouped[$key])) {
                        $grouped[$key] = ['dpjp' => trim(preg_replace('/\s+/u', ' ', $raw_dpjp))];
                        foreach ($numeric_cols as $col) {
                            $grouped[$key][$col] = 0;
                        }
                    }
                    foreach ($numeric_cols as $col) {
                        $val = isset($item[$col]) ? $item[$col] : 0;
                        $grouped[$key][$col] += is_numeric($val) ? (float)$val : 0;
                    }
                }

                foreach ($grouped as $item) {
                    $sheet->setCellValue('A' . $row, $item['dpjp']);
                    $sheet->setCellValue('B' . $row, $item['jumlah_pasien']);
                    $sheet->setCellValue('C' . $row, $item['jumlah_pasien_ada_inacbg']);
                    $sheet->setCellValue('D' . $row, $item['total_tagihan']);
                    $sheet->setCellValue('E' . $row, $item['total_tagihan_pribadi']);
                    $sheet->setCellValue('F' . $row, $item['total_tagihan_penjamin']);
                    $sheet->setCellValue('G' . $row, $item['total_tarif_inacbg']);
                    $row++;
                }
            }

            if (ob_get_length()) {
                ob_end_clean();
            }

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="DATA_DETAIL_TAGIHAN.xlsx"');
            header('Cache-Control: max-age=0');

            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        }
    }

    public function datadetailtagih_asuransi()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AWAL']) && isset($_POST['KD_JENIS_PASIEN'])) {
            // Mengambil input tanggal dari form
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];
            $kdjenispasien = $_POST['KD_JENIS_PASIEN'];

            // Mengonversi format tanggal ke dd/mm/yyyy
            $tanggal_awal = date('d/m/Y', strtotime($tanggalawal));
            $tanggal_akhir = date('d/m/Y', strtotime($tanggalakhir));

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_rekap_tagihan_asuransi',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => array(
                    'TANGGAL_AWAL' => $tanggal_awal,
                    'TANGGAL_AKHIR' => $tanggal_akhir,
                    'KD_JENIS_PASIEN' => $kdjenispasien
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }

    public function unduhdetailtagih_asuransi()
    {
        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');
        $tanggal_awal  = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');
        $kdjenispasien = $this->input->get('KD_JENIS_PASIEN');


        // Ubah format tanggal jika diperlukan
        $tanggal_awali = date('d/m/Y', strtotime($tanggal_awal));
        $tanggal_akhiri = date('d/m/Y', strtotime($tanggal_akhir));

        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_rekap_tagihan_asuransi',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL' => $tanggal_awali,
                'TANGGAL_AKHIR' => $tanggal_akhiri,
                'KD_JENIS_PASIEN' => $kdjenispasien
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download Data Detail Tagihan Pasien Asuransi."
        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 3,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $datai,
        ]);
        curl_exec($curl);
        curl_close($curl);

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Sembunyikan notice PHP 8.1 dari PhpSpreadsheet agar tidak mengganggu output header
            error_reporting(E_ERROR | E_PARSE);

            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'DPJP');
            $sheet->setCellValue('B1', 'Jumlah Pasien');
            $sheet->setCellValue('C1', 'Jumlah Pasien INACBG');
            $sheet->setCellValue('D1', 'Total Tagihan');
            $sheet->setCellValue('E1', 'Total Tagihan Pribadi');
            $sheet->setCellValue('F1', 'Total Tagihan Penjamin');
            $sheet->setCellValue('G1', 'Total Tarif INACBG');
            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['dpjp']);
                $sheet->setCellValue('B' . $row, $item['jumlah_pasien']);
                $sheet->setCellValue('C' . $row, $item['jumlah_pasien_ada_inacbg']);
                $sheet->setCellValue('D' . $row, $item['total_tagihan']);
                $sheet->setCellValue('E' . $row, $item['total_tagihan_pribadi']);
                $sheet->setCellValue('F' . $row, $item['total_tagihan_penjamin']);
                $sheet->setCellValue('G' . $row, $item['total_tarif_inacbg']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="DATAKEU_DETAIL_TAGIHAN_ASURANSI.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }
}
