<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentAcademicHistoryModel extends Model
{
    protected $table            = 'student_academic_histories';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'student_id', 'academic_period_id', 'classroom_id', 'status', 'notes'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    public function getByStudent($studentId)
    {
        return $this->select('
                student_academic_histories.*,
                academic_periods.semester,
                academic_years.name as year_name,
                classrooms.name as classroom_name,
                grades.name as grade_name
            ')
            ->join('academic_periods', 'academic_periods.id = student_academic_histories.academic_period_id')
            ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('student_academic_histories.student_id', $studentId)
            ->orderBy('academic_years.name', 'DESC')
            ->orderBy('academic_periods.semester', 'ASC')
            ->findAll();
    }

    public function getByPeriod($periodId)
    {
        return $this->select('
                student_academic_histories.*,
                students.nis,
                students.nisn,
                students.full_name,
                students.gender,
                classrooms.name as classroom_name,
                grades.name as grade_name
            ')
            ->join('students', 'students.id = student_academic_histories.student_id')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('student_academic_histories.academic_period_id', $periodId)
            ->where('students.deleted_at', null)
            ->orderBy('grades.order', 'ASC')
            ->orderBy('classrooms.name', 'ASC')
            ->orderBy('students.full_name', 'ASC')
            ->findAll();
    }

    public function getCurrentClass($studentId, $periodId)
    {
        return $this->where('student_id', $studentId)
                    ->where('academic_period_id', $periodId)
                    ->first();
    }
}