<?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_Prestasi_santri_model $prestasi_santri_model
 */

use Dompdf\Dompdf;
use Dompdf\Options;

class PrestasiSantri extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('prestasi_santri_model');
        is_logged_in();
    }

    public function index()
    {
        $data['title'] = 'Prestasi Santri';
        $data['prestasisantri'] = $this->prestasi_santri_model->get_data('tb_prestasi_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/prestasi_santri');
        $this->load->view('templates/footer');
    }

    public function tambah()
    {
        $data['title'] = 'Tambah Prestasi Santri';
        $data['prestasisantri'] = $this->prestasi_santri_model->get_data('tb_prestasi_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_prestasi_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['prestasisantri'] = $this->prestasi_santri_model->get_filtered_data($start, $end);
        } else {
            // Ambil semua data jika tidak ada filter
            $data['prestasisantri'] = $this->db->get('tb_prestasi_santri')->result();
        }

        $this->load->view('admin/print_prestasi_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['prestasisantri'] = $this->db->get('tb_prestasi_santri')->result();

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


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

        if ($this->form_validation->run() == FALSE) {
            $this->tambah();
        } else {
            $bukti = $this->input->post('bukti_prestasi');
            $valid = false;

            if (strpos($bukti, '/d/') !== false) {
                $parts = explode('/d/', $bukti);
                if (count($parts) > 1 && strpos($parts[1], '/') !== false) {
                    $valid = true;
                }
            } elseif (strpos($bukti, 'id=') !== false) {
                $parsedUrl = parse_url($bukti);
                if (isset($parsedUrl['query'])) {
                    parse_str($parsedUrl['query'], $queryParams);
                    if (isset($queryParams['id']) && !empty($queryParams['id'])) {
                        $valid = true;
                    }
                }
            }

            if (!$valid && !empty($bukti)) {
                $this->session->set_flashdata('pesan', '
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    Link file tidak valid! Pastikan menggunakan format Google Drive seperti 
                    <code>https://drive.google.com/file/d/FILE_ID/view</code> atau <code>?id=FILE_ID</code>.
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>');
                redirect('prestasisantri/tambah');
                return;
            }

            // Lanjut simpan jika valid
            $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' => $this->input->post('kelas_diniyah'),
                'prestasi' => $this->input->post('prestasi'),
                'perlombaan' => $this->input->post('perlombaan'),
                'agenda' => $this->input->post('agenda'),
                'tanggal' => $tanggal_formatted,
                'bukti_prestasi' => $bukti,
            );

            $this->prestasi_santri_model->insert_data($data, 'tb_prestasi_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('prestasisantri');
        }
    }


    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'] = 'Prestasi Santri';
        $data['santri'] = $this->db->get_where('tb_santri', ['id_santri' => $id_santri])->row();
        $data['prestasisantri'] = $this->prestasi_santri_model->get_prestasi_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_prestasi_santri', $data);
        $this->load->view('templates/footer');
    }

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

        if ($this->form_validation->run() == FALSE) {
            $this->index();
        } else {
            $bukti = $this->input->post('bukti_prestasi');
            $valid = false;

            if (strpos($bukti, '/d/') !== false) {
                $parts = explode('/d/', $bukti);
                if (count($parts) > 1 && strpos($parts[1], '/') !== false) {
                    $valid = true;
                }
            } elseif (strpos($bukti, 'id=') !== false) {
                $parsedUrl = parse_url($bukti);
                if (isset($parsedUrl['query'])) {
                    parse_str($parsedUrl['query'], $queryParams);
                    if (isset($queryParams['id']) && !empty($queryParams['id'])) {
                        $valid = true;
                    }
                }
            }

            if (!$valid && !empty($bukti)) {
                $this->session->set_flashdata('pesan', '
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    Link file tidak valid! Pastikan menggunakan format Google Drive seperti 
                    <code>https://drive.google.com/file/d/FILE_ID/view</code> atau <code>?id=FILE_ID</code>.
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>');
                redirect('prestasisantri');
                return;
            }

            $tanggal_input = $this->input->post('tanggal');
            $tanggal_formatted = date('Y-m-d', strtotime(str_replace('/', '-', $tanggal_input))); // Format aman untuk MySQL

            $data = array(
                'id_prestasi_santri' => $id_prestasi_santri,
                'NIS' => $this->input->post('NIS'),
                'nama_santri' => $this->input->post('nama_santri'),
                'kelas_diniyah' => $this->input->post('kelas_diniyah'),
                'prestasi' => $this->input->post('prestasi'),
                'perlombaan' => $this->input->post('perlombaan'),
                'agenda' => $this->input->post('agenda'),
                'tanggal' => $tanggal_formatted, // Sudah diformat dengan aman
                'bukti_prestasi' => $bukti
            );

            $this->prestasi_santri_model->update_data($data, 'tb_prestasi_santri');
            $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('prestasisantri');
        }
    }


    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('prestasi', 'Prestasi', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('agenda', 'Agenda', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('perlombaan', 'Perlombaan', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tanggal', 'Tanggal', 'required', array(
            'required' => '%s harus diisi!!'
        ));
    }

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

        $this->prestasi_santri_model->delete($where, 'tb_prestasi_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('prestasisantri');
    }
}
