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

class Detailrawatinap extends CI_Controller
{

    public function detailinapview()

    {

        if (!$this->session->userdata('berhasil_loginu')) {

            redirect(''); // Jika tidak login, redirect ke halaman login

        }
        $data['akses'] = $this->session->userdata("kd_akses");
        $data['app'] = $this->session->userdata("kd_app");
        $data['user'] = $this->session->userdata("nm_akses");

        $this->load->view('header', $data);
        $this->load->view('detail_px_inap_al_v', $data);
    }

    public function viewdetailpasieninap()
    {
        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/inap_all_detail',
                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 unduhdetailpxinapall()
    {
        $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_detail',
            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 px inap all detail."

        ];
        $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 Poliklinik');
            $sheet->setCellValue('L1', 'NIP Dokter');
            $sheet->setCellValue('M1', 'Kode Ruang');
            $sheet->setCellValue('N1', 'Kode Status Periksa');
            $sheet->setCellValue('O1', 'Total Billing');
            $sheet->setCellValue('P1', 'Total Pribadi');
            $sheet->setCellValue('Q1', 'Total Penjamin');
            $sheet->setCellValue('R1', 'NIP Petugas Input');
            $sheet->setCellValue('S1', 'No Antrian');
            $sheet->setCellValue('T1', 'Nama Pasien');
            $sheet->setCellValue('U1', 'Alamat Domisili');

            // ========================================================
            // PERBAIKAN JUDUL HEADER AGAR SESUAI DENGAN FORMAT GABUNGAN
            // ========================================================
            $sheet->setCellValue('V1', 'Kecamatan (Kode Desa)'); // Kolom V
            $sheet->setCellValue('W1', 'Kecamatan (Kode Kec)');  // Kolom W
            $sheet->setCellValue('X1', 'Kota / Kabupaten (Kode Kota)'); // Kolom X
            // ========================================================

            $sheet->setCellValue('Y1', 'Kode Provinsi');
            $sheet->setCellValue('Z1', 'Nama Pendaftaran');
            $sheet->setCellValue('AA1', 'Nama Cara Masuk');
            $sheet->setCellValue('AB1', 'Nama Pembayaran');
            $sheet->setCellValue('AC1', 'Nama Jenis Pasien');
            $sheet->setCellValue('AD1', 'Nama Poliklinik');
            $sheet->setCellValue('AE1', 'Kode Grup Ruang');
            $sheet->setCellValue('AF1', 'Nama Dokter');
            $sheet->setCellValue('AG1', 'Nama Status Periksa');
            $sheet->setCellValue('AH1', 'Nama Jenis Kelamin');
            $sheet->setCellValue('AI1', 'Jenis Kelamin (Inisial)');
            $sheet->setCellValue('AJ1', 'Tanggal Lahir');
            $sheet->setCellValue('AK1', 'Umur (Tahun)');
            $sheet->setCellValue('AL1', 'Umur (Bulan)');
            $sheet->setCellValue('AM1', 'Umur (Hari)');
            $sheet->setCellValue('AN1', 'Keterangan');
            $sheet->setCellValue('AO1', 'Dokter DPJP');
            $sheet->setCellValue('AP1', 'Nama Kota');
            $sheet->setCellValue('AQ1', 'Nama Kecamatan');
            $sheet->setCellValue('AR1', 'Tindakan OP');
            $sheet->setCellValue('AS1', 'Realisasi Tindakan');
            $sheet->setCellValue('AT1', 'Tgl OP Selesai');
            $sheet->setCellValue('AU1', 'Nama Bed');
            $sheet->setCellValue('AV1', 'Nama Ruang');
            $sheet->setCellValue('AW1', 'Nama Kelas');
            $sheet->setCellValue('AX1', 'Hari Rawat');
            $sheet->setCellValue('AY1', 'Tanggal (Tgl)');
            $sheet->setCellValue('AZ1', 'Nama Item');
            $sheet->setCellValue('BA1', 'Tagih Hari Rawat');
            $sheet->setCellValue('BB1', 'DX Primer (ICD-10)');
            $sheet->setCellValue('BC1', 'DX Sekunder (ICD-10)');
            $sheet->setCellValue('BD1', 'Nama Penyakit Primer');
            $sheet->setCellValue('BE1', 'Nama Penyakit Sekunder');
            $sheet->setCellValue('BF1', 'Nama Perujuk');
            $sheet->setCellValue('BG1', 'Asal PPK');
            $sheet->setCellValue('BH1', 'Diagnosa');
            $sheet->setCellValue('BI1', 'Ket Rujuk');
            $sheet->setCellValue('BJ1', 'Assesmen Klinis');
            $sheet->setCellValue('BK1', 'Alasan Ranap');
            $sheet->setCellValue('BL1', 'Kondisi Keluar');
            $sheet->setCellValue('BM1', 'No Tagihan');

            // 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'] ?? '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['alamat'] ?? '');
            
            // ========================================================
            // SEJAJARKAN MODEL REGIONAL (DESA, KECAMATAN, KOTA) SEPERTI VIEW
            // ========================================================
            // Kolom V (Kd Desa) diisi: Nama Kecamatan (Kode Desa) -> sesuai logik View Anda
            $desa_format = ($item['nm_kec'] ?? '-') . ' (' . ($item['kd_desa'] ?? '-') . ')';
            $sheet->setCellValue('V'.$row, $desa_format);
            
            // Kolom W (Kd Kec) diisi: Nama Kecamatan (Kode Kec)
            $kec_format = ($item['nm_kec'] ?? '-') . ' (' . ($item['kd_kec'] ?? '-') . ')';
            $sheet->setCellValue('W'.$row, $kec_format);
            
            // Kolom X (Kd Kota) diisi: Nama Kota (Kode Kota)
            $kota_format = ($item['nm_kota'] ?? '-') . ' (' . ($item['kd_kota'] ?? '-') . ')';
            $sheet->setCellValue('X'.$row, $kota_format);
            // ========================================================

            $sheet->setCellValue('Y'.$row, $item['kd_prov'] ?? '');
            $sheet->setCellValue('Z'.$row, $item['nm_pendaftaran'] ?? '');
            $sheet->setCellValue('AA'.$row, $item['nm_cara_masuk'] ?? '');
            $sheet->setCellValue('AB'.$row, $item['nm_pembayaran'] ?? '');
            $sheet->setCellValue('AC'.$row, $item['nm_jenis_pasien'] ?? '');
            
            // Sejajarkan juga nama fungsional lain yang menggabungkan Nama + (Kode) jika ada
            $sheet->setCellValue('AD'.$row, $item['nm_poliklinik'] ?? '');
            $sheet->setCellValue('AE'.$row, $item['kd_grup_ruang'] ?? '');
            $sheet->setCellValue('AF'.$row, $item['nm_dokter'] ?? '');
            $sheet->setCellValue('AG'.$row, $item['nm_status_periksa'] ?? '');
            
            // Kolom AH & AI tetap dipisah sesuai urutan respon asli API Anda
            $sheet->setCellValue('AH'.$row, $item['nm_jenis_kelamin'] ?? '');
            $sheet->setCellValue('AI'.$row, $item['jenis_kelamin'] ?? '');
            $sheet->setCellValue('AJ'.$row, $item['tgl_lahir'] ?? '');
            $sheet->setCellValue('AK'.$row, $item['umur_tahun'] ?? '0');
            $sheet->setCellValue('AL'.$row, $item['umur_bulan'] ?? '0');
            $sheet->setCellValue('AM'.$row, $item['umur_hari'] ?? '0');
            $sheet->setCellValue('AN'.$row, $item['keterangan'] ?? '');
            $sheet->setCellValue('AO'.$row, $item['dpjp'] ?? '');
            $sheet->setCellValue('AP'.$row, $item['nm_kota'] ?? '');
            $sheet->setCellValue('AQ'.$row, $item['nm_kec'] ?? '');
            $sheet->setCellValue('AR'.$row, $item['tindakan_op'] ?? '');
            $sheet->setCellValue('AS'.$row, $item['realisasi_tindakan'] ?? '');
            $sheet->setCellValue('AT'.$row, $item['tgl_op_selesai'] ?? '');
            $sheet->setCellValue('AU'.$row, $item['nama_bed'] ?? '');
            $sheet->setCellValue('AV'.$row, $item['nama_ruang'] ?? '');
            $sheet->setCellValue('AW'.$row, $item['nama_kelas'] ?? '');
            $sheet->setCellValue('AX'.$row, $item['hari_rawat'] ?? '0');
            $sheet->setCellValue('AY'.$row, $item['tgl'] ?? '');
            $sheet->setCellValue('AZ'.$row, $item['nama_item'] ?? '');
            $sheet->setCellValue('BA'.$row, $item['tagih_hari_rawat'] ?? '0');
            $sheet->setCellValue('BB'.$row, $item['dx_primer'] ?? '');
            $sheet->setCellValue('BC'.$row, $item['dx_sekunder'] ?? '');
            $sheet->setCellValue('BD'.$row, $item['nm_penyakit_primer'] ?? '');
            $sheet->setCellValue('BE'.$row, $item['nm_penyakit_sekunder'] ?? '');
            $sheet->setCellValue('BF'.$row, $item['nm_perujuk'] ?? '');
            $sheet->setCellValue('BG'.$row, $item['ppk'] ?? '');
            $sheet->setCellValue('BH'.$row, $item['diagnosa'] ?? '');
            $sheet->setCellValue('BI'.$row, $item['ket_rujuk'] ?? '');
            $sheet->setCellValue('BJ'.$row, $item['assesmen'] ?? '');
            $sheet->setCellValue('BK'.$row, $item['alasan_ranap'] ?? '');
            $sheet->setCellValue('BL'.$row, $item['kondisi_keluar'] ?? '');
            $sheet->setCellValue('BM'.$row, $item['no_tagihan'] ?? '');
            $row++;
            }

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

}