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

class Surat extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->helper('authorization');
        $this->load->library('session');
        $this->load->model('Surat_model');
        $this->load->model('Warga_model');
        $this->load->model('Pengaturan_model'); // untuk print_surat

        check_login();
    }

    public function index() {
        if(cannot('surat', 'view')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini!');
            redirect('dashboard');
        }

        $data['title'] = is_warga() ? 'Pengajuan Surat' : 'Permohonan Surat';

        if(is_warga()) {
            $user_id       = $this->session->userdata('user_id');
            $data['surat'] = $this->Surat_model->get_by_user($user_id);
        } else {
            $data['surat'] = $this->Surat_model->get_all();
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('surat/index', $data);
        $this->load->view('templates/footer');
    }

    public function ajukan() {
        if(cannot('surat', 'create')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk mengajukan surat!');
            redirect('surat');
        }

        $data['title']       = 'Ajukan Surat';
        $data['jenis_surat'] = $this->Surat_model->get_jenis_surat();

        if(is_warga()) {
            $user_id            = $this->session->userdata('user_id');
            $data['warga_saya'] = $this->Warga_model->get_by_user_id($user_id);

            if(!$data['warga_saya']) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan! Hubungi admin.');
                redirect('surat');
            }
        } else {
            $data['warga'] = $this->Warga_model->get_all();
        }

        if($this->input->post()) {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('jenis_surat_id', 'Jenis Surat', 'required');
            $this->form_validation->set_rules('keperluan', 'Keperluan', 'required');

            if(is_admin()) {
                $this->form_validation->set_rules('warga_id', 'Warga', 'required');
            }

            if($this->form_validation->run()) {
                if(is_warga()) {
                    $warga_id = $data['warga_saya']->id;
                } else {
                    $warga_id = $this->input->post('warga_id');
                }

                $insert_data = array(
                    'warga_id'           => $warga_id,
                    'jenis_surat_id'     => $this->input->post('jenis_surat_id'),
                    'keperluan'          => $this->input->post('keperluan'),
                    'status'             => 'pending',
                    'tanggal_permohonan' => date('Y-m-d'),
                );

                if(!empty($_FILES['dokumen']['name'])) {
                    $config['upload_path']   = './uploads/surat/';
                    $config['allowed_types'] = 'jpg|jpeg|png|pdf';
                    $config['max_size']      = 2048;
                    $config['file_name']     = 'surat_' . time();

                    if(!is_dir($config['upload_path'])) {
                        mkdir($config['upload_path'], 0777, true);
                    }

                    $this->load->library('upload', $config);

                    if($this->upload->do_upload('dokumen')) {
                        $upload_data = $this->upload->data();
                        $insert_data['file_surat'] = $upload_data['file_name'];
                    } else {
                        $this->session->set_flashdata('error', 'Gagal upload dokumen: ' . $this->upload->display_errors());
                        redirect('surat/ajukan');
                        return;
                    }
                }

                if($this->Surat_model->insert($insert_data)) {
                    $this->session->set_flashdata('success', 'Pengajuan surat berhasil! Menunggu persetujuan admin.');
                    redirect('surat');
                } else {
                    $this->session->set_flashdata('error', 'Gagal mengajukan surat!');
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('surat/ajukan', $data);
        $this->load->view('templates/footer');
    }

    public function proses($id) {
        require_admin();

        $surat = $this->Surat_model->get_by_id($id);

        if(!$surat) {
            $this->session->set_flashdata('error', 'Data surat tidak ditemukan!');
            redirect('surat');
            return;
        }

        if($surat->status != 'pending') {
            $this->session->set_flashdata('error', 'Surat sudah diproses sebelumnya!');
            redirect('surat/detail/' . $id);
            return;
        }

        $nomor_surat = $this->Surat_model->generate_nomor_surat($surat->jenis_surat_id);

        $update_data = array(
            'status'          => 'selesai',
            'nomor_surat'     => $nomor_surat,
            'tanggal_selesai' => date('Y-m-d'),
            'diproses_oleh'   => $this->session->userdata('user_id'),
        );

        if($this->Surat_model->update($id, $update_data)) {
            $this->session->set_flashdata('success', 'Surat berhasil disetujui! Nomor: ' . $nomor_surat);
            redirect('surat/detail/' . $id);
        } else {
            $this->session->set_flashdata('error', 'Gagal memproses surat!');
            redirect('surat/detail/' . $id);
        }
    }

    public function tolak($id) {
        require_admin();

        $surat = $this->Surat_model->get_by_id($id);

        if(!$surat) {
            $this->session->set_flashdata('error', 'Data surat tidak ditemukan!');
            redirect('surat');
            return;
        }

        if($surat->status != 'pending') {
            $this->session->set_flashdata('error', 'Surat sudah diproses sebelumnya!');
            redirect('surat/detail/' . $id);
            return;
        }

        $update_data = array(
            'status'               => 'ditolak',
            'keterangan_penolakan' => $this->input->post('keterangan_penolakan'),
            'tanggal_selesai'      => date('Y-m-d'),
            'diproses_oleh'        => $this->session->userdata('user_id'),
        );

        if($this->Surat_model->update($id, $update_data)) {
            $this->session->set_flashdata('success', 'Permohonan surat ditolak!');
            redirect('surat/detail/' . $id);
        } else {
            $this->session->set_flashdata('error', 'Gagal menolak surat!');
            redirect('surat/detail/' . $id);
        }
    }

    public function print_surat($id) {
        $redirect_to = 'surat/detail/' . $id;

        $surat = $this->Surat_model->get_by_id($id);

        if(!$surat) {
            $this->session->set_flashdata('error', 'Data surat tidak ditemukan!');
            redirect('surat');
            return;
        }

        // Cek kepemilikan untuk warga
        // Cast ke (int) agar tidak gagal karena perbedaan tipe string vs int dari MySQL
        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga   = $this->Warga_model->get_by_user_id($user_id);

            if(!$warga || (int)$surat->warga_id !== (int)$warga->id) {
                $this->session->set_flashdata('error', 'Anda tidak berhak mengakses surat ini!');
                redirect('surat');
                return;
            }
        }

        // Cek status surat
        if($surat->status != 'selesai') {
            $this->session->set_flashdata('error', 'Surat belum selesai diproses! Status: ' . ucfirst($surat->status));
            redirect($redirect_to);
            return;
        }

        // Cek nomor surat sudah ada
        if(empty($surat->nomor_surat)) {
            $this->session->set_flashdata('error', 'Nomor surat belum tersedia, hubungi admin!');
            redirect($redirect_to);
            return;
        }

        $data['surat']      = $surat;
        $data['pengaturan'] = $this->Pengaturan_model->get(); // load dari DB, dikirim ke view
        $data['title']      = 'Cetak Surat';

        $this->load->view('surat/print_surat', $data);
    }

    public function download($id) {
        redirect('surat/print_surat/' . $id);
    }

    public function detail($id) {
        $surat = $this->Surat_model->get_by_id($id);

        if(!$surat) {
            $this->session->set_flashdata('error', 'Data surat tidak ditemukan!');
            redirect('surat');
            return;
        }

        // Cek kepemilikan untuk warga
        // Cast ke (int) agar tidak gagal karena perbedaan tipe string vs int dari MySQL
        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga   = $this->Warga_model->get_by_user_id($user_id);

            if(!$warga || (int)$surat->warga_id !== (int)$warga->id) {
                $this->session->set_flashdata('error', 'Anda tidak berhak melihat surat ini!');
                redirect('surat');
                return;
            }
        }

        $data['title'] = 'Detail Surat';
        $data['surat'] = $surat;

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('surat/detail', $data);
        $this->load->view('templates/footer');
    }

    public function hapus($id) {
        require_admin();

        $surat = $this->Surat_model->get_by_id($id);

        if(!$surat) {
            $this->session->set_flashdata('error', 'Data surat tidak ditemukan!');
            redirect('surat');
            return;
        }

        // Hapus file jika ada
        if(!empty($surat->file_surat)) {
            $file_path = './uploads/surat/' . $surat->file_surat;
            if(file_exists($file_path)) {
                unlink($file_path);
            }
        }

        if($this->Surat_model->delete($id)) {
            $this->session->set_flashdata('success', 'Data surat berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus data!');
        }

        redirect('surat');
    }
}