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

class Rekapbpjsperksm extends CI_Controller

{

    public function datarekapkeubpjsperksm()
    {

        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AWAL']) && isset($_POST['KD_JENIS_PASIEN'])) {

            // Mengambil input tanggal dari form
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];
            $kdjenispasien = $_POST['KD_JENIS_PASIEN'];
            // Mengonversi format tanggal ke dd/mm/yyyy
            $tanggal_awal = date('d/m/Y', strtotime($tanggalawal));
            $tanggal_akhir = date('d/m/Y', strtotime($tanggalakhir));

            // Mengambil data dari API

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

            ));

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

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

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

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


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


        // Memanggil API menggunakan cURL
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/tampil_rekap_bpjs_ksm',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'TANGGAL_AWAL' => $tanggal_awali,
                'TANGGAL_AKHIR' => $tanggal_akhiri,
                'KD_JENIS_PASIEN' => $kdjenispasien

            ),

        ));



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

        //log harian download

        $datai = [

            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download Data Rekap BPJS PER-KSM."
        ];

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

            $data = json_decode($tampil, true)['tampil'];
            // Sembunyikan notice PHP 8.1 dari PhpSpreadsheet agar tidak mengganggu output header
            error_reporting(E_ERROR | E_PARSE);

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

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

            // Set header kolo
            $sheet->setCellValue('A1', 'Nama Spesialis');
            $sheet->setCellValue('B1', 'Jumlah');
            $sheet->setCellValue('C1', 'Tarif BPJS');
            $sheet->setCellValue('D1', 'Tarif RS');
            $sheet->setCellValue('E1', 'Prosedur Non Bedah');
            $sheet->setCellValue('F1', 'Prosedur Bedah');
            $sheet->setCellValue('G1', 'Konsultasi');
            $sheet->setCellValue('H1', 'Tenaga Ahli');
            $sheet->setCellValue('I1', 'Keperawatan');
            $sheet->setCellValue('J1', 'Penunjang');
            $sheet->setCellValue('K1', 'Radiologi');
            $sheet->setCellValue('L1', 'Laboratorium');
            $sheet->setCellValue('M1', 'Pelayanan Darah');
            $sheet->setCellValue('N1', 'Rehabilitasi');
            $sheet->setCellValue('O1', 'Kamar Akomodasi');
            $sheet->setCellValue('P1', 'Rawat Intensif');
            $sheet->setCellValue('Q1', 'Obat');
            $sheet->setCellValue('R1', 'Alkes');
            $sheet->setCellValue('S1', 'BMHP');
            $sheet->setCellValue('T1', 'Sewa Alat');



            // Isi data

            $row = 2;

            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['nm_spesialis'] ?? '-');
                $sheet->setCellValue('B' . $row, $item['jml'] ?? '0');
                $sheet->setCellValue('C' . $row, $item['tarif_bpjs'] ?? '0');
                $sheet->setCellValue('D' . $row, $item['tarif_rs'] ?? '0');
                $sheet->setCellValue('E' . $row, $item['prosedur_non_bedah'] ?? '0');
                $sheet->setCellValue('F' . $row, $item['prosedur_bedah'] ?? '0');
                $sheet->setCellValue('G' . $row, $item['konsultasi'] ?? '0');
                $sheet->setCellValue('H' . $row, $item['tenaga_ahli'] ?? '0');
                $sheet->setCellValue('I' . $row, $item['keperawatan'] ?? '0');
                $sheet->setCellValue('J' . $row, $item['penunjang'] ?? '0');
                $sheet->setCellValue('K' . $row, $item['radiologi'] ?? '0');
                $sheet->setCellValue('L' . $row, $item['laboratorium'] ?? '0');
                $sheet->setCellValue('M' . $row, $item['pelayanan_darah'] ?? '0');
                $sheet->setCellValue('N' . $row, $item['rehabilitasi'] ?? '0');
                $sheet->setCellValue('O' . $row, $item['kamar_akomodasi'] ?? '0');
                $sheet->setCellValue('P' . $row, $item['rawat_intensif'] ?? '0');
                $sheet->setCellValue('Q' . $row, $item['obat'] ?? '0');
                $sheet->setCellValue('R' . $row, $item['alkes'] ?? '0');
                $sheet->setCellValue('S' . $row, $item['bmhp'] ?? '0');
                $sheet->setCellValue('T' . $row, $item['sewa_alat'] ?? '0');
                $row++;
            }


            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $tmpFile = tempnam(sys_get_temp_dir(), 'nonbpjs_xlsx_');
            $writer->save($tmpFile);

            while (ob_get_level()) {
                ob_end_clean();
            }

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

            readfile($tmpFile);
            @unlink($tmpFile);
            exit();
        } else {

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