<?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_Wali_santri_model $wali_santri_model
 * @property CI_Santri_model $santri_model
 * @property CI_Chat_model $chat_model
 */

class WaliSantri extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('wali_santri_model');
        $this->load->model('santri_model');
        $this->load->model('chat_model');
        is_logged_in();
    }

    public function index()
    {
        $data['title'] = 'Wali Santri';
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();
        $data['santri'] = $this->wali_santri_model->get_all_santri(); // Tambahkan data santri
        $data['santri'] = $this->db->select('tb_santri.id_santri, tb_santri.NIS, tb_santri.nama_santri, tb_wali_santri.id_wali_santri, tb_wali_santri.nama_wali_santri, tb_wali_santri.alamat, tb_wali_santri.no_telepon, tb_wali_santri.email, tb_wali_santri.password, tb_wali_santri.pekerjaan')
            ->from('tb_santri')
            ->join('tb_wali_santri', 'tb_santri.id_santri = tb_wali_santri.id_santri', 'left')
            ->get()
            ->result();

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

    public function get_all_santri()
    {
        $this->db->select('tb_wali_santri.nama_wali_santri, tb_santri.nama_santri, tb_wali_santri.alamat, tb_wali_santri.no_telepon, tb_santri.id_santri');
        $this->db->from('tb_wali_santri');
        $this->db->join('tb_santri', 'tb_santri.id_santri = tb_wali_santri.id_santri');
        return $this->db->get()->result();
    }


    public function tambah($id_santri = null)
    {
        // Set judul halaman
        $data['title'] = 'Tambah Wali Santri';

        // Periksa apakah id_santri ada dan valid
        if ($id_santri && is_numeric($id_santri)) {
            // Ambil data santri berdasarkan id_santri dari model
            $santri = $this->santri_model->get_santri_by_id($id_santri);

            if ($santri) {
                $data['santri'] = $santri; // Berikan data santri jika ditemukan
            } else {
                $data['santri'] = null; // Set null jika data tidak ditemukan
                $this->session->set_flashdata('error', 'Data santri tidak ditemukan');
            }
        } else {
            $data['santri'] = null; // Set null jika id_santri tidak ada atau tidak valid
        }

        // Load view dengan data santri
        $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_wali_santri', $data); // Kirim data ke view
        $this->load->view('templates/footer');
    }

    public function tambah_aksi()
    {
        $id_santri = $this->input->post('id_santri');

        // Cek apakah wali santri dengan username ini sudah ada untuk santri tersebut
        if ($this->wali_santri_model->check_wali_exists($id_santri)) {
            $this->session->set_flashdata('pesan', '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                Wali santri sudah pernah ditambahkan! <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span></button></div>');
            redirect('santri');
        }
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->tambah();
        } else {
            // Cek apakah id_santri kosong
            $id_santri = $this->input->post('id_santri');
            if (empty($id_santri)) {
                $this->session->set_flashdata('error', 'Kesalahan: id_santri tidak boleh kosong!');
                redirect('walisantri');
                return;
            }
            $data = array(
                'email' => $this->input->post('email'),
                'password' => $this->input->post('password'),
                'nama_wali_santri' => $this->input->post('nama_wali_santri'),
                'id_santri' => $id_santri,
                // 'no_ktp' => $this->input->post('no_ktp'),
                // 'tempat_lahir' => $this->input->post('tempat_lahir'),
                // 'tanggal_lahir' => $this->input->post('tanggal_lahir'),
                'alamat' => $this->input->post('alamat'),
                'no_telepon' => $this->input->post('no_telepon'),
                'pekerjaan' => $this->input->post('pekerjaan'),
            );

            $this->wali_santri_model->insert_data($data, 'tb_wali_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('walisantri');
        }
    }

    public function edit($id_wali_santri = null)
    {
        $this->_rules();

        if ($id_wali_santri === null) {
            redirect('walisantri');
        } else {
            $data = array(
                'id_wali_santri' => $id_wali_santri,
                'email' => $this->input->post('email'),
                'password' => $this->input->post('password'),
                'nama_wali_santri' => $this->input->post('nama_wali_santri'),
                'id_santri' => $this->input->post('id_santri'),
                // 'no_ktp' => $this->input->post('no_ktp'),
                // 'tempat_lahir' => $this->input->post('tempat_lahir'),
                // 'tanggal_lahir' => $this->input->post('tanggal_lahir'),
                'alamat' => $this->input->post('alamat'),
                'no_telepon' => $this->input->post('no_telepon'),
                'pekerjaan' => $this->input->post('pekerjaan'),
            );
            $this->wali_santri_model->update_data($data, 'tb_wali_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('walisantri');
        }
    }

    public function view($id_santri)
    {
        // Load model jika belum diload
        $this->load->model('wali_santri_model');

        // Ambil data wali santri berdasarkan id_santri dari model
        $data['santri'] = $this->wali_santri_model->get_santri_by_id($id_santri);

        // Periksa apakah data ditemukan
        if ($data['santri']) {
            // Kirim data ke view untuk ditampilkan dalam modal
            $this->load->view('wali_santri', $data);
        } else {
            // Jika data tidak ditemukan, redirect ke halaman utama dengan pesan error
            $this->session->set_flashdata('pesan', 'Data wali santri tidak ditemukan');
            redirect('admin/santri');  // Ubah sesuai route halaman utama Anda
        }
    }


    private function _rules()
    {
        $this->form_validation->set_rules('email', 'Email', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('password', 'Password', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('nama_wali_santri', 'Nama Wali Santri', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        // $this->form_validation->set_rules('no_ktp', 'No KTP', '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', 'Alamat', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('no_telepon', 'No Telepon', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('pekerjaan', 'Pekerjaan', 'required', array(
            'required' => '%s harus diisi!!'
        ));
    }

    public function chatAdmin($id_wali_santri = null)
    {
        $data['title'] = 'Halaman Pesan';
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();
        $data['chat'] = $this->chat_model->getChatByWali($id_wali_santri);
        $data['id_wali_santri'] = $id_wali_santri;

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

    public function sendChatFromAdmin()
    {
        $id_wali_santri = $this->input->post('id_wali_santri');
        $message = $this->input->post('message');
        $sender = 'admin';

        if ($id_wali_santri && $message) {
            $this->chat_model->insertChat($id_wali_santri, $sender, $message);
            redirect('chat/chatadmin/' . $id_wali_santri);
        } else {
            show_error('Input tidak lengkap!');
        }
    }

    public function saveToken()
    {
        $input = json_decode(file_get_contents("php://input"), true);
        $id_wali_santri = $input['id_wali_santri'];
        $token = $input['token'];

        if ($id_wali_santri && $token) {
            $data = [
                'id_wali_santri' => $id_wali_santri,
                'token' => $token,
                'created_at' => date('Y-m-d H:i:s')
            ];

            // Jika sudah ada token, update
            $existing = $this->db->get_where('fcm_tokens', ['id_wali_santri' => $id_wali_santri])->row();
            if ($existing) {
                $this->db->where('id_wali_santri', $id_wali_santri)->update('fcm_tokens', $data);
            } else {
                $this->db->insert('fcm_tokens', $data);
            }

            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'failed']);
        }
    }
}
