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

class Datarawatjalan extends CI_Controller
{


    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     *	- or -
     * 		http://example.com/index.php/welcome/index
     *	- or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/userguide3/general/urls.html
     */
    public function filter_datarajal()
    {
        if (!$this->session->userdata('berhasil_loginu')) {
            redirect(''); // Jika tidak login, redirect ke halaman login
        }

        $akses = $this->session->userdata("kd_akses");
        $app = $this->session->userdata("kd_app");

        // 1. PERBAIKAN: Ambil POST dengan aman dan beri default hari ini
        $post_awal = $this->input->post('tanggal_awal');
        $post_akhir = $this->input->post('tanggal_akhir');

        $tgl_awal = !empty($post_awal) ? $post_awal : date('Y-m-d');
        $tgl_akhir = !empty($post_akhir) ? $post_akhir : date('Y-m-d');

        // Format tanggal sesuai kebutuhan API
        $tanggal_awal = date('d/m/Y', strtotime($tgl_awal));
        $tanggal_akhir = date('d/m/Y', strtotime($tgl_akhir));

        // 2. PERBAIKAN: Pastikan Semuanya masuk ke dalam $datai
        $datai["TANGGAL_AWAL"] = $tanggal_awal;
        $datai["TANGGAL_AKHIR"] = $tanggal_akhir;

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_poli_lama_baru',
            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
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $jsona =  str_replace('\r\n     ', "---0", $response);
        $jsona =  str_replace('\r\n', "---", $jsona);
        $jsona = json_decode($jsona);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/d_reg_online/tampil_pasien_smf_sum',
            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
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $jsonb =  str_replace('\r\n     ', "---0", $response);
        $jsonb =  str_replace('\r\n', "---", $jsonb);
        $jsonb = json_decode($jsonb);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/d_reg_online/tampil_pasien_smf',
            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
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $jsonc =  str_replace('\r\n     ', "---0", $response);
        $jsonc =  str_replace('\r\n', "---", $jsonc);
        $jsonc = json_decode($jsonc);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/poli_per_jam', // Sesuai dengan route API Anda
            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
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $jsonpjm =  str_replace('\r\n     ', "---0", $response);
        $jsonpjm =  str_replace('\r\n', "---", $jsonpjm);
        $jsonpjm = json_decode($jsonpjm);

        $data["ratapoliperjam"]         = $jsonpjm;
        $data["pasienpolilamabaru"]     = $jsona;
        $data["pasienrajaltotal"]       = $jsonb;
        $data["tampilpasienrajal"]      = $jsonc;
        $data["akses"]                  = $akses;
        $data["app"]                    = $app;

        // 3. PERBAIKAN: Kirim kedua tanggal kembali ke view agar form tidak error
        $data["tgl_awal"]               = $tgl_awal;
        $data["tgl_akhir"]              = $tgl_akhir;

        $this->load->view('dashboard/header', $data);
        $this->load->view('dashboard/pasiensmfpoli', $data);
    }

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

            // 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/pasien_homecare',
                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
                ),
            ));

            $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 download()
    {

        $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');

        // 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/pasien_homecare',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasien RAJAL HOMECARE."

        ];
        $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', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Tanggal Registrasi');
            $sheet->setCellValue('C1', 'Nama Pasien');
            $sheet->setCellValue('D1', 'Alamat');
            $sheet->setCellValue('E1', 'Nama Dokter');
            $sheet->setCellValue('F1', 'Nama Poli');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('B' . $row, $item['tgl_registrasi']);
                $sheet->setCellValue('C' . $row, $item['nm_pasien']);
                $sheet->setCellValue('D' . $row, $item['alamat']);
                $sheet->setCellValue('E' . $row, $item['nm_dokter']);
                $sheet->setCellValue('F' . $row, $item['nm_poliklinik']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_rawatjalan_homecare.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.']);
        }
    }

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

            // 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/poli_all',
                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
                ),
            ));

            $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 downloadrajaltotal()
    {

    ini_set('memory_limit', '1024M'); // Menaikkan limit memori PHP menjadi 1 GB
    ini_set('max_execution_time', 300); // Memberikan waktu proses hingga 5 menit (300 detik)

        $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');

        // 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/poli_all',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasieb Rajal Total."

        ];
        $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'];

            $statusperiksaMap=[
                '0' => 'PEMESANAN',
                '1' => 'MENUNGGU',
                '2' => 'SEDANG PEMERIKSAAN',
                '3' => 'SELESAI PEMERIKSAAN',
                'X' => 'BATAL'
            ];
            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

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

            // Set header kolom
            $sheet->setCellValue('A1', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Kode RM');
            $sheet->setCellValue('C1', 'Kode Pendaftarn');
            $sheet->setCellValue('D1', 'Kode Cara Masuk');
            $sheet->setCellValue('E1', 'Kode Pembayaran');
            $sheet->setCellValue('F1', 'Tgl Regist');
            $sheet->setCellValue('G1', 'Jam Regist');
            $sheet->setCellValue('H1', 'Tgl Keluar');
            $sheet->setCellValue('I1', 'Jam Keluar');
            $sheet->setCellValue('J1', 'Kode Jenis Pasien');
            $sheet->setCellValue('K1', 'Kode Poli');
            $sheet->setCellValue('L1', 'NIP Dokter');
            $sheet->setCellValue('M1', 'Kode Ruang');
            $sheet->setCellValue('N1', 'Status Periksa');
            $sheet->setCellValue('O1', 'Total');
            $sheet->setCellValue('P1', 'Total Pribadi');
            $sheet->setCellValue('Q1', 'Total Penjamin');
            $sheet->setCellValue('R1', 'NIP Petugas');
            $sheet->setCellValue('S1', 'No Antri');
            $sheet->setCellValue('T1', 'Nama Pasien');
            $sheet->setCellValue('U1', 'Alamat');
            $sheet->setCellValue('V1', 'Kode Desa');
            $sheet->setCellValue('W1', 'Nama Pendaftaran');
            $sheet->setCellValue('X1', 'Cara Masuk');
            $sheet->setCellValue('Y1', 'Nama Pembayaran');
            $sheet->setCellValue('Z1', 'Nama Jenis Pasien');
            $sheet->setCellValue('AA1', 'Nama Poli');
            $sheet->setCellValue('AB1', 'Kode Ruang');
            $sheet->setCellValue('AC1', 'Nama Dokter');
            $sheet->setCellValue('AD1', 'Status');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('B' . $row, $item['kd_rekam_medis']);
                $sheet->setCellValue('C' . $row, $item['kd_pendaftaran']);
                $sheet->setCellValue('D' . $row, $item['kd_cara_masuk']);
                $sheet->setCellValue('E' . $row, $item['kd_pembayaran']);
                $sheet->setCellValue('F' . $row, $item['tgl_registrasi']);
                $sheet->setCellValue('G' . $row, $item['jam_registrasi']);
                $sheet->setCellValue('H' . $row, $item['tgl_keluar']);
                $sheet->setCellValue('I' . $row, $item['jam_keluar']);
                $sheet->setCellValue('J' . $row, $item['kd_jenis_pasien']);
                $sheet->setCellValue('K' . $row, $item['kd_poliklinik']);
                $sheet->setCellValue('L' . $row, $item['nip_dokter']);
                $sheet->setCellValue('M' . $row, $item['kd_ruang']);
                // status periksa
                $kdStatus = strtoupper((string)$item['kd_status_periksa']);
                $labelStatus = isset($statusperiksaMap[$kdStatus]) ? $statusperiksaMap[$kdStatus] : $item['nm_status_periksa'];
                $sheet->setCellValue('N' . $row, $labelStatus);
                // status periksa
                $sheet->setCellValue('O' . $row, $item['total']);
                $sheet->setCellValue('P' . $row, $item['total_pribadi']);
                $sheet->setCellValue('Q' . $row, $item['total_penjamin']);
                $sheet->setCellValue('R' . $row, $item['nip_petugas']);
                $sheet->setCellValue('S' . $row, $item['no_antri']);
                $sheet->setCellValue('T' . $row, $item['nm_pasien']);
                $sheet->setCellValue('U' . $row, $item['alamat']);
                $sheet->setCellValue('V' . $row, $item['kd_desa']);
                $sheet->setCellValue('W' . $row, $item['nm_pendaftaran']);
                $sheet->setCellValue('X' . $row, $item['nm_cara_masuk']);
                $sheet->setCellValue('Y' . $row, $item['nm_pembayaran']);
                $sheet->setCellValue('Z' . $row, $item['nm_jenis_pasien']);
                $sheet->setCellValue('AA' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('AB' . $row, $item['kd_grup_ruang']);
                $sheet->setCellValue('AC' . $row, $item['nm_dokter']);
                $sheet->setCellValue('AD' . $row, $item['nm_status_periksa']);
                $row++;
            }

            // 1. MATIKAN SEMUA WARNING & ERROR AGAR TIDAK MASUK KE EXCEL
            error_reporting(0); 

            // 2. BERSIHKAN BUFFER DARI "SAMPAH" SPASI ATAU TEKS SEBELUMNYA
            if (ob_get_length()) {
                ob_clean();
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_pasien_rajaltotal.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.']);
        }
    }

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

            // 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/poli_batal',
                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
                ),
            ));

            $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 tampildatapasienrajal()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AKHIR'])) {
            // Mengambil input tanggal dari form
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];

            // 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/d_reg_online/tampil_antrean_poliklinik',
                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
                ),
            ));

            $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 downloaddataantreanpoli()
    {

        $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');

        // 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/d_reg_online/tampil_antrean_poliklinik',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasien RAJAL Batal."

        ];
        $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', 'Nama Hari');
            $sheet->setCellValue('B1', 'Jadwal Poli');
            $sheet->setCellValue('C1', 'Nama Poliklinik');
            $sheet->setCellValue('D1', 'NIP Dokter');
            $sheet->setCellValue('E1', 'Nama Dokter');
            $sheet->setCellValue('F1', 'Jumlah Pasieb');
            $sheet->setCellValue('G1', 'Jumlah Daftar');
            $sheet->setCellValue('H1', 'Terlayani');
            $sheet->setCellValue('I1', 'Batal');
            $sheet->setCellValue('J1', 'Sisa Kuota');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['nm_hari']);
                $sheet->setCellValue('B' . $row, $item['jadwal_poli']);
                $sheet->setCellValue('C' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('D' . $row, $item['nip_dokter']);
                $sheet->setCellValue('E' . $row, $item['nm_dokter']);
                $sheet->setCellValue('F' . $row, $item['jumlah_pasien']);
                $sheet->setCellValue('G' . $row, $item['daftar']);
                $sheet->setCellValue('H' . $row, $item['terlayani']);
                $sheet->setCellValue('I' . $row, $item['batal']);
                $sheet->setCellValue('J' . $row, $item['sisa']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_antreanpoliklinik.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.']);
        }
    }

    public function downloadrajaltotalbatal()
    {

        $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');

        // 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/poli_batal',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasien RAJAL Batal."

        ];
        $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', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Kode RM');
            $sheet->setCellValue('C1', 'Kode Pendaftaran');
            $sheet->setCellValue('D1', 'Kode Cara Masuk');
            $sheet->setCellValue('E1', 'Kode Pembayaran');
            $sheet->setCellValue('F1', 'Tanggal Registrasi');
            $sheet->setCellValue('G1', 'Jam Registrasi');
            $sheet->setCellValue('H1', 'Tanggal Keluar');
            $sheet->setCellValue('I1', 'Jam Keluar');
            $sheet->setCellValue('J1', 'Kode Jenis Pasien');
            $sheet->setCellValue('K1', 'Kode Poli');
            $sheet->setCellValue('L1', 'NIP Dokter');
            $sheet->setCellValue('M1', 'Kode Ruang');
            $sheet->setCellValue('N1', 'Kode Status Periksa');
            $sheet->setCellValue('O1', 'Total');
            $sheet->setCellValue('P1', 'Total Pribadi');
            $sheet->setCellValue('Q1', 'Total Penjamin');
            $sheet->setCellValue('R1', 'NIP Petugas');
            $sheet->setCellValue('S1', 'No Antrian');
            $sheet->setCellValue('T1', 'Nama Pasien');
            $sheet->setCellValue('U1', 'Alamat');
            $sheet->setCellValue('V1', 'Kode Desa');
            $sheet->setCellValue('W1', 'Nama Pendaftaran');
            $sheet->setCellValue('X1', 'Cara Masuk');
            $sheet->setCellValue('Y1', 'Nama Pembayaran');
            $sheet->setCellValue('Z1', 'Nama Jenis Pasien');
            $sheet->setCellValue('AA1', 'Nama Poli');
            $sheet->setCellValue('AB1', 'Grup Ruang');
            $sheet->setCellValue('AC1', 'Nama Dokter');
            $sheet->setCellValue('AD1', 'Status Periksa');
            $sheet->setCellValue('AE1', 'Tanggal Batal');
            $sheet->setCellValue('AF1', 'Kode Alasan');
            $sheet->setCellValue('AG1', 'Nama Alasan');
            $sheet->setCellValue('AH1', 'Keterangan');
            $sheet->setCellValue('AI1', 'Catatan');
            $sheet->setCellValue('AJ1', 'NIP Insert');
            $sheet->setCellValue('AK1', 'NIP Update');
            $sheet->setCellValue('AL1', 'Tanggal Insert');
            $sheet->setCellValue('AM1', 'Tanggal Update');



            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('B' . $row, $item['kd_rekam_medis']);
                $sheet->setCellValue('C' . $row, $item['kd_pendaftaran']);
                $sheet->setCellValue('D' . $row, $item['kd_cara_masuk']);
                $sheet->setCellValue('E' . $row, $item['kd_pembayaran']);
                $sheet->setCellValue('F' . $row, $item['tgl_registrasi']);
                $sheet->setCellValue('G' . $row, $item['jam_registrasi']);
                $sheet->setCellValue('H' . $row, $item['tgl_keluar']);
                $sheet->setCellValue('I' . $row, $item['jam_keluar']);
                $sheet->setCellValue('J' . $row, $item['kd_jenis_pasien']);
                $sheet->setCellValue('K' . $row, $item['kd_poliklinik']);
                $sheet->setCellValue('L' . $row, $item['nip_dokter']);
                $sheet->setCellValue('M' . $row, $item['kd_ruang']);
                $sheet->setCellValue('N' . $row, $item['kd_status_periksa']);
                $sheet->setCellValue('O' . $row, $item['total']);
                $sheet->setCellValue('P' . $row, $item['total_pribadi']);
                $sheet->setCellValue('Q' . $row, $item['total_penjamin']);
                $sheet->setCellValue('R' . $row, $item['nip_petugas']);
                $sheet->setCellValue('S' . $row, $item['no_antri']);
                $sheet->setCellValue('T' . $row, $item['nm_pasien']);
                $sheet->setCellValue('U' . $row, $item['alamat']);
                $sheet->setCellValue('V' . $row, $item['kd_desa']);
                $sheet->setCellValue('W' . $row, $item['nm_pendaftaran']);
                $sheet->setCellValue('X' . $row, $item['nm_cara_masuk']);
                $sheet->setCellValue('Y' . $row, $item['nm_pembayaran']);
                $sheet->setCellValue('Z' . $row, $item['nm_jenis_pasien']);
                $sheet->setCellValue('AA' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('AB' . $row, $item['kd_grup_ruang']);
                $sheet->setCellValue('AC' . $row, $item['nm_dokter']);
                $sheet->setCellValue('AD' . $row, $item['nm_status_periksa']);
                $sheet->setCellValue('AE' . $row, $item['tgl_batal']);
                $sheet->setCellValue('AF' . $row, $item['kd_alasan']);
                $sheet->setCellValue('AG' . $row, $item['nm_alasan']);
                $sheet->setCellValue('AH' . $row, $item['keterangan']);
                $sheet->setCellValue('AI' . $row, $item['catatan']);
                $sheet->setCellValue('AJ' . $row, $item['nip_insert']);
                $sheet->setCellValue('AK' . $row, $item['nip_update']);
                $sheet->setCellValue('AL' . $row, $item['tgl_insert']);
                $sheet->setCellValue('AM' . $row, $item['tgl_update']);


                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_pasien_rajalbatal.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.']);
        }
    }

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

            // 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/poli_dilayani',
                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
                ),
            ));

            $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 downloadrajaldilayani()
    {
        // KUNCI UTAMA: Alokasikan memori & waktu eksekusi lebih tinggi secara dinamis hanya untuk fungsi ini
        ini_set('memory_limit', '1024M'); // Naikkan sementara ke 1 GB khusus ekspor data besar
        set_time_limit(300);             // Berikan batas waktu eksekusi hingga 5 menit agar tidak timeout

        $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');

        $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/poli_dilayani',
            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
            ),
        ));

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

        // log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasien RAJAL Dilayani ."
        ];
        $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) {
            $res_json = json_decode($response, true);
            $data = isset($res_json['response']) ? $res_json['response'] : null;

            if (empty($data) || !is_array($data)) {
                echo "Tidak ada data untuk rentang tanggal tersebut.";
                exit();
            }

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

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

            // Set header kolom
            $sheet->setCellValue('A1', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Kode RM');
            $sheet->setCellValue('C1', 'Nama Pendaftaran');
            $sheet->setCellValue('D1', 'Cara Masuk');
            $sheet->setCellValue('E1', 'Nama Pembayaran');
            $sheet->setCellValue('F1', 'Tgl Regist');
            $sheet->setCellValue('G1', 'Jam Regist');
            $sheet->setCellValue('H1', 'Tgl Keluar');
            $sheet->setCellValue('I1', 'Jam Keluar');
            $sheet->setCellValue('J1', 'Kode Jenis Pasien');
            $sheet->setCellValue('K1', 'Kode Poli');
            $sheet->setCellValue('L1', 'NIP Dokter');
            $sheet->setCellValue('M1', 'Kode Ruang');
            $sheet->setCellValue('N1', 'Kode Status');
            $sheet->setCellValue('O1', 'Total');
            $sheet->setCellValue('P1', 'Total Pribadi');
            $sheet->setCellValue('Q1', 'Total Penjamin');
            $sheet->setCellValue('R1', 'NIP Petugas');
            $sheet->setCellValue('S1', 'No Antri');
            $sheet->setCellValue('T1', 'Nama Pasien');
            $sheet->setCellValue('U1', 'Kode Desa');
            $sheet->setCellValue('V1', 'Nama Pendaftaran');
            $sheet->setCellValue('W1', 'Cara Masuk');
            $sheet->setCellValue('X1', 'Nama Pembayaran');
            $sheet->setCellValue('Y1', 'Nama Jenis Pasien');
            $sheet->setCellValue('Z1', 'Nama Poli');
            $sheet->setCellValue('AA1', 'Kode Ruang');
            $sheet->setCellValue('AB1', 'Nama Dokter');
            $sheet->setCellValue('AC1', 'Status');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_registrasi'] ?? '');
                $sheet->setCellValue('B' . $row, $item['kd_rekam_medis'] ?? '');
                $sheet->setCellValue('C' . $row, $item['nm_pendaftaran'] ?? '');
                $sheet->setCellValue('D' . $row, $item['nm_cara_masuk'] ?? '');
                $sheet->setCellValue('E' . $row, $item['nm_pembayaran'] ?? '');
                $sheet->setCellValue('F' . $row, $item['tgl_registrasi'] ?? '');
                $sheet->setCellValue('G' . $row, $item['jam_registrasi'] ?? '');
                $sheet->setCellValue('H' . $row, $item['tgl_keluar'] ?? '');
                $sheet->setCellValue('I' . $row, $item['jam_keluar'] ?? '');
                $sheet->setCellValue('J' . $row, $item['kd_jenis_pasien'] ?? '');
                $sheet->setCellValue('K' . $row, $item['kd_poliklinik'] ?? '');
                $sheet->setCellValue('L' . $row, $item['nip_dokter'] ?? '');
                $sheet->setCellValue('M' . $row, $item['kd_ruang'] ?? '');
                $sheet->setCellValue('N' . $row, $item['kd_status_periksa'] ?? '');
                $sheet->setCellValue('O' . $row, $item['total'] ?? '0');
                $sheet->setCellValue('P' . $row, $item['total_pribadi'] ?? '0');
                $sheet->setCellValue('Q' . $row, $item['total_penjamin'] ?? '0');
                $sheet->setCellValue('R' . $row, $item['nip_petugas'] ?? '');
                $sheet->setCellValue('S' . $row, $item['no_antri'] ?? '');
                $sheet->setCellValue('T' . $row, $item['nm_pasien'] ?? '');
                $sheet->setCellValue('U' . $row, $item['kd_desa'] ?? '');
                $sheet->setCellValue('V' . $row, $item['nm_pendaftaran'] ?? '');
                $sheet->setCellValue('W' . $row, $item['nm_cara_masuk'] ?? '');
                $sheet->setCellValue('X' . $row, $item['nm_pembayaran'] ?? '');
                $sheet->setCellValue('Y' . $row, $item['nm_jenis_pasien'] ?? '');
                $sheet->setCellValue('Z' . $row, $item['nm_poliklinik'] ?? '');
                $sheet->setCellValue('AA' . $row, $item['kd_grup_ruang'] ?? '');
                $sheet->setCellValue('AB' . $row, $item['nm_dokter'] ?? '');
                $sheet->setCellValue('AC' . $row, $item['nm_status_periksa'] ?? '');
                
                $row++;

                // MENGHINDARI MEMORY EXHAUSTED: Lepas memori variabel iterasi setiap 500 baris data
                if ($row % 500 === 0) {
                    gc_collect_cycles(); 
                }
            }

            // Membersihkan memori variabel API yang sudah tidak terpakai
            unset($response);
            unset($data);

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

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


    public function rmunduhrajaldilayani()
    {
        $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');

        // 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/poli_dilayani',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data RM Pasien RAJAL Dilayani ."

        ];
        $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', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Kode Rekam Medis');
            $sheet->setCellValue('C1', 'Tanggal Registrasi');
            $sheet->setCellValue('D1', 'Jam Registrasi');
            $sheet->setCellValue('E1', 'Tanggal Keluar');
            $sheet->setCellValue('F1', 'Jam Keluar');
            $sheet->setCellValue('G1', 'Kode Jenis Pasien');
            $sheet->setCellValue('H1', 'Kode Poliklinik');
            $sheet->setCellValue('I1', 'NIP Dokter');
            $sheet->setCellValue('J1', 'Kode Ruang');
            $sheet->setCellValue('K1', 'Kode Status Periksa');
            $sheet->setCellValue('L1', 'Total');
            $sheet->setCellValue('M1', 'Total Pribadi');
            $sheet->setCellValue('N1', 'Total Penjamin');
            $sheet->setCellValue('O1', 'NIP Petugas');
            $sheet->setCellValue('P1', 'No Antrian');
            $sheet->setCellValue('Q1', 'Nama Pasien');
            $sheet->setCellValue('R1', 'Kode Desa');
            $sheet->setCellValue('S1', 'Kode Pendaftaran');
            $sheet->setCellValue('T1', 'Kode Cara Masuk');
            $sheet->setCellValue('U1', 'Kode Pembayaran');
            $sheet->setCellValue('V1', 'Nama Pendaftaran');
            $sheet->setCellValue('W1', 'Nama Pembayaran');
            $sheet->setCellValue('X1', 'Jenis Pasien');
            $sheet->setCellValue('Y1', 'Nama Poliklinik');
            $sheet->setCellValue('Z1', 'Grup Ruang');
            $sheet->setCellValue('AA1', 'Nama Dokter');
            $sheet->setCellValue('AB1', 'Status Periksa');
            $sheet->setCellValue('AC1', 'Cara Masuk');
            $sheet->setCellValue('AD1', 'Alamat');
            $sheet->setCellValue('AE1', 'Umur Tahun');
            $sheet->setCellValue('AF1', 'Umur Bulan');
            $sheet->setCellValue('AG1', 'Jenis Kelamin');
            $sheet->setCellValue('AH1', 'Kota');
            $sheet->setCellValue('AI1', 'Kecamatan');
            $sheet->setCellValue('AJ1', 'Asal PPK');
            $sheet->setCellValue('AK1', 'Diagnosa Primer');
            $sheet->setCellValue('AL1', 'Diagnosa Sekunder');
            $sheet->setCellValue('AM1', 'Nama Penyakit Primer');
            $sheet->setCellValue('AN1', 'Nama Penyakit Sekunder');

            

            // Isi data
            $row = 2;
            foreach ($data as $item) {
            $sheet->setCellValue('A' . $row, $item['kd_registrasi'] ?? '');
            $sheet->setCellValue('B' . $row, $item['kd_rekam_medis'] ?? '');
            $sheet->setCellValue('C' . $row, $item['tgl_registrasi'] ?? '');
            $sheet->setCellValue('D' . $row, $item['jam_registrasi'] ?? '');
            $sheet->setCellValue('E' . $row, $item['tgl_keluar'] ?? '');
            $sheet->setCellValue('F' . $row, $item['jam_keluar'] ?? '');
            $sheet->setCellValue('G' . $row, $item['kd_jenis_pasien'] ?? '');
            $sheet->setCellValue('H' . $row, $item['kd_poliklinik'] ?? '');
            $sheet->setCellValue('I' . $row, $item['nip_dokter'] ?? '');
            $sheet->setCellValue('J' . $row, $item['kd_ruang'] ?? '');
            $sheet->setCellValue('K' . $row, $item['kd_status_periksa'] ?? '');
            $sheet->setCellValue('L' . $row, $item['total'] ?? '');
            $sheet->setCellValue('M' . $row, $item['total_pribadi'] ?? '');
            $sheet->setCellValue('N' . $row, $item['total_penjamin'] ?? '');
            $sheet->setCellValue('O' . $row, $item['nip_petugas'] ?? '');
            $sheet->setCellValue('P' . $row, $item['no_antri'] ?? '');
            $sheet->setCellValue('Q' . $row, $item['nm_pasien'] ?? '');
            $sheet->setCellValue('R' . $row, $item['kd_desa'] ?? '');
            $sheet->setCellValue('S' . $row, $item['kd_pendaftaran'] ?? '');
            $sheet->setCellValue('T' . $row, $item['kd_cara_masuk'] ?? '');
            $sheet->setCellValue('U' . $row, $item['kd_pembayaran'] ?? '');
            $sheet->setCellValue('V' . $row, $item['nm_pendaftaran'] ?? '');
            $sheet->setCellValue('W' . $row, $item['nm_pembayaran'] ?? '');
            $sheet->setCellValue('X' . $row, $item['nm_jenis_pasien'] ?? '');
            $sheet->setCellValue('Y' . $row, $item['nm_poliklinik'] ?? '');
            $sheet->setCellValue('Z' . $row, $item['kd_grup_ruang'] ?? '');
            $sheet->setCellValue('AA' . $row, $item['nm_dokter'] ?? '');
            $sheet->setCellValue('AB' . $row, $item['nm_status_periksa'] ?? '');
            $sheet->setCellValue('AC' . $row, $item['nm_cara_masuk'] ?? '');
            $sheet->setCellValue('AD' . $row, $item['alamat'] ?? '');
            $sheet->setCellValue('AE' . $row, $item['umur_tahun'] ?? '');
            $sheet->setCellValue('AF' . $row, $item['umur_bulan'] ?? '');
            $sheet->setCellValue('AG' . $row, $item['jenis_kelamin'] ?? '');
            $sheet->setCellValue('AH' . $row, $item['nm_kota'] ?? '');
            $sheet->setCellValue('AI' . $row, $item['nm_kec'] ?? '');
            $sheet->setCellValue('AJ' . $row, $item['ppk'] ?? '');
            $sheet->setCellValue('AK' . $row, $item['dx_primer'] ?? '');
            $sheet->setCellValue('AL' . $row, $item['dx_sekunder'] ?? '');
            $sheet->setCellValue('AM' . $row, $item['nm_penyakit_primer'] ?? '');
            $sheet->setCellValue('AN' . $row, $item['nm_penyakit_sekunder'] ?? '');
                        
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_RM_pasien_rajal_dilayani_detail.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.']);
        }
    }

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

            // 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/poli_to_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' => $tanggal_awal,
                    'TANGGAL_AKHIR' => $tanggal_akhir
                ),
            ));

            $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 downloadrajaltransfer()
    {
        $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');

        // 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/poli_to_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' => $tanggal_awali,
                'TANGGAL_AKHIR' => $tanggal_akhiri
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Pasien RAJAL Transfer."

        ];
        $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', 'Kode Registrasi');
            $sheet->setCellValue('B1', 'Kode RM');
            $sheet->setCellValue('C1', 'Kode Pendaftarn');
            $sheet->setCellValue('D1', 'Kode Cara Masuk');
            $sheet->setCellValue('E1', 'Kode Pembayaran');
            $sheet->setCellValue('F1', 'Tgl Regist');
            $sheet->setCellValue('G1', 'Jam Regist');
            $sheet->setCellValue('H1', 'Tgl Keluar');
            $sheet->setCellValue('I1', 'Jam Keluar');
            $sheet->setCellValue('J1', 'Kode Jenis Pasien');
            $sheet->setCellValue('K1', 'Kode Poli');
            $sheet->setCellValue('L1', 'NIP Dokter');
            $sheet->setCellValue('M1', 'Kode Ruang');
            $sheet->setCellValue('N1', 'Kode Status');
            $sheet->setCellValue('O1', 'Total');
            $sheet->setCellValue('P1', 'Total Pribadi');
            $sheet->setCellValue('Q1', 'Total Penjamin');
            $sheet->setCellValue('R1', 'NIP Petugas');
            $sheet->setCellValue('S1', 'No Antri');
            $sheet->setCellValue('T1', 'Nama Pasien');
            $sheet->setCellValue('U1', 'Alamat');
            $sheet->setCellValue('V1', 'Kode Desa');
            $sheet->setCellValue('W1', 'Nama Pendaftaran');
            $sheet->setCellValue('X1', 'Cara Masuk');
            $sheet->setCellValue('Y1', 'Nama Pembayaran');
            $sheet->setCellValue('Z1', 'Nama Jenis Pasien');
            $sheet->setCellValue('AA1', 'Nama Poli');
            $sheet->setCellValue('AB1', 'Kode Ruang');
            $sheet->setCellValue('AC1', 'Nama Dokter');
            $sheet->setCellValue('AD1', 'Status');
            $sheet->setCellValue('AE1', 'Asal PPK');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('B' . $row, $item['kd_rekam_medis']);
                $sheet->setCellValue('C' . $row, $item['kd_pendaftaran']);
                $sheet->setCellValue('D' . $row, $item['kd_cara_masuk']);
                $sheet->setCellValue('E' . $row, $item['kd_pembayaran']);
                $sheet->setCellValue('F' . $row, $item['tgl_registrasi']);
                $sheet->setCellValue('G' . $row, $item['jam_registrasi']);
                $sheet->setCellValue('H' . $row, $item['tgl_keluar']);
                $sheet->setCellValue('I' . $row, $item['jam_keluar']);
                $sheet->setCellValue('J' . $row, $item['kd_jenis_pasien']);
                $sheet->setCellValue('K' . $row, $item['kd_poliklinik']);
                $sheet->setCellValue('L' . $row, $item['nip_dokter']);
                $sheet->setCellValue('M' . $row, $item['kd_ruang']);
                $sheet->setCellValue('N' . $row, $item['kd_status_periksa']);
                $sheet->setCellValue('O' . $row, $item['total']);
                $sheet->setCellValue('P' . $row, $item['total_pribadi']);
                $sheet->setCellValue('Q' . $row, $item['total_penjamin']);
                $sheet->setCellValue('R' . $row, $item['nip_petugas']);
                $sheet->setCellValue('S' . $row, $item['no_antri']);
                $sheet->setCellValue('T' . $row, $item['nm_pasien']);
                $sheet->setCellValue('U' . $row, $item['alamat']);
                $sheet->setCellValue('V' . $row, $item['kd_desa']);
                $sheet->setCellValue('W' . $row, $item['nm_pendaftaran']);
                $sheet->setCellValue('X' . $row, $item['nm_cara_masuk']);
                $sheet->setCellValue('Y' . $row, $item['nm_pembayaran']);
                $sheet->setCellValue('Z' . $row, $item['nm_jenis_pasien']);
                $sheet->setCellValue('AA' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('AB' . $row, $item['kd_grup_ruang']);
                $sheet->setCellValue('AC' . $row, $item['nm_dokter']);
                $sheet->setCellValue('AD' . $row, $item['nm_status_periksa']);
                $sheet->setCellValue('AE' . $row, $item['asal_ppk']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_pasien_rajaltransfer.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.']);
        }
    }

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

            // 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/poli_batal',
                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
                ),
            ));

            $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 downloadantreanpoli()
    {
        $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');

        // 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/poli_all',
            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
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Antrean Poliklinik."

        ];
        $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', 'Hari');
            $sheet->setCellValue('B1', 'Jam Poli');
            $sheet->setCellValue('C1', 'Kode Poli BPJS');
            $sheet->setCellValue('D1', 'Kode Poli RS');
            $sheet->setCellValue('E1', 'Nama Poli');
            $sheet->setCellValue('F1', 'NIP Dokter');
            $sheet->setCellValue('G1', 'Nama Dokter');
            $sheet->setCellValue('H1', 'Jumlah Pasien');
            $sheet->setCellValue('I1', 'Daftar');
            $sheet->setCellValue('J1', 'Terlayani');
            $sheet->setCellValue('K1', 'Batal');
            $sheet->setCellValue('L1', 'Sisa');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['nm_hari']);
                $sheet->setCellValue('B' . $row, $item['jadwal_poli']);
                $sheet->setCellValue('C' . $row, $item['kd_poli_bpjs']);
                $sheet->setCellValue('D' . $row, $item['kd_poli_rs']);
                $sheet->setCellValue('E' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('F' . $row, $item['nip_dokter']);
                $sheet->setCellValue('G' . $row, $item['nm_dokter']);
                $sheet->setCellValue('H' . $row, $item['jumlah_pasien']);
                $sheet->setCellValue('I' . $row, $item['daftar']);
                $sheet->setCellValue('J' . $row, $item['terlayani']);
                $sheet->setCellValue('K' . $row, $item['batal']);
                $sheet->setCellValue('L' . $row, $item['sisa']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_antrean_poliklinik.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.']);
        }
    }
}
