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

class Datademografi 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 __construct()
    {
        parent::__construct();
        // Cek login di construct agar berlaku untuk semua fungsi
        if (!$this->session->userdata('berhasil_loginu')) {
            redirect('');
        }
    }

public function filter_datausia()
    {
        $akses = $this->session->userdata("kd_akses");
        $app   = $this->session->userdata("kd_app");

        // 1. LOGIKA TANGGAL PINTAR
        // Jika User klik tombol Filter (POST), pakai tanggal itu.
        // Jika User baru buka menu (Tidak ada POST), pakai TANGGAL HARI INI.
        if ($this->input->post('tanggal_awal')) {
            $tgl_awal_html = $this->input->post('tanggal_awal');
            $tgl_akhir_html = $this->input->post('tanggal_akhir');
        } else {
            $tgl_awal_html = date('Y-m-d'); // Default Hari Ini
            $tgl_akhir_html = date('Y-m-d'); // Default Hari Ini
        }

        $ta_api = date('d/m/Y', strtotime($tgl_awal_html));
        $tk_api = date('d/m/Y', strtotime($tgl_akhir_html));

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

        // ---------------------------------------------------------------------
        // BAGIAN A: AMBIL DATA USIA (Kode Lama Anda - Tetap Ada)
        // ---------------------------------------------------------------------
        $apis_usia = [
            'usiakurang1thn'    => 'demografi_kurang_satu_tahun',
            'usia1sampai3thn'   => 'demografi_satu_sampai_tiga_tahun',
            'usia3sampai5thn'   => 'demografi_tiga_sampai_lima_tahun',
            'usia5sampai18thn'  => 'demografi_lima_sampai_delapanbelas_tahun',
            'usia18sampai58thn' => 'demografi_delapanbelas_sampai_limadepalan_tahun',
            'usia58thnlebih'    => 'demografi_lebihdari_limadepalan_tahun'
        ];

        foreach ($apis_usia as $key => $endpoint) {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => '103.255.241.146/api/service_rs/' . $endpoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $postData,
            ]);
            $resp = curl_exec($curl);
            curl_close($curl);
            
            // Pembersihan JSON (Sesuai kebiasaan kode Anda)
            $cleanJson = str_replace(['\r\n     ', '\r\n'], ["---0", "---"], $resp);
            $data[$key] = json_decode($cleanJson);
        }

        // ---------------------------------------------------------------------
        // BAGIAN B: AMBIL DATA ALAMAT (INI YANG SEBELUMNYA HILANG!) 
        // <--- PERUBAHAN BARU: SAYA TAMBAHKAN BAGIAN INI
        // ---------------------------------------------------------------------
        
        $apis_alamat = [
            'demokabupatenkota' => 'demografi_kabupate_kota',
            'demokecamatan'     => 'demografi_kecamatan',
            'demodesa'          => 'demografi_desa'
        ];

        foreach ($apis_alamat as $key => $endpoint) {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => '103.255.241.146/api/service_rs/' . $endpoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $postData,
            ]);
            $resp = curl_exec($curl);
            curl_close($curl);

            // Pembersihan JSON juga diterapkan di sini agar aman
            $cleanJson = str_replace(['\r\n     ', '\r\n'], ["---0", "---"], $resp);
            
            // Simpan ke variabel data utama ($demokabupatenkota, dll)
            $data[$key] = json_decode($cleanJson); 
        }
        // <--- AKHIR PERUBAHAN BARU (Logic Alamat Selesai)

        // ---------------------------------------------------------------------
        // BAGIAN C: KIRIM KE VIEW
        // ---------------------------------------------------------------------
        $data["akses"]      = $akses;
        $data["app"]        = $app;
        $data["tgl_awal"]   = $tgl_awal_html;
        $data["tgl_akhir"]  = $tgl_akhir_html;
        
        // Agar saat refresh tetap di tab yang dipilih
        $data["active_tab"] = $this->input->post('active_tab') ?? '#tab-usia';

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

    // =========================================================================
    // FUNGSI LAINNYA (TETAP SAMA SEPERTI ASLINYA - UNTUK AJAX/DOWNLOAD)
    // =========================================================================

    public function filter_dataalamat()
    {
        // 1. Cek Login (Penting)
        if (!$this->session->userdata('berhasil_loginu')) {
            // Jika sesi habis, kirim JSON error agar JS bisa redirect/alert
            echo json_encode(['status' => 'error', 'message' => 'Sesi habis']);
            exit;
        }

        // 2. Ambil Input Tanggal (Dari AJAX POST)
        // Gunakan default Hari Ini jika kosong
        $tgl_awal = $this->input->post('TANGGAL_AWAL') ?: date('Y-m-d');
        $tgl_akhir = $this->input->post('TANGGAL_AKHIR') ?: date('Y-m-d');

        // Format Tanggal untuk API
        $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
        ];

        // 3. Siapkan Array Penampung Data
        $result = [];

        // --- A. HIT API KABUPATEN ---
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_kabupate_kota',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
        ]);
        $resp = curl_exec($curl);
        curl_close($curl);
        // Bersihkan JSON
        $clean = str_replace(['\r\n     ', '\r\n'], ["---0", "---"], $resp);
        $decoded = json_decode($clean);
        // Ambil bagian response saja
        $result['kabupaten'] = isset($decoded->response) ? $decoded->response : [];


        // --- B. HIT API KECAMATAN ---
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_kecamatan',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
        ]);
        $resp = curl_exec($curl);
        curl_close($curl);
        $clean = str_replace(['\r\n     ', '\r\n'], ["---0", "---"], $resp);
        $decoded = json_decode($clean);
        $result['kecamatan'] = isset($decoded->response) ? $decoded->response : [];


        // --- C. HIT API DESA ---
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_desa',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
        ]);
        $resp = curl_exec($curl);
        curl_close($curl);
        $clean = str_replace(['\r\n     ', '\r\n'], ["---0", "---"], $resp);
        $decoded = json_decode($clean);
        $result['desa'] = isset($decoded->response) ? $decoded->response : [];


        // 4. PENTING: Return JSON ke View (Jangan Load View!)
        header('Content-Type: application/json');
        echo json_encode($result);
    }
    
    public function downloaddataExcel()
    {
        if (!$this->session->userdata('berhasil_loginu')) {
            redirect('');
        }

        // Ambil parameter tanggal dari URL (GET)
        $tgl_awal = $this->input->get('tanggal_awal');
        $tgl_akhir = $this->input->get('tanggal_akhir');

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

        // Daftar API Endpoints
        $apis = [
            'Kurang 1 Tahun' => '103.255.241.146/api/service_rs/demografi_kurang_satu_tahun',
            '1-3 Tahun'      => '103.255.241.146/api/service_rs/demografi_satu_sampai_tiga_tahun',
            '3-5 Tahun'      => '103.255.241.146/api/service_rs/demografi_tiga_sampai_lima_tahun',
            '5-18 Tahun'     => '103.255.241.146/api/service_rs/demografi_lima_sampai_delapanbelas_tahun',
            '18-58 Tahun'    => '103.255.241.146/api/service_rs/demografi_delapanbelas_sampai_limadepalan_tahun',
            '> 58 Tahun'     => '103.255.241.146/api/service_rs/demografi_lebihdari_limadepalan_tahun'
        ];

        // Load library PhpSpreadsheet melalui Composer autoload
        require_once APPPATH . '../vendor/autoload.php';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // --- SETUP HEADER KOLOM ---
        $sheet->setCellValue('A1', 'Kategori Usia');
        $sheet->setCellValue('B1', 'Detail Usia');
        $sheet->setCellValue('C1', 'Jumlah Pasien');

        // Styling Header agar tebal (Optional)
        $sheet->getStyle('A1:C1')->getFont()->setBold(true);

        $rowNum = 2; // Mulai isi data dari baris ke-2

        // --- PROSES HIT API DAN ISI DATA ---
        foreach ($apis as $kategori => $url) {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => ['TANGGAL_AWAL' => $ta_api, 'TANGGAL_AKHIR' => $tk_api],
            ]);
            $response = curl_exec($curl);
            curl_close($curl);

            $dataJson = json_decode($response);

            if (isset($dataJson->response) && is_array($dataJson->response)) {
                foreach ($dataJson->response as $item) {
                    $sheet->setCellValue('A' . $rowNum, $kategori);

                    // Logika kolom Detail (Menyesuaikan field tiap API)
                    if ($kategori == 'Kurang 1 Tahun') {
                        $detail = ($item->bulan ?? 0) . " bln, " . ($item->hari ?? 0) . " hr";
                    } else {
                        $detail = ($item->umur ?? 0) . " Tahun";
                    }

                    $sheet->setCellValue('B' . $rowNum, $detail);
                    $sheet->setCellValue('C' . $rowNum, $item->qty ?? 0);
                    $rowNum++;
                }
            }
        }

        // --- KONFIGURASI DOWNLOAD ---
        $filename = "Data_Demografi_Usia" . date('Ymd_His') . ".xlsx";
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }

     public function downloaddatagender()
    {
        $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_jenis_kelamin',
            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', '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++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="data_demografi_jeniskelamin.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 unduhdata_alamat() {
        // 1. Cek Login
        if (!$this->session->userdata('berhasil_loginu')) {
            redirect('');
        }

        $tgl_awal = $this->input->get('tanggal_awal');
        $tgl_akhir = $this->input->get('tanggal_akhir');
        $ta_api = date('d/m/Y', strtotime($tgl_awal));
        $tk_api = date('d/m/Y', strtotime($tgl_akhir));

        // Array API
        $apis = [
            'Kabupaten' => '103.255.241.146/api/service_rs/demografi_kabupate_kota',
            'Kecamatan' => '103.255.241.146/api/service_rs/demografi_kecamatan',
            'Desa'      => '103.255.241.146/api/service_rs/demografi_desa'
        ];

        require_once APPPATH . '../vendor/autoload.php';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        
        $i = 0;
        foreach ($apis as $label => $url) {
            if ($i > 0) $spreadsheet->createSheet();
            $spreadsheet->setActiveSheetIndex($i);
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->setTitle($label);

            // Header Style
            $sheet->setCellValue('A1', 'Nama Wilayah');
            $sheet->setCellValue('B1', 'Jumlah Pasien');
            $sheet->getStyle('A1:B1')->getFont()->setBold(true);
            $sheet->getColumnDimension('A')->setAutoSize(true);

            // Hit API
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_POSTFIELDS, ['TANGGAL_AWAL' => $ta_api, 'TANGGAL_AKHIR' => $tk_api]);
            $res = json_decode(curl_exec($curl));
            curl_close($curl);

            $rowNum = 2;
            if (isset($res->response) && is_array($res->response)) {
                foreach ($res->response as $item) {
                    $valName = $item->nm_kabupaten ?? $item->nm_kota ?? 
                            $item->nm_kecamatan ?? $item->nama_kecamatan ?? 
                            $item->nm_desa ?? $item->nama_desa ?? 
                            '-';

                    $qty = $item->qty ?? 0;

                    $sheet->setCellValue('A' . $rowNum, $valName);
                    $sheet->setCellValue('B' . $rowNum, $qty);
                    $rowNum++;
                }
            }
            $i++;
        }

        $filename = "Demografi_Alamat_".$tgl_awal.".xlsx";
        
        // Header Download
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }

    public function tampilpekerjaan()
    {
        // Cek input (Saya perbaiki typo: yang kedua harusnya TANGGAL_AKHIR)
        if ($this->input->post('TANGGAL_AWAL') && $this->input->post('TANGGAL_AKHIR')) {
            
            $tanggal_awal = date('d/m/Y', strtotime($this->input->post('TANGGAL_AWAL')));
            $tanggal_akhir = date('d/m/Y', strtotime($this->input->post('TANGGAL_AKHIR')));

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/demografi_pekerjaanx',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => array(
                    'TANGGAL_AWAL' => $tanggal_awal,
                    'TANGGAL_AKHIR' => $tanggal_akhir
                ),
            ));

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

            // Langsung echo response JSON agar bisa dibaca JS
            if ($response) {
                echo $response;
            } else {
                echo json_encode(['response' => []]); // Return array kosong jika gagal
            }
        }
    }

    // --- 2. FUNGSI UNTUK DOWNLOAD EXCEL PEKERJAAN ---
    public function unduhdata_pekerjaan() {
        if (!$this->session->userdata('berhasil_loginu')) { redirect(''); }

        $tgl_awal = $this->input->get('tanggal_awal');
        $tgl_akhir = $this->input->get('tanggal_akhir');
        $ta_api = date('d/m/Y', strtotime($tgl_awal));
        $tk_api = date('d/m/Y', strtotime($tgl_akhir));

        require_once APPPATH . '../vendor/autoload.php';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Header
        $sheet->setCellValue('A1', 'Nama Pekerjaan');
        $sheet->setCellValue('B1', 'Jumlah Pasien');
        $sheet->getStyle('A1:B1')->getFont()->setBold(true);
        $sheet->getColumnDimension('A')->setAutoSize(true);

        // Hit API
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, '103.255.241.146/api/service_rs/demografi_pekerjaanx');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_POSTFIELDS, ['TANGGAL_AWAL' => $ta_api, 'TANGGAL_AKHIR' => $tk_api]);
        $response = json_decode(curl_exec($curl));
        curl_close($curl);

        $row = 2;
        if (isset($response->response) && is_array($response->response)) {
            foreach ($response->response as $item) {
                // Menyesuaikan nama field dari API (biasanya 'pekerjaan' atau 'nm_pekerjaan')
                $nama = $item->pekerjaan ?? $item->nm_pekerjaan ?? '-';
                $sheet->setCellValue('A' . $row, $nama);
                $sheet->setCellValue('B' . $row, $item->qty);
                $row++;
            }
        }

        $filename = "Demografi_Pekerjaan_".$tgl_awal.".xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }
}
