<?php

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

class Polirujuk extends CI_Controller
{
     public function datapolirujuk()
    {
        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/poli_konsul',
                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 unduhdatapolirujuk()
    {
        $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/poli_konsul',
            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 POLI RUJUK."
        ];
        
        $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) {
            $rawData = json_decode($response, true);
            
            // Cek apakah key 'response' ada dan berisi array
            if (isset($rawData['response']) && is_array($rawData['response'])) {
                $data = $rawData['response'];

                // Load library PhpSpreadsheet
                require_once APPPATH . '../vendor/autoload.php';

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

                // ==========================================
                // 1. SET HEADER & STYLE
                // ==========================================
                $headerStyle = [
                    'font' => ['bold' => true],
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                    ],
                    'borders' => [
                        'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN],
                    ],
                    'fill' => [
                        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                        'startColor' => ['argb' => 'FFE0E0E0'],
                    ],
                ];

                $sheet->setCellValue('A1', 'Nama DPJP');
                $sheet->setCellValue('B1', 'Kd Poliklinik');
                $sheet->setCellValue('C1', 'Nama Sifat Konsul');
                $sheet->setCellValue('D1', 'Jumlah Konsul');
                $sheet->setCellValue('E1', 'Nama Dokter Tujuan');
                
                $sheet->getStyle('A1:E1')->applyFromArray($headerStyle);

                // ==========================================
                // 2. LOGIKA GROUPING DATA (Agar bisa merge)
                // ==========================================
                $groupedData = [];
                foreach ($data as $item) {
                    $dpjpName = $item['dpjp'];
                    if (!isset($groupedData[$dpjpName])) {
                        $groupedData[$dpjpName] = [];
                    }
                    $groupedData[$dpjpName][] = $item;
                }

                // ==========================================
                // 3. LOOPING DATA & MERGE CELLS
                // ==========================================
                $row = 2;
                
                foreach ($groupedData as $dpjpName => $items) {
                    $startRow = $row; // Baris awal grup ini
                    
                    foreach ($items as $detail) {
                        // Isi kolom detail (B, C, D, E)
                        $sheet->setCellValue('B' . $row, $detail['kd_poliklinik']);
                        $sheet->setCellValue('C' . $row, $detail['nm_sifat_konsul']);
                        $sheet->setCellValue('D' . $row, $detail['jumlah_konsul']);
                        $sheet->setCellValue('E' . $row, $detail['nm_dokter']);
                        
                        $row++; // Pindah ke baris berikutnya
                    }
                    
                    $endRow = $row - 1; // Baris akhir grup ini

                    // Isi Nama DPJP di baris pertama grup
                    $sheet->setCellValue('A' . $startRow, $dpjpName);

                    // Lakukan MERGE jika grup memiliki lebih dari 1 baris
                    if ($endRow > $startRow) {
                        $sheet->mergeCells("A{$startRow}:A{$endRow}");
                    }

                    // Styling kolom DPJP agar teks di tengah (Vertically Center)
                    $sheet->getStyle("A{$startRow}:A{$endRow}")->getAlignment()
                        ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
                }

                // ==========================================
                // 4. FINISHING (Border & AutoSize)
                // ==========================================
                $lastRow = $row - 1;
                $styleArray = [
                    'borders' => [
                        'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN],
                    ],
                ];
                // Beri border ke seluruh data
                $sheet->getStyle('A1:E' . $lastRow)->applyFromArray($styleArray);

                // Auto width kolom
                foreach (range('A', 'E') as $col) {
                    $sheet->getColumnDimension($col)->setAutoSize(true);
                }

                // Mengatur header untuk unduhan
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="Data_Poli_Konsul.xlsx"');
                header('Cache-Control: max-age=0');

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

            } else {
                // Jika response API tidak memiliki data array
                echo "Data tidak ditemukan atau format respon API salah.";
            }

        } else {
            echo json_encode(['error' => 'Gagal terhubung ke server API.']);
        }
    }


}