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

class Datarawatinap 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_datarawatinap()
    {
        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");

        // Ambil tanggal awal dari input POST
        $tgl_awal = $_POST['tanggal_awal'];

        // Atur tanggal akhir secara otomatis (misalnya, 1 hari setelah tanggal awal)
        $tgl_akhir = date('Y-m-d', strtotime($tgl_awal));

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

        // Siapkan data untuk dikirim ke API
        $datai["TANGGAL_AWAL"] = $tanggal_awal;
        $data["TANGGAL_PERIKSA"] = $tanggal_awal;
        $datae["TANGGAL_AKHIR"] = $tanggal_akhir;


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/d_reg_online/tampil_pasien_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 // Tambahkan tanggal akhir ke body request
            ),
        ));

        $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_inap_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 => array(
                'TANGGAL_AWAL' => $tanggal_awal,
                'TANGGAL_AKHIR' => $tanggal_akhir // Tambahkan tanggal akhir ke body request
            ),

        ));

        $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/service_rs/tampil_ketersediaan_tempat_tidur',
            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 // Tambahkan tanggal akhir ke body request
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $jsonc =  str_replace('\r\n     ', "---0", $response);
        $jsonc =  str_replace('\r\n', "---", $jsonc);
        $jsonc = json_decode($jsonc);


        $data["pasieninap"]                = $jsona;
        $data["totalpasieninap"]               = $jsonb;
        $data["ketersediantt"]               = $jsonc;
        $data["akses"]               = $akses;
        $data["app"]               = $app;
        $data["tgl_awal"]        = $tgl_akhir;
        $this->load->view('dashboard/header', $data);
        $this->load->view('dashboard/pasienrawatinap', $data);
    }


    public function pasieninapdpjp()
    {
        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/inap_dpjp',
                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 downloadpenjamindpjp()
    {
        $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/inap_dpjp',
            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 Penjamin DPJP."

        ];
        $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 Dokter');
            $sheet->setCellValue('B1', 'Jumlah');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['nm_dokter']);
                $sheet->setCellValue('B' . $row, $item['qty']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_pasien_inap_dpjp.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 batalresumeranap()
    {
        // Pastikan method request adalah POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Ambil data KD_REGISTRASI dari permintaan POST
            $kd_registrasi = isset($_POST['kd_registrasi']) ? $_POST['kd_registrasi'] : '';
            $kd_jenis_pasien = isset($_POST['kd_jenis_pasien']) ? $_POST['kd_jenis_pasien'] : '';

            // Periksa apakah KD_REGISTRASI dan KD_JENIS_PASIEN saat kosong
            if (!empty($kd_registrasi) && !empty($kd_jenis_pasien)) {
                // Inisialisasi cURL
                $curl = curl_init();

                // Set parameter cURL
                curl_setopt_array($curl, array(
                    CURLOPT_URL => '103.255.241.146/api/d_reg_online/batal_resume',
                    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(
                        'KD_REGISTRASI' => $kd_registrasi, // Mengirim kode registrasi dari permintaan
                        'KD_JENIS_PASIEN' => $kd_jenis_pasien // Mengirim kode jenis pasien dari permintaan
                    ),
                ));

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

                // Periksa apakah ada error dalam eksekusi cURL
                if (curl_errno($curl)) {
                    echo 'Error:' . curl_error($curl);
                } else {
                    // Tampilkan respons API
                    echo $response;
                }

                // Tutup cURL
                curl_close($curl);
            } else {
                // Jika KD_REGISTRASI kosong, kirimkan pesan kesalahan
                echo json_encode(array('status' => false, 'message' => 'KD_REGISTRASI tidak valid.'));
            }
        } else {
            // Jika request method bukan POST
            echo json_encode(array('status' => false, 'message' => 'Invalid request method.'));
        }
    }

    public function pasieninaptotal()
    {
        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/inap_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 downloadpasienranaptotal()
    {
        $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/inap_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 Pasien RANAP 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'];

            // 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 Regist');
            $sheet->setCellValue('G1', 'Jam Regist');
            $sheet->setCellValue('H1', 'Tanggal Keluar');
            $sheet->setCellValue('I1', 'Jam Keluar');
            $sheet->setCellValue('J1', 'Kode Jenis Pasien');
            $sheet->setCellValue('K1', 'Kode Poliklinik');
            $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', 'Nama Cara Masuk');
            $sheet->setCellValue('Y1', 'Nama Pembayaran');
            $sheet->setCellValue('Z1', 'Nama Jenis Pasien');
            $sheet->setCellValue('AA1', 'Nama Poliklinik');
            $sheet->setCellValue('AB1', 'Kode Grup Ruang');
            $sheet->setCellValue('AC1', 'Nama Dokter');
            $sheet->setCellValue('AD1', 'Nama Status Periksa');
            $sheet->setCellValue('AE1', 'DPJP');

            // 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['dpjp']);
                $row++;
            }

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