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

/**
 * @property CI_Db $db
 * @property CI_Session $session
 * @property CI_Form_validation $form_validation
 * @property CI_Input $input
 * @property CI_Santri_model $santri_model
 */

use Dompdf\Dompdf;
use Dompdf\Options;

class Santri extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('santri_model');
        is_logged_in();
    }
    public function index()
    {
        $data['title'] = 'Santri';
        $data['santri'] = $this->santri_model->get_data('tb_santri')->result();
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

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

    public function tambah()
    {
        $data['title'] = 'Tambah Santri';
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

        // Pastikan $data['id_santri'] memiliki nilai unik, misalnya berdasarkan jumlah santri yang sudah ada
        $data['id_santri'] = $this->db->select_max('id_santri')->get('tb_santri')->row()->id_santri + 1;

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

    public function print()
    {
        $data['santri'] = $this->santri_model->get_data('tb_santri')->result();
        $this->load->view('admin/print_santri', $data);
    }

    public function pdf()
    {
        // Buat instance baru Dompdf dan set opsi jika diperlukan
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true); // Mengaktifkan parser HTML5
        $dompdf = new Dompdf($options);

        // Ambil data santri dari model
        $data['santri'] = $this->santri_model->get_data('tb_santri')->result();

        // Load view laporan_santri dan simpan output HTML ke dalam variabel
        $html = $this->load->view('admin/laporan_santri', $data, true);

        // Atur ukuran kertas dan orientasi
        $dompdf->setPaper('legal', 'portrait'); // Pilih 'portrait' atau 'landscape'

        // Muat konten HTML ke dalam Dompdf
        $dompdf->loadHtml($html);

        // Render konten HTML menjadi PDF
        $dompdf->render();

        // Stream atau unduh file PDF
        $dompdf->stream('laporan_santri.pdf', array("Attachment" => 0)); // Attachment=0 untuk menampilkan di browser
    }

    public function tambah_aksi()
    {
        // Ambil NIS dari input form
        $NIS = $this->input->post('NIS');

        // Cek apakah NIS sudah ada di database
        if ($this->santri_model->check_nis_exists($NIS)) {
            $this->session->set_flashdata('pesan', '<div class="alert alert-danger alert-dismissible fade show" role="alert">
            NIS sudah pernah ditambahkan! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> 
            <span aria-hidden="true">&times;</span></button></div>');
            redirect('santri/tambah');
        }
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->tambah();
        } else {
            $tanggal_input = $this->input->post('tanggal_lahir');
            $tanggal_formatted = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_input)));
            $data = array(
                'NIS' => $this->input->post('NIS'),
                'nama_santri' => $this->input->post('nama_santri'),
                'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                'status_santri' => $this->input->post('status_santri'),
                'kondisi_kesehatan' => $this->input->post('kondisi_kesehatan'),
                'tahun_masuk' => $this->input->post('tahun_masuk'),
                'tahun_keluar' => $this->input->post('tahun_keluar'),
                'keterangan_keluar' => $this->input->post('keterangan_keluar'),
                'tempat_lahir' => $this->input->post('tempat_lahir'),
                'tanggal_lahir' => $tanggal_formatted,
                'alamat_santri' => $this->input->post('alamat_santri'),
            );

            $this->santri_model->insert_data($data, 'tb_santri');
            $this->session->set_flashdata('pesan', '<div class="alert alert-success alert-dismissible fade show" role="alert">
            Data berhasil ditambahkan! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span>
            </button></div>');
            redirect('santri');
        }
    }

    public function edit($id_santri)
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->index();
        } else {
            $tanggal_input = $this->input->post('tanggal_lahir');
            $tanggal_formatted = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_input)));

            // Ambil nilai dari form
            $id_santri = $this->input->post('id_santri');
            $namaSantri = $this->input->post('nama_santri');
            $kondisi_kesehatan = $this->input->post('kondisi_kesehatan');

            $data = array(
                'id_santri' => $id_santri,
                'NIS' => $this->input->post('NIS'),
                'nama_santri' => $namaSantri,
                'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                'status_santri' => $this->input->post('status_santri'),
                'kondisi_kesehatan' => $kondisi_kesehatan,
                'tahun_masuk' => $this->input->post('tahun_masuk'),
                'tahun_keluar' => $this->input->post('tahun_keluar'),
                'keterangan_keluar' => $this->input->post('keterangan_keluar'),
                'tempat_lahir' => $this->input->post('tempat_lahir'),
                'tanggal_lahir' => $tanggal_formatted,
                'alamat_santri' => $this->input->post('alamat_santri'),
            );

            // Update data santri
            $this->santri_model->update_data($data, 'tb_santri');

            // Jika kondisi_kesehatan = sehat atau sakit, kirim notifikasi ke wali
            if ($kondisi_kesehatan == "Dalam Kondisi Sehat" || $kondisi_kesehatan == "Dalam Kondisi Sakit") {
                $wali = $this->db->get_where('tb_wali_santri', ['id_santri' => $id_santri])->row();
                if ($wali) {
                    $token = $this->db->get_where('fcm_tokens', ['id_wali_santri' => $wali->id_wali_santri])->row('token');
                    if ($token) {
                        $title = 'Kondisi Kesehatan';
                        $body  = $namaSantri . ' ' . $kondisi_kesehatan;

                        // Load dan kirim notifikasi
                        $this->load->library('notif');
                        $notif = new Notif();
                        $response = $notif->send($token, $title, $body);

                        log_message('debug', 'RESPON FCM: ' . print_r($response, true));
                    }
                }
            }

            // Flash pesan berhasil
            $this->session->set_flashdata('pesan', '<div class="alert alert-success alert-dismissible fade show" role="alert">
            Data berhasil diubah! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> 
            <span aria-hidden="true">&times;</span></button></div>');

            redirect('santri');
        }
    }

    public function _rules()
    {
        $this->form_validation->set_rules('NIS', 'NIS', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('nama_santri', 'Nama Santri', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('kelas_diniyah', 'Kelas Diniyah', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('status_santri', 'Status Santri', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('kondisi_kesehatan', 'Kondisi Kesehatan', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tahun_masuk', 'Tahun Masuk', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tempat_lahir', 'Tempat Lahir', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('alamat_santri', 'Alamat Santri', 'required', array(
            'required' => '%s harus diisi!!'
        ));
    }

    public function delete($id)
    {
        $where = array('id_santri' => $id);

        $this->santri_model->delete($where, 'tb_santri');
        $this->session->set_flashdata('pesan', '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                Data berhasil dihapus! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span>
                </button></div>');
        redirect('santri');
    }
}
