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

class Rekammedis 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 datawaktutunggupoli()
    {
        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/waktu_tunggu_poli',
                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 downloadwaktutunggupoli()
    {

        $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/waktu_tunggu_poli',
            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 Waktu Tunggu Poli."

        ];
        $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', 'Kd Regist');
            $sheet->setCellValue('B1', 'Tgl Regist');
            $sheet->setCellValue('C1', 'Nama Jenis Pasien');
            $sheet->setCellValue('D1', 'Nama Poli');
            $sheet->setCellValue('E1', 'Waktu Cehckin');
            $sheet->setCellValue('F1', 'Waktu Panggil Dokter');
            $sheet->setCellValue('G1', 'Selisih');
            $sheet->setCellValue('H1', 'Tgl Tagihan');
            $sheet->setCellValue('I1', 'Nama Pembayaran');

            // 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_jenis_pasien']);
                $sheet->setCellValue('D' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('E' . $row, $item['waktu_cek_in']);
                $sheet->setCellValue('F' . $row, $item['waktu_panggil_dokter']);
                $sheet->setCellValue('G' . $row, $item['selisih']);
                $sheet->setCellValue('H' . $row, $item['tgl_tagihan']);
                $sheet->setCellValue('I' . $row, $item['nm_pembayaran']);
                $row++;
            }

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

        // Pastikan method request adalah POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            $nm_user = $this->session->userdata('nm_user');
            $kd_user = $this->session->userdata('kd_user');
            // Ambil data dari permintaan POST
            $kd_registrasi = isset($_POST['kd_registrasi']) ? trim($_POST['kd_registrasi']) : '';
            $no_sep = isset($_POST['no_sep']) ? trim($_POST['no_sep']) : '';

            // Periksa apakah KD_REGISTRASI dan NO_SEP tidak kosong
            if (!empty($kd_registrasi) && !empty($no_sep)) {
                // Inisialisasi cURL

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

                // Set parameter cURL
                curl_setopt_array($curl, array(
                    CURLOPT_URL => '103.255.241.146/api/d_reg_online/batal_sep', // Tambahkan protokol http://
                    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 => http_build_query(array(
                        'KD_REGISTRASI' => $kd_registrasi,
                        'NO_SEP' => $no_sep
                    )),
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/x-www-form-urlencoded'
                    ),
                ));

                // Eksekusi permintaan cURL dan ambil respons dari API
                $response = curl_exec($curl);
                $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

                // Periksa apakah ada error dalam eksekusi cURL
                if (curl_errno($curl)) {
                    $error_msg = curl_error($curl);
                    curl_close($curl);
                    echo json_encode(array('status' => false, 'message' => 'cURL Error: ' . $error_msg));
                    exit();
                }

                curl_close($curl);

                //log harian download
                $datai = [
                    "KD_REGISTRASI" => $kd_registrasi,
                    "NO_SEP" => $no_sep,
                    "NIP_PETUGAS" => $kd_user,
                    "CATATAN" => "Akun " . $nm_user . " Telah Menghapus SEP dengan NO SEP." . $no_sep
                ];
                $curl = curl_init();
                curl_setopt_array($curl, [
                    CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_batal_sep',
                    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);

                // Periksa kode respons dari API
                if ($httpCode == 200) {
                    // Decode respons API
                    $response_data = json_decode($response, true);

                    // Periksa apakah API memberikan status sukses
                    if (isset($response_data['status']) && $response_data['status'] === true) {
                        echo json_encode(array('status' => true, 'message' => 'Berhasil membatalkan SEP.'));
                    } else {
                        echo json_encode(array('status' => false, 'message' => 'Gagal membatalkan SEP.', 'data' => $response_data));
                    }
                } else {
                    echo json_encode(array('status' => false, 'message' => 'Error: Respons API tidak benar (' . $httpCode . ')', 'response' => $response));
                }
            } else {
                // Jika KD_REGISTRASI atau NO_SEP kosong, kirimkan pesan kesalahan
                echo json_encode(array('status' => false, 'message' => 'KD_REGISTRASI atau NO_SEP tidak valid.'));
            }
        } else {
            // Jika request method bukan POST
            echo json_encode(array('status' => false, 'message' => 'Invalid request method.'));
        }
    }

    public function datapasienmeninggal()
    {
        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/service_rs/pasien_meninggal',
                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 downloaddatapasienmeninggal()
    {

        $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_meninggal',
            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 Meninggal."

        ];
        $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', 'Kode Rekam Medis');
            $sheet->setCellValue('D1', 'Nama Pembayaran');
            $sheet->setCellValue('E1', 'Nama Pasien');
            $sheet->setCellValue('F1', 'No KTP');
            $sheet->setCellValue('G1', 'Alamat');
            $sheet->setCellValue('H1', 'Status Pulang');
            $sheet->setCellValue('I1', 'Jenis Pasien');
            $sheet->setCellValue('J1', 'Poliklinik');
            $sheet->setCellValue('K1', 'Diagnosa Klinis');
            $sheet->setCellValue('L1', 'Dokter');
            $sheet->setCellValue('M1', 'Diagnosa Primer');
            $sheet->setCellValue('N1', 'Diagnosa Sekunder');
            $sheet->setCellValue('O1', 'Jenis Kelamin');
            $sheet->setCellValue('P1', 'Usia');


            // 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['kd_rekam_medis']);
                $sheet->setCellValue('D' . $row, $item['nm_pembayaran']);
                $sheet->setCellValue('E' . $row, $item['nm_pasien']);
                $sheet->setCellValue('F' . $row, $item['no_ktp']);
                $sheet->setCellValue('G' . $row, $item['alamat']);
                $sheet->setCellValue('H' . $row, $item['nm_status_pulang']);
                $sheet->setCellValue('I' . $row, $item['nm_jenis_pasien']);
                $sheet->setCellValue('J' . $row, $item['nm_poliklinik']);
                $sheet->setCellValue('K' . $row, trim($item['diagnosa_klinis']));
                $sheet->setCellValue('L' . $row, $item['dokter']);
                $sheet->setCellValue('M' . $row, $item['dx_primer'] ?? '');
                $sheet->setCellValue('N' . $row, $item['dx_sekunder'] ?? '');
                $sheet->setCellValue('O' . $row, $item['nm_jenis_kelamin']);
                $sheet->setCellValue('P' . $row, $item['usia_lengkap']);

                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_pasien_meninggal.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 ref_dokterrm()
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://103.255.241.146/api/service_rs/ref_dokter',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0, // Waktu tunggu permintaan selama 30 detik
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            // Metode diatur ke POST sesuai kebutuhan API backend
            CURLOPT_CUSTOMREQUEST => 'POST',
            // Mengirim body kosong secara eksplisit menggunakan sintaks array() yang kompatibel
            CURLOPT_POSTFIELDS => array(),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl); // Menangkap error dari cURL jika ada

        curl_close($curl);

        // Selalu atur header Content-Type agar browser tahu ini adalah JSON
        header('Content-Type: application/json');

        if ($err) {
            // Jika terjadi error pada cURL (misal: tidak bisa terhubung ke API)
            echo json_encode(['error' => 'Gagal terhubung ke server API eksternal: ' . $err]);
        } elseif ($response) {
            // Cek apakah respons adalah JSON yang valid sebelum dikirim
            json_decode($response);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['error' => 'Respons dari API eksternal bukan JSON yang valid.']);
            } else {
                // Kirimkan kembali data JSON yang benar dari API
                echo $response;
            }
        } else {
            // Jika tidak ada respons sama sekali dari API
            echo json_encode(['error' => 'Tidak ada respons dari server API eksternal.']);
        }
    }

    public function updateSEPnew()
    {
        // Set header output ke JSON
        header('Content-Type: application/json');

        // Pastikan method request adalah POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            // Ambil data session
            $nm_user = $this->session->userdata('nm_user');
            $kd_user = $this->session->userdata('kd_user');

            // Ambil data dari permintaan POST
            $kd_registrasi = isset($_POST['KD_REGISTRASI']) ? trim($_POST['KD_REGISTRASI']) : '';
            $no_sep = isset($_POST['NO_SEP']) ? trim($_POST['NO_SEP']) : '';
            $tgl_sep = isset($_POST['TGL_SEP']) ? trim($_POST['TGL_SEP']) : '';
            $kd_poli = isset($_POST['KD_POLI']) ? trim($_POST['KD_POLI']) : '';
            $nm_poli = isset($_POST['NM_POLI']) ? trim($_POST['NM_POLI']) : '';
            $dpjp = isset($_POST['DPJP']) ? trim($_POST['DPJP']) : '';
            $nm_dpjp = isset($_POST['NM_DPJP']) ? trim($_POST['NM_DPJP']) : '';

            // Periksa apakah data penting tidak kosong
            if (!empty($kd_registrasi) && !empty($no_sep) && !empty($tgl_sep) && !empty($dpjp)) {

                // --- PERBAIKAN: Format ulang tanggal ---
                // Ubah format dari yyyy-MM-dd (dari form) ke d/m/Y (sesuai kebutuhan API)
                $tgl_sep_api = date('d/m/Y', strtotime($tgl_sep));

                // Siapkan data untuk cURL
                $data_post_api = array(
                    'KD_REGISTRASI' => $kd_registrasi,
                    'NO_SEP'        => $no_sep,
                    'TGL_SEP'       => $tgl_sep_api, // Gunakan tanggal yang sudah diformat
                    'KD_POLI'       => $kd_poli,
                    'NM_POLI'       => $nm_poli,
                    'DPJP'          => $dpjp,
                    'NM_DPJP'       => $nm_dpjp
                );

                // Inisialisasi cURL
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'http://103.255.241.146/api/service_rs/tambah_sep', // Tambahkan http://
                    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 => http_build_query($data_post_api), // Gunakan http_build_query
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/x-www-form-urlencoded' // Sesuaikan header
                    ),
                ));

                $response = curl_exec($curl);
                $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

                if (curl_errno($curl)) {
                    $error_msg = curl_error($curl);
                    curl_close($curl);
                    echo json_encode(array('status' => false, 'message' => 'cURL Error: ' . $error_msg));
                    exit();
                }

                curl_close($curl);

                // Log harian (mengikuti contoh batal_sep)
                // Pastikan endpoint 'sinaran_update_sep' ada atau sesuaikan
                $datai = [
                    "KD_REGISTRASI" => $kd_registrasi,
                    "NO_SEP" => $no_sep,
                    "NIP_PETUGAS" => $kd_user,
                    "CATATAN" => "Akun " . $nm_user . " Telah Mengupdate SEP dengan NO SEP: " . $no_sep
                ];
                $curl_log = curl_init();
                curl_setopt_array($curl_log, [
                    CURLOPT_URL => 'http://103.255.241.146/api/service_rs/sinaran_update_sep', // Sesuaikan endpoint log
                    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 => http_build_query($datai), // Gunakan http_build_query
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/x-www-form-urlencoded'
                    ),
                ]);
                $responsee_log = curl_exec($curl_log); // Eksekusi log
                curl_close($curl_log);
                // Akhir dari Log Harian

                // Periksa kode respons dari API
                if ($httpCode == 200) {
                    $response_data = json_decode($response, true);

                    // Sesuaikan pengecekan respons dengan format API 'tambah_sep'
                    if (isset($response_data['metadata']['code']) && $response_data['metadata']['code'] == 200) {
                        echo json_encode(array('status' => true, 'message' => $response_data['metadata']['message'] ?? 'Berhasil mengupdate SEP.'));
                    } else {
                        $error_message = $response_data['metadata']['message'] ?? 'Gagal mengupdate SEP.';
                        echo json_encode(array('status' => false, 'message' => $error_message, 'data' => $response_data));
                    }
                } else {
                    echo json_encode(array('status' => false, 'message' => 'Error: Respons API tidak benar (' . $httpCode . ')', 'response' => $response));
                }
            } else {
                // Jika data POST tidak lengkap
                echo json_encode(array('status' => false, 'message' => 'Data input tidak lengkap. Pastikan Kode Registrasi, No SEP, Tgl SEP, dan DPJP terisi.'));
            }
        } else {
            // Jika request method bukan POST
            echo json_encode(array('status' => false, 'message' => 'Invalid request method.'));
        }
    }

    public function datapasienispapneu()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AKHIR'])) {
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];

            $tanggal_awal = date('d/m/Y', strtotime($tanggalawal));
            $tanggal_akhir = date('d/m/Y', strtotime($tanggalakhir));

            // Ambil data aggregate
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/pasien_ispa_agg',
                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
                ),
            ));
            $aggResponse = curl_exec($curl);
            curl_close($curl);

            // Ambil data detail
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/pasien_pneu_ispa',
                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
                ),
            ));
            $tableResponse = curl_exec($curl);
            curl_close($curl);

            if (!$aggResponse || !$tableResponse) {
                echo json_encode(['status' => false, 'message' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
                return;
            }

            $aggData = json_decode($aggResponse, true);
            $tableData = json_decode($tableResponse, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['status' => false, 'message' => 'Data tidak valid.']);
                return;
            }

            if (!isset($tableData['response']) || !is_array($tableData['response'])) {
                echo json_encode(['status' => false, 'message' => 'Format data detail tidak valid.']);
                return;
            }

            $aggValue = $aggData;
            if (isset($aggData['response'])) {
                $aggValue = $aggData['response'];
            }

            echo json_encode([
                'status' => true,
                'agg' => $aggValue,
                'response' => $tableData['response']
            ]);
        } else {
            echo json_encode(['status' => false, 'message' => 'Data input tidak lengkap. Pastikan TANGGAL_AWAL dan TANGGAL_AKHIR terisi.']);
        }
    }

    public function downloadataispapneumoni()
    {

        $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 aggregate menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/pasien_ispa_agg',
            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
            ),
        ));

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

        // Memanggil API detail menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/pasien_pneu_ispa',
            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
            ),
        ));

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

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

        ];
        $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 ($tableResponse) {
            $decoded = json_decode($tableResponse, true);
            if (!is_array($decoded) || !isset($decoded['response']) || !is_array($decoded['response'])) {
                echo json_encode(['error' => 'Data tidak valid untuk diekspor.']);
                return;
            }

            $data = $decoded['response'];

            $oldDisplayErrors = ini_get('display_errors');
            $oldStartupErrors = ini_get('display_startup_errors');
            $oldErrorReporting = error_reporting();
            ini_set('display_errors', '0');
            ini_set('display_startup_errors', '0');
            error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);

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

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

            // Set header kolom
            $sheet->setCellValue('A1', 'No Urut');
            $sheet->setCellValue('B1', 'Kelompok Penyakit');
            $sheet->setCellValue('C1', 'Total Kasus');
            $sheet->setCellValue('D1', '< 1 Tahun (L)');
            $sheet->setCellValue('E1', '< 1 Tahun (P)');
            $sheet->setCellValue('F1', '< 1 Tahun (Total)');
            $sheet->setCellValue('G1', '< 5 Tahun (L)');
            $sheet->setCellValue('H1', '< 5 Tahun (P)');
            $sheet->setCellValue('I1', '< 5 Tahun (Total)');
            $sheet->setCellValue('J1', 'Usia 5-9 (L)');
            $sheet->setCellValue('K1', 'Usia 5-9 (P)');
            $sheet->setCellValue('L1', 'Usia 5-9 (Total)');
            $sheet->setCellValue('M1', 'Usia 10-18 (L)');
            $sheet->setCellValue('N1', 'Usia 10-18 (P)');
            $sheet->setCellValue('O1', 'Usia 10-18 (Total)');
            $sheet->setCellValue('P1', 'Usia 19-59 (L)');
            $sheet->setCellValue('Q1', 'Usia 19-59 (P)');
            $sheet->setCellValue('R1', 'Usia 19-59 (Total)');
            $sheet->setCellValue('S1', '≥ 60 Tahun (L)');
            $sheet->setCellValue('T1', '≥ 60 Tahun (P)');
            $sheet->setCellValue('U1', '≥ 60 Tahun (Total)');
            $sheet->setCellValue('V1', 'Total Laki-laki');
            $sheet->setCellValue('W1', 'Total Perempuan');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['urut'] ?? '');
                $sheet->setCellValue('B' . $row, $item['kelompok_penyakit'] ?? '');
                $sheet->setCellValue('C' . $row, $item['total'] ?? '');

                $sheet->setCellValue('D' . $row, $item['lt1_l'] ?? '');
                $sheet->setCellValue('E' . $row, $item['lt1_p'] ?? '');
                $sheet->setCellValue('F' . $row, $item['lt5_tot'] ?? '');

                $sheet->setCellValue('G' . $row, $item['lt_1_5_l'] ?? '');
                $sheet->setCellValue('H' . $row, $item['lt_1_5_p'] ?? '');
                $sheet->setCellValue('I' . $row, $item['lt_1_5_tot'] ?? '');

                $sheet->setCellValue('J' . $row, $item['usia_5_9_l'] ?? '');
                $sheet->setCellValue('K' . $row, $item['usia_5_9_p'] ?? '');
                $sheet->setCellValue('L' . $row, $item['usia_5_9_tot'] ?? '');

                $sheet->setCellValue('M' . $row, $item['usia_10_18_l'] ?? '');
                $sheet->setCellValue('N' . $row, $item['usia_10_18_p'] ?? '');
                $sheet->setCellValue('O' . $row, $item['usia_10_18_tot'] ?? '');

                $sheet->setCellValue('P' . $row, $item['usia_19_59_l'] ?? '');
                $sheet->setCellValue('Q' . $row, $item['usia_19_59_p'] ?? '');
                $sheet->setCellValue('R' . $row, $item['usia_19_59_tot'] ?? '');

                $sheet->setCellValue('S' . $row, $item['l60_l'] ?? '');
                $sheet->setCellValue('T' . $row, $item['l60_p'] ?? '');
                $sheet->setCellValue('U' . $row, $item['l60_tot'] ?? '');

                $sheet->setCellValue('V' . $row, $item['total_l'] ?? '');
                $sheet->setCellValue('W' . $row, $item['total_p'] ?? '');
                $row++;
            }

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

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

            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            ini_set('display_errors', $oldDisplayErrors);
            ini_set('display_startup_errors', $oldStartupErrors);
            error_reporting($oldErrorReporting);
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }



    public function dataispa_pneuantibiotik()
    {
        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/service_rs/pasien_pneu_ispa_antibiotik',
                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 unduhdataispapneu_antibiotik()
    {

        $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_pneu_ispa_antibiotik',
            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 ispa pneu antibiotik."

        ];
        $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
            // Set header kolom
            $sheet->setCellValue('A1', 'No Urut');
            $sheet->setCellValue('B1', 'Kelompok Penyakit');
            $sheet->setCellValue('C1', 'Total Kasus');

            $sheet->setCellValue('D1', '< 5 Tahun (L)');
            $sheet->setCellValue('E1', '< 5 Tahun (P)');
            $sheet->setCellValue('F1', '< 5 Tahun (Total)');

            $sheet->setCellValue('G1', '1–5 Tahun (L)');
            $sheet->setCellValue('H1', '1–5 Tahun (P)');
            $sheet->setCellValue('I1', '1–5 Tahun (Total)');

            $sheet->setCellValue('J1', 'Usia 5–9 (L)');
            $sheet->setCellValue('K1', 'Usia 5–9 (P)');
            $sheet->setCellValue('L1', 'Usia 5–9 (Total)');

            $sheet->setCellValue('M1', 'Total Laki-laki');
            $sheet->setCellValue('N1', 'Total Perempuan');


            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['urut'] ?? '');
                $sheet->setCellValue('B' . $row, $item['kelompok_penyakit'] ?? '');
                $sheet->setCellValue('C' . $row, $item['total'] ?? '');

                $sheet->setCellValue('D' . $row, $item['lt5_l'] ?? '');
                $sheet->setCellValue('E' . $row, $item['lt5_p'] ?? '');
                $sheet->setCellValue('F' . $row, $item['lt5_tot'] ?? '');

                $sheet->setCellValue('G' . $row, $item['lt_1_5_l'] ?? '');
                $sheet->setCellValue('H' . $row, $item['lt_1_5_p'] ?? '');
                $sheet->setCellValue('I' . $row, $item['lt_1_5_tot'] ?? '');

                $sheet->setCellValue('J' . $row, $item['usia_5_9_l'] ?? '');
                $sheet->setCellValue('K' . $row, $item['usia_5_9_p'] ?? '');
                $sheet->setCellValue('L' . $row, $item['usia_5_9_tot'] ?? '');

                $sheet->setCellValue('M' . $row, $item['total_laki_laki'] ?? '');
                $sheet->setCellValue('N' . $row, $item['total_p'] ?? '');

                $row++;
            }

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