<?php

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



class Demoperpoli extends CI_Controller

{


 public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('berhasil_loginu')) {
            redirect('');
        }
    }

   // -------------------------------------------------------------------------
    // 1. REFERENSI POLI (Menggunakan Kode Anda + Support Internal Call)
    // -------------------------------------------------------------------------
    public function refpoliklinik($return_array = false)
    {
        // Menginisialisasi cURL
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://103.255.241.146/api/service_rs/ref_poliklinik', // URL 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', // METHOD POST
            CURLOPT_POSTFIELDS => array(),
        ));

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

        // LOGIKA TAMBAHAN:
        // Jika fungsi ini dipanggil oleh PHP lain ($return_array = true),
        // kembalikan array data, bukan echo JSON.
        if ($return_array) {
            if ($err || !$response) return [];
            $decoded = json_decode($response);
            return $decoded->response ?? [];
        }

        // Jika dipanggil oleh AJAX (JavaScript), echo JSON
        header('Content-Type: application/json');

        if ($err) {
            echo json_encode(['error' => 'Gagal terhubung ke server API eksternal: ' . $err]);
        } elseif ($response) {
            json_decode($response);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['error' => 'Respons dari API eksternal bukan JSON yang valid.']);
            } else {
                echo $response;
            }
        } else {
            echo json_encode(['error' => 'Tidak ada respons dari server API eksternal.']);
        }
    }

    // -------------------------------------------------------------------------
    // 2. TAMPIL DATA USIA PER POLI
    // -------------------------------------------------------------------------
   public function demousiaperpoli1()
    {
        // 1. Ambil Session (PENTING: Agar Sidebar tidak error)
        $data['akses'] = $this->session->userdata("kd_akses");
        $data['app']   = $this->session->userdata("kd_app");

        // 2. Ambil Input
        $tgl_awal  = $this->input->post('tanggal_awal');
        $tgl_akhir = $this->input->post('tanggal_akhir');
        $kd_poli   = $this->input->post('kd_jenispoli');

        $ta_api = date('d/m/Y', strtotime($tgl_awal));
        $tk_api = date('d/m/Y', strtotime($tgl_akhir));

        $postData = [
            'TANGGAL_AWAL'  => $ta_api,
            'TANGGAL_AKHIR' => $tk_api,
            'KD_POLIKLINIK' => $kd_poli
        ];

        // 3. Hit API Usia (CUKUP SEKALI SAJA)
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_usia_perpoli',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
        ]);
        $response = json_decode(curl_exec($curl));
        curl_close($curl);

        // Simpan hasil response ke variabel utama
        $data['demografi_usia'] = $response;

        // 4. Data Pendukung View
        $data['tgl_awal']      = $tgl_awal;
        $data['tgl_akhir']     = $tgl_akhir;
        $data['active_tab']    = '#tab-usia-poli';
        $data['selected_poli'] = $kd_poli; 

        // Load ulang list poli
        $data['list_poli'] = $this->refpoliklinik(true);
        
        // Cari Nama Poli
        $data['nama_poli_selected'] = '-';
        if(!empty($data['list_poli'])){
            foreach($data['list_poli'] as $p) {
                if($p->kd_poliklinik == $kd_poli) {
                    $data['nama_poli_selected'] = $p->nm_poliklinik;
                    break;
                }
            }
        }

        $this->load->view('dashboard/header', $data); 
        $this->load->view('dashboard/datademografiperpoli_view', $data); 
    }
    // -------------------------------------------------------------------------
    // 3. TAMPIL DATA GENDER PER POLI
    // -------------------------------------------------------------------------
    public function demojeniskelpoli1()
    {
        $data['akses'] = $this->session->userdata("kd_akses");
        $data['app']   = $this->session->userdata("kd_app");

        $tgl_awal  = $this->input->post('tanggal_awal');
        $tgl_akhir = $this->input->post('tanggal_akhir');
        $kd_poli   = $this->input->post('kd_jenispoli');

        $ta_api = date('d/m/Y', strtotime($tgl_awal));
        $tk_api = date('d/m/Y', strtotime($tgl_akhir));

        $postData = [
            'TANGGAL_AWAL'  => $ta_api,
            'TANGGAL_AKHIR' => $tk_api,
            'KD_POLIKLINIK' => $kd_poli
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_jenis_kelamin_perpoli',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
        ]);
        $data['datagender'] = json_decode(curl_exec($curl));
        curl_close($curl);

        $data['tgl_awal']      = $tgl_awal;
        $data['tgl_akhir']     = $tgl_akhir;
        $data['active_tab']    = '#tab-gender-poli';
        $data['selected_poli'] = $kd_poli;
        $data['list_poli']     = $this->refpoliklinik(true);

        $data['nama_poli_selected'] = '-';
        if(!empty($data['list_poli'])){
            foreach($data['list_poli'] as $p) {
                if($p->kd_poliklinik == $kd_poli) {
                    $data['nama_poli_selected'] = $p->nm_poliklinik;
                    break;
                }
            }
        }

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

    public function unduhdatademousiaperpoli()
    {
        ob_start();
        $tanggal_awal = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');
        $kdjenispoli = $this->input->get('KD_POLIKLINIK');


        // 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/demografi_usia_perpoli',
            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_POLIKLINIK' => $kdjenispoli
            ),
        ));

        $response = 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', 'Umur');
            $sheet->setCellValue('B1', 'Jumlah');


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

            // Hapus semua output yang mungkin sudah ada di buffer sebelum mengirim header
             ob_end_clean();

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

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


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

            // Hapus semua output yang mungkin sudah ada di buffer sebelum mengirim header
             ob_end_clean();

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_demografi_usia_alldata.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 unduhdemojeniskelperpoli()
    {
        ob_start();
        $tanggal_awal = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');
        $kdjenispoli =$this->input->get ('KD_POLIKLINIK');


        // 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/demografi_jenis_kelamin_perpoli',
            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_POLIKLINIK' => $kdjenispoli
            ),
        ));

        $response = 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', 'Jenis Kelamin');
            $sheet->setCellValue('B1', 'Jumlah');


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

              // Hapus semua output yang mungkin sudah ada di buffer sebelum mengirim header
             ob_end_clean();

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