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

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

/**
 * @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_Sejarah_model $sejarah_model
 */

class Api extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('santri_model'); // ini penting!
        $this->load->model('sejarah_model'); // ini penting!
    }

    public function loginWaliSantri()
    {
        // Ambil input JSON
        $post = json_decode(file_get_contents("php://input"), true);

        if (!$post) {
            echo json_encode([
                "status" => "failed",
                "message" => "Data tidak dikirim dengan benar."
            ]);
            return;
        }

        $email_or_NIS = $post['email_or_NIS'] ?? null;
        $password = $post['password'] ?? null;

        if (empty($email_or_NIS) || empty($password)) {
            echo json_encode([
                "status" => "failed",
                "message" => "Email/NIS dan password wajib diisi."
            ]);
            return;
        }

        // JOIN wali dan santri
        $this->db->select('tb_wali_santri.*, tb_santri.NIS, tb_santri.nama_santri as nama_santri, tb_santri.*');
        $this->db->from('tb_wali_santri');
        $this->db->join('tb_santri', 'tb_santri.id_santri = tb_wali_santri.id_santri');
        $this->db->group_start();
        $this->db->where('tb_wali_santri.email', $email_or_NIS);
        $this->db->or_where('tb_santri.NIS', $email_or_NIS);
        $this->db->group_end();
        $this->db->where('tb_wali_santri.password', $password); // pastikan field password sesuai

        $query = $this->db->get();
        $result = $query->row();

        if ($result) {
            $id_santri = $result->id_santri;

            // Ambil data terkait santri
            $prestasi = $this->db->get_where('tb_prestasi_santri', ['id_santri' => $id_santri])->result();
            $pelanggaran = $this->db->get_where('tb_pelanggaran_santri', ['id_santri' => $id_santri])->result();
            $spp = $this->db->get_where('tb_informasi_spp_santri', ['id_santri' => $id_santri])->result();

            // Data umum
            $kegiatan = $this->db->get('tb_kegiatan')->result();
            $berita = $this->db->get('tb_berita')->result();
            $sejarah = $this->db->get('tb_sejarah')->result();

            echo json_encode([
                "status" => "success",
                "wali_santri" => $result,
                "santri" => [
                    "id_santri" => $result->id_santri,
                    "NIS" => $result->NIS,
                    "nama" => $result->nama_santri
                ],
                "prestasi" => $prestasi,
                "pelanggaran" => $pelanggaran,
                "spp" => $spp,
                "kegiatan" => $kegiatan,
                "berita" => $berita,
                "sejarah" => $sejarah
            ]);
        } else {
            echo json_encode([
                "status" => "failed",
                "message" => "Email/NIS atau password salah."
            ]);
        }
    }
    public function getDataSantri()
    {
        $id_santri = $this->input->get('id_santri');
        $NIS = $this->input->get('NIS');
        $email = $this->input->get('email');

        if ($id_santri) {
            $data = $this->santri_model->get_data_by_id_santri($id_santri); // pastikan model ini ada
        } else if ($NIS) {
            $data = $this->santri_model->get_data_by_nis($NIS);
        } else if ($email) {
            $data = $this->santri_model->get_data_by_email_wali($email);
        } else {
            echo json_encode([
                "status" => false,
                "message" => "Parameter id_santri, NIS atau email harus diisi"
            ]);
            return;
        }

        if ($data) {
            echo json_encode([
                "status" => true,
                "data" => $data
            ]);
        } else {
            echo json_encode([
                "status" => false,
                "message" => "Data tidak ditemukan"
            ]);
        }
    }

    public function getSejarah()
    {
        $this->load->model('sejarah_model');

        $data = $this->sejarah_model->get_sejarah(); // ambil dari model

        if ($data) {
            echo json_encode([
                'status' => true,
                'data' => $data
            ]);
        } else {
            echo json_encode([
                'status' => false,
                'message' => 'Data sejarah tidak ditemukan'
            ]);
        }
    }
    public function getKegiatan()
    {
        $query = $this->db->get('tb_kegiatan');

        if ($query->num_rows() > 0) {
            $data = $query->result();

            echo json_encode([
                'status' => true,
                'data' => $data
            ]);
        } else {
            echo json_encode([
                'status' => false,
                'message' => 'Tidak ada kegiatan ditemukan'
            ]);
        }
    }

    public function getBerita()
    {
        $this->db->select('judul, tanggal, gambar, deskripsi');
        $this->db->from('tb_berita');
        $this->db->order_by('tanggal', 'DESC');

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $data = $query->result();

            // Tambahkan base URL agar Glide di Android bisa load gambarnya
            foreach ($data as &$row) {
                $row->gambar = base_url('assets/img/berita/' . $row->gambar);
            }

            echo json_encode([
                'status' => true,
                'data' => $data
            ]);
        } else {
            echo json_encode([
                'status' => false,
                'message' => 'Data berita tidak ditemukan'
            ]);
        }
    }
    // Kirim chat dari Android
    public function sendChat()
    {
        header('Content-Type: application/json');
        $sender = $this->input->post('sender'); // 'wali' atau 'admin'
        $id_wali_santri = $this->input->post('id_wali_santri');
        $message = $this->input->post('message');

        if (!$sender || !$id_wali_santri || !$message) {
            echo json_encode([
                'status' => false,
                'message' => 'Semua field wajib diisi.'
            ]);
            return;
        }

        $data = [
            'sender' => $sender,
            'id_wali_santri' => $id_wali_santri,
            'message' => $message
        ];

        $this->db->insert('chat', $data);

        echo json_encode([
            'status' => true,
            'message' => 'Pesan berhasil dikirim.'
        ]);
    }

    // Ambil chat berdasarkan wali santri (untuk Android)
    public function getChatByWali($id_wali_santri)
    {
        $this->db->select('chat.*, tb_wali_santri.nama_wali_santri, tb_santri.nama_santri');
        $this->db->from('chat');
        $this->db->join('tb_wali_santri', 'tb_wali_santri.id_wali_santri = chat.id_wali_santri');
        $this->db->join('tb_santri', 'tb_santri.id_santri = tb_wali_santri.id_santri');
        $this->db->where('chat.id_wali_santri', $id_wali_santri);
        $this->db->order_by('chat.timestamp', 'ASC');

        $query = $this->db->get();
        $result = $query->result();

        echo json_encode([
            'status' => true,
            'data' => $result
        ]);
    }
    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']);
        }
    }
}
