<?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_Pelanggaran_santri_model $pelanggaran_santri_model
 */

use Dompdf\Dompdf;
use Dompdf\Options;

class PelanggaranSantri extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('pelanggaran_santri_model');
        $this->load->library('notif'); // load library Notif
        is_logged_in();
    }

    public function index()
    {
        $data['title'] = 'Pelanggaran Santri';
        $data['pelanggaransantri'] = $this->pelanggaran_santri_model->get_data('tb_pelanggaran_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/pelanggaran_santri');
        $this->load->view('templates/footer');
    }

    public function tambah()
    {
        $data['title'] = 'Tambah Pelanggaran Santri';
        $data['pelanggaransantri'] = $this->pelanggaran_santri_model->get_data('tb_pelanggaran_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/tambah_pelanggaran_santri', $data);
        $this->load->view('templates/footer');
    }

    public function print()
    {
        // Ambil input dari form
        $start_input = $this->input->get('start_date');
        $end_input = $this->input->get('end_date');

        // Ubah format dari dd/mm/yyyy ke Y-m-d
        if (!empty($start_input) && !empty($end_input)) {
            $start = date('Y-m-d', strtotime(str_replace('/', '-', $start_input)));
            $end = date('Y-m-d', strtotime(str_replace('/', '-', $end_input)));

            // Filter berdasarkan tanggal
            $data['pelanggaransantri'] = $this->pelanggaran_santri_model->get_filtered_data($start, $end);
        } else {
            // Ambil semua data jika tidak ada filter
            $data['pelanggaransantri'] = $this->db->get('tb_pelanggaran_santri')->result();
        }

        $this->load->view('admin/print_pelanggaran_santri', $data);
    }


    public function pdf()
    {
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $dompdf = new Dompdf($options);

        // Ambil input tanggal dari GET
        $tanggal_awal_input = $this->input->get('start_date');
        $tanggal_akhir_input = $this->input->get('end_date');

        // Format ulang dari dd/mm/yyyy ke Y-m-d
        if (!empty($tanggal_awal_input) && !empty($tanggal_akhir_input)) {
            $tgl_awal = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_awal_input)));
            $tgl_akhir = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_akhir_input)));

            // Filter berdasarkan tanggal yang sudah diformat
            $this->db->where('tanggal >=', $tgl_awal);
            $this->db->where('tanggal <=', $tgl_akhir);
        }

        $data['pelanggaransantri'] = $this->db->get('tb_pelanggaran_santri')->result();

        $html = $this->load->view('admin/data_pelanggaran_santri', $data, true);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->loadHtml($html);
        $dompdf->render();
        $dompdf->stream('pelanggaran_santri.pdf', array("Attachment" => 0));
    }


    public function tambah_aksi()
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->tambah();
        } else {

            $tanggal_input = $this->input->post('tanggal');
            $tanggal_formatted = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_input)));
            $data = array(
                'id_santri' => $this->input->post('id_santri'),
                'NIS' => $this->input->post('NIS'),
                'nama_santri' => $this->input->post('nama_santri'),
                'kelas_diniyah' => intval($this->input->post('kelas_diniyah')),
                'pelanggaran' => $this->input->post('pelanggaran'),
                'tanggal' => $tanggal_formatted,
                'sanksi' => $this->input->post('sanksi'),
                'keterangan' => $this->input->post('keterangan')
            );

            $this->pelanggaran_santri_model->insert_data($data, 'tb_pelanggaran_santri');

            $id_santri = $this->input->post('id_santri');
            $namaSantri = $this->input->post('nama_santri');
            // Kirim notifikasi FCM ke wali santri jika token tersedia
            $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 = 'Nufaku - Pelanggaran Baru';
                    $body  = $namaSantri . ' melakukan pelanggaran baru';

                    $host = $_SERVER['HTTP_HOST'];
                    if (strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false) {
                        $host = '192.168.0.80:8080'; // Ganti sesuai IP kamu
                    }

                    $this->load->library('notif');
                    $notif = new Notif();

                    $title = 'Nufaku - Pelanggaran Baru';
                    $body  = $namaSantri . ' melakukan pelanggaran baru';

                    // Tambahkan payload
                    $dataPayload = [
                        'type' => 'pelanggaran',
                        'id_santri' => $id_santri,
                        'nama_santri' => $namaSantri,
                        'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                        'pelanggaran' => $this->input->post('pelanggaran'),
                        'tanggal' => $tanggal_formatted,
                        'sanksi' => $this->input->post('sanksi'),
                        'keterangan' => $this->input->post('keterangan'),
                        'from_notif' => 'true'
                    ];

                    $response = $notif->send($token, $title, $body, $dataPayload);
                    log_message('debug', 'RESPON FCM: ' . print_r($response, true));
                }
            }

            $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('pelanggaransantri');
        }
    }

    public function get_nis_autocomplete()
    {
        $term = $this->input->get('term');
        $this->db->like('NIS', $term);
        $this->db->or_like('nama_santri', $term);
        $query = $this->db->get('tb_santri');

        $result = [];
        $kelas_diniyah = [
            1 => 'Al-Wadhih Banin',
            2 => 'Al-Wadhih Banat',
            3 => 'Al-Jurūmiyyah Banin',
            4 => 'Al-Jurūmiyyah Banat',
            5 => 'Al-Imriti Banin',
            6 => 'Al-Imriti Banat',
            7 => 'Alfiyah Ula Banin',
            8 => 'Alfiyah Ula Banat',
            9 => 'Alfiyah Tsani Banin',
            10 => 'Alfiyah Tsani Banat',
            11 => 'Alfiyah Tsalits Banin',
            12 => 'Alfiyah Tsalits Banat'
        ];
        foreach ($query->result() as $row) {
            $kelas_diniyah_text = isset($kelas_diniyah[$row->kelas_diniyah]) ? $kelas_diniyah[$row->kelas_diniyah] : 'Tidak Diketahui';
            $result[] = [
                'label' => $row->NIS . ' - ' . $row->nama_santri . ' (' . $kelas_diniyah_text . ')',
                'value' => $row->NIS,
                'nama_santri' => $row->nama_santri,
                'id_santri' => $row->id_santri,
                'kelas_diniyah' => $kelas_diniyah_text, // Kirim teksnya ke JS, bukan angkanya
                'kelas_diniyah_id' => $row->kelas_diniyah // untuk disimpan ke DB
            ];
        }

        echo json_encode($result);
    }

    public function view($id_santri)
    {
        $data['title'] = 'Pelanggaran Santri';
        $data['santri'] = $this->db->get_where('tb_santri', ['id_santri' => $id_santri])->row();
        $data['pelanggaransantri'] = $this->pelanggaran_santri_model->get_pelanggaran_by_santri($id_santri);
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

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

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

        if ($this->form_validation->run() == FALSE) {
            $this->index();
        } else {

            $tanggal_input = $this->input->post('tanggal');
            $tanggal_formatted = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_input)));
            $data = array(
                'id_pelanggaran_santri' => $id_pelanggaran_santri,
                'NIS' => $this->input->post('NIS'),
                'nama_santri' => $this->input->post('nama_santri'),
                'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                'pelanggaran' => $this->input->post('pelanggaran'),
                'tanggal' => $tanggal_formatted,
                'sanksi' => $this->input->post('sanksi'),
                'keterangan' => $this->input->post('keterangan')
            );

            $this->pelanggaran_santri_model->update_data($data, 'tb_pelanggaran_santri');

            $id_santri = $this->input->post('id_santri');
            $namaSantri = $this->input->post('nama_santri');
            // Kirim notifikasi FCM ke wali santri jika token tersedia
            $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');
                log_message('debug', 'TOKEN FCM DITEMUKAN: ' . $token);
                if ($token) {
                    $title = 'Nufaku - Pelanggaran Baru';
                    $body  = $namaSantri . ' melakukan pelanggaran baru';

                    $host = $_SERVER['HTTP_HOST'];
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

                    // URL backend (digunakan misal dalam notifikasi FCM yang arahkan ke web)
                    $baseUrl = $protocol . $host . base_url(); // base_url() sudah dinamis jika config-nya sudah benar

                    // Jika butuh URL API manual (misalnya untuk disisipkan dalam payload FCM), contoh:
                    $urlApi = $protocol . $host . '/admin-nufa/api/';

                    $this->load->library('notif');
                    $notif = new Notif();
                    $title = 'Nufaku - Pembaruan Pelanggaran';
                    $body  = 'Data pelanggaran milik ' . $namaSantri . ' telah diperbarui';

                    // Tambahkan payload
                    $dataPayload = [
                        'type' => 'pelanggaran',
                        'id_santri' => $id_santri,
                        'login_key' => 'id_santri',
                        'login_value' => $id_santri,
                        'nama_santri' => $namaSantri,
                        'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                        'pelanggaran' => $this->input->post('pelanggaran'),
                        'tanggal' => $tanggal_formatted,
                        'sanksi' => $this->input->post('sanksi'),
                        'keterangan' => $this->input->post('keterangan'),
                        'from_notif' => 'true',
                        'detail_url' => $baseUrl . 'pelanggaransantri/detail/' . $id_santri, // misal untuk Android nanti
                        'api_url' => $urlApi . 'getDataSantri?id_santri=' . $id_santri
                    ];

                    $response = $notif->send($token, $title, $body, $dataPayload);
                    log_message('debug', 'RESPON FCM: ' . print_r($response, true));
                }
            }

            $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('pelanggaransantri');
        }
    }

    public function rekap()
    {
        $data['title'] = 'Rekap Pelanggaran Santri';

        // Ambil semua data pelanggaran
        $pelanggaransantri = $this->pelanggaran_santri_model->get_data('tb_pelanggaran_santri')->result();

        // Proses pengelompokan
        $rekap = [];
        foreach ($pelanggaransantri as $row) {
            $nis = $row->NIS;

            if (!isset($rekap[$nis])) {
                $rekap[$nis] = [
                    'NIS' => $row->NIS,
                    'nama_santri' => $row->nama_santri,
                    'kelas_diniyah' => $row->kelas_diniyah,
                    'jumlah_pelanggaran' => 0,
                    'sanksi_ada' => [],
                    'sanksi_kosong' => []
                ];
            }

            $rekap[$nis]['jumlah_pelanggaran']++;

            if (!empty($row->sanksi)) {
                $rekap[$nis]['sanksi_ada'][] = $row->sanksi;
            } else {
                $rekap[$nis]['sanksi_kosong'][] = $row->pelanggaran;
            }
        }

        $data['rekap'] = $rekap;
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

        // Load tampilan rekap
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('admin/rekap_pelanggaran', $data);
        $this->load->view('templates/footer');
    }

    public function rekap_pdf()
    {
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $dompdf = new Dompdf($options);

        // Ambil data pelanggaran dan rekap
        $pelanggaransantri = $this->pelanggaran_santri_model->get_data('tb_pelanggaran_santri')->result();

        $rekap = [];
        foreach ($pelanggaransantri as $row) {
            $nis = $row->NIS;

            if (!isset($rekap[$nis])) {
                $rekap[$nis] = [
                    'NIS' => $row->NIS,
                    'nama_santri' => $row->nama_santri,
                    'kelas_diniyah' => $row->kelas_diniyah,
                    'jumlah_pelanggaran' => 0,
                    'sanksi_ada' => [],
                    'sanksi_kosong' => []
                ];
            }

            $rekap[$nis]['jumlah_pelanggaran']++;

            if (strtolower(trim($row->keterangan)) == 'sudah disanksi') {
                $rekap[$nis]['sanksi_ada'][] = $row->sanksi;
            } else {
                $rekap[$nis]['sanksi_kosong'][] = $row->sanksi;
            }
        }


        $data['rekap'] = $rekap;

        // Load HTML view sebagai string
        $html = $this->load->view('admin/rekap_pelanggaran', $data, true);

        $dompdf->setPaper('A4', 'landscape');
        $dompdf->loadHtml($html);
        $dompdf->render();
        $dompdf->stream('rekap_pelanggaran_santri.pdf', array("Attachment" => false));
    }


    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|numeric|greater_than[0]', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('pelanggaran', 'Pelanggaran', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tanggal', 'Tanggal', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('sanksi', 'Sanksi', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('keterangan', 'Keterangan', 'required', array(
            'required' => '%s harus diisi!!'
        ));
    }

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

        $this->pelanggaran_santri_model->delete($where, 'tb_pelanggaran_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('pelanggaransantri');
    }
}
