<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\StudentModel;
use App\Models\StudentAcademicHistoryModel;

class StudentHistory extends BaseController
{
    protected $studentModel;
    protected $historyModel;

    public function __construct()
    {
        $this->studentModel = new StudentModel();
        $this->historyModel = new StudentAcademicHistoryModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $data = [
            'title' => 'Riwayat Siswa',
        ];

        return view('student_history/index', $data);
    }

    // AJAX — cari siswa by NIS/NISN/nama
    public function search()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $keyword = $this->request->getGet('q');

        if (empty($keyword)) {
            return $this->response->setJSON([
                'success'  => false,
                'students' => [],
            ]);
        }

        $db      = \Config\Database::connect();
        $students = $db->table('students')
            ->select('id, nis, nisn, full_name, gender, entry_year, status')
            ->where('deleted_at', null)
            ->groupStart()
                ->like('nis', $keyword)
                ->orLike('nisn', $keyword)
                ->orLike('full_name', $keyword)
            ->groupEnd()
            ->orderBy('full_name', 'ASC')
            ->limit(20)
            ->get()
            ->getResultArray();

        return $this->response->setJSON([
            'success'  => true,
            'students' => $students,
        ]);
    }

    // AJAX — ambil riwayat akademik siswa
    public function history($studentId)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $student  = $this->studentModel->find($studentId);
        if (!$student) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Siswa tidak ditemukan',
            ]);
        }

        $histories = $this->historyModel->getByStudent($studentId);

        return $this->response->setJSON([
            'success'   => true,
            'student'   => $student,
            'histories' => $histories,
        ]);
    }
}