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

// Load Composer autoload
require_once FCPATH . 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class Tracking extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Tracking_model');
    }

    public function index()
    {
        $data = [
            'title' => 'Tracking Registrasi Pasien',
            'list_petugas' => $this->Tracking_model->get_all_petugas()
        ];

        $filters = [
            'start_date' => $this->input->get('start_date'),
            'end_date' => $this->input->get('end_date'),
            'id_petugas' => $this->input->get('id_petugas'),
            'id_petugas_pj' => $this->input->get('id_petugas_pj')
        ];

        $data['tracking_data'] = $this->Tracking_model->get_tracking_data($filters);
        $data['filters'] = $filters;

        $this->render('tracking/index', $data);
    }

    public function export_excel()
    {
        // Set memory limit untuk handle data besar
        ini_set('memory_limit', '512M');
        set_time_limit(300);
        
        $filters = [
            'start_date' => $this->input->get('start_date'),
            'end_date' => $this->input->get('end_date'),
            'id_petugas' => $this->input->get('id_petugas'),
            'id_petugas_pj' => $this->input->get('id_petugas_pj')
        ];

        $data = $this->Tracking_model->get_tracking_data($filters);

        try {
            // Create new Spreadsheet
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set document properties
            $spreadsheet->getProperties()
                ->setCreator("Sistem e-RM")
                ->setLastModifiedBy("Sistem e-RM")
                ->setTitle("Laporan Tracking Registrasi")
                ->setSubject("Tracking Registrasi Pasien");

            // Set header
            $headers = [
                'NO', 
                'TANGGAL REGISTRASI', 
                'NO RM', 
                'NAMA PASIEN', 
                'POLI', 
                'DOKTER',
                'PETUGAS', 
                'PETUGAS PJ', 
                'WAKTU MULAI', 
                'WAKTU SELESAI', 
                'DURASI (MENIT)', 
                'STATUS'
            ];

            // Set header values
            $column = 'A';
            foreach ($headers as $header) {
                $sheet->setCellValue($column . '1', $header);
                $column++;
            }

            // Add data
            $row = 2;
            $no = 1;
            foreach ($data as $item) {
                $waktu_mulai = date('d/m/Y H:i', strtotime($item->waktu_mulai_registrasi));
                $waktu_selesai = $item->waktu_selesai_registrasi ? 
                    date('d/m/Y H:i', strtotime($item->waktu_selesai_registrasi)) : 'Masih Proses';
                $durasi = $item->durasi_menit ? $item->durasi_menit . ' menit' : '-';

                $sheet->setCellValue('A' . $row, $no);
                $sheet->setCellValue('B' . $row, $item->tanggal_registrasi);
                $sheet->setCellValue('C' . $row, $item->rme_no);
                $sheet->setCellValue('D' . $row, $item->nama_pasien);
                $sheet->setCellValue('E' . $row, $item->nama_poli);
                $sheet->setCellValue('F' . $row, $item->nama_dokter ?: '-');
                $sheet->setCellValue('G' . $row, $item->nama_petugas ?: '-');
                $sheet->setCellValue('H' . $row, $item->nama_petugas_pj ?: '-');
                $sheet->setCellValue('I' . $row, $waktu_mulai);
                $sheet->setCellValue('J' . $row, $waktu_selesai);
                $sheet->setCellValue('K' . $row, $durasi);
                $sheet->setCellValue('L' . $row, $item->status_registrasi);

                $row++;
                $no++;
            }

            // Style untuk header
            $headerStyle = [
                'font' => [
                    'bold' => true,
                    'color' => ['rgb' => 'FFFFFF']
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical' => Alignment::VERTICAL_CENTER
                ],
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => '3498DB']
                ]
            ];

            $sheet->getStyle('A1:L1')->applyFromArray($headerStyle);

            // Set column widths
            $sheet->getColumnDimension('A')->setWidth(8);
            $sheet->getColumnDimension('B')->setWidth(15);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(25);
            $sheet->getColumnDimension('E')->setWidth(20);
            $sheet->getColumnDimension('F')->setWidth(20);
            $sheet->getColumnDimension('G')->setWidth(20);
            $sheet->getColumnDimension('H')->setWidth(20);
            $sheet->getColumnDimension('I')->setWidth(20);
            $sheet->getColumnDimension('J')->setWidth(20);
            $sheet->getColumnDimension('K')->setWidth(15);
            $sheet->getColumnDimension('L')->setWidth(15);

            // Set row height untuk header
            $sheet->getRowDimension(1)->setRowHeight(25);

            // Auto filter
            $sheet->setAutoFilter('A1:L' . ($row - 1));

            // Set filename
            $filename = 'tracking_registrasi_' . date('Ymd_His') . '.xlsx';

            // Clear any previous output
            if (ob_get_length()) ob_clean();

            // Redirect output to browser
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
            header('Cache-Control: cache, must-revalidate');
            header('Pragma: public');

            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');
            exit;

        } catch (Exception $e) {
            log_message('error', 'PhpSpreadsheet Export Error: ' . $e->getMessage());
            $this->export_csv();
        }
    }

    public function export_csv()
    {
        $filters = [
            'start_date' => $this->input->get('start_date'),
            'end_date' => $this->input->get('end_date'),
            'id_petugas' => $this->input->get('id_petugas'),
            'id_petugas_pj' => $this->input->get('id_petugas_pj')
        ];

        $data = $this->Tracking_model->get_tracking_data($filters);

        // Clear any previous output
        if (ob_get_length()) ob_clean();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="tracking_registrasi_' . date('Ymd_His') . '.csv"');

        $output = fopen('php://output', 'w');
        fwrite($output, "\xEF\xBB\xBF"); // BOM for UTF-8

        // Header
        fputcsv($output, [
            'NO', 'TANGGAL REGISTRASI', 'NO RM', 'NAMA PASIEN', 'POLI', 'DOKTER',
            'PETUGAS', 'PETUGAS PJ', 'WAKTU MULAI', 'WAKTU SELESAI', 'DURASI (MENIT)', 'STATUS'
        ], ';');

        // Data
        $no = 1;
        foreach ($data as $item) {
            $waktu_mulai = date('d/m/Y H:i', strtotime($item->waktu_mulai_registrasi));
            $waktu_selesai = $item->waktu_selesai_registrasi ? 
                date('d/m/Y H:i', strtotime($item->waktu_selesai_registrasi)) : 'Masih Proses';
            $durasi = $item->durasi_menit ? $item->durasi_menit . ' menit' : '-';

            fputcsv($output, [
                $no++,
                $item->tanggal_registrasi,
                $item->rme_no,
                $item->nama_pasien,
                $item->nama_poli,
                $item->nama_dokter ?: '-',
                $item->nama_petugas ?: '-',
                $item->nama_petugas_pj ?: '-',
                $waktu_mulai,
                $waktu_selesai,
                $durasi,
                $item->status_registrasi
            ], ';');
        }

        fclose($output);
        exit;
    }
}
