<?php

namespace App\Models;

use CodeIgniter\Model;

class TeachingJournalModel extends Model
{
    protected $table            = 'teaching_journals';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'teacher_id', 'academic_period_id', 'classroom_id', 'school_subject_id',
        'meeting_date', 'start_period', 'end_period', 'meeting_number',
        'topic', 'tp_ids', 'notes',
        'total_students', 'total_present', 'total_sick', 'total_permit', 'total_absent',
        'is_final',
    ];

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

    /**
     * Hitung pertemuan ke- berikutnya untuk kelas+mapel+periode tertentu
     */
    public function getNextMeetingNumber(int $teacherId, int $periodId, int $classroomId, int $subjectId): int
    {
        $last = $this->where('teacher_id', $teacherId)
            ->where('academic_period_id', $periodId)
            ->where('classroom_id', $classroomId)
            ->where('school_subject_id', $subjectId)
            ->orderBy('meeting_number', 'DESC')
            ->first();

        return $last ? (int)$last['meeting_number'] + 1 : 1;
    }

    /**
     * Daftar jurnal milik guru tertentu
     */
    public function getByTeacher(int $teacherId, ?int $periodId = null, ?int $classroomId = null, ?int $subjectId = null, ?string $search = null)
    {
        $builder = $this->select('
                teaching_journals.*,
                classrooms.name AS classroom_name,
                school_subjects.name AS subject_name,
                academic_periods.semester
            ')
            ->join('classrooms', 'classrooms.id = teaching_journals.classroom_id')
            ->join('school_subjects', 'school_subjects.id = teaching_journals.school_subject_id')
            ->join('academic_periods', 'academic_periods.id = teaching_journals.academic_period_id')
            ->where('teaching_journals.teacher_id', $teacherId)
            ->where('teaching_journals.deleted_at', null)
            ->orderBy('teaching_journals.meeting_date', 'DESC')
            ->orderBy('teaching_journals.created_at', 'DESC');

        if ($periodId) {
            $builder->where('teaching_journals.academic_period_id', $periodId);
        }
        if ($classroomId) {
            $builder->where('teaching_journals.classroom_id', $classroomId);
        }
        if ($subjectId) {
            $builder->where('teaching_journals.school_subject_id', $subjectId);
        }
        if ($search) {
            $builder->groupStart()
                ->like('teaching_journals.topic', $search)
                ->orLike('classrooms.name', $search)
                ->orLike('school_subjects.name', $search)
                ->groupEnd();
        }

        return $builder->findAll();
    }

    /**
     * Detail jurnal dengan join lengkap (untuk cetak / edit)
     */
    public function getDetail(int $id, ?int $teacherId = null)
    {
        $builder = $this->select('
                teaching_journals.*,
                classrooms.name AS classroom_name,
                school_subjects.name AS subject_name,
                academic_periods.semester,
                academic_years.name AS academic_year_name
            ')
            ->join('classrooms', 'classrooms.id = teaching_journals.classroom_id')
            ->join('school_subjects', 'school_subjects.id = teaching_journals.school_subject_id')
            ->join('academic_periods', 'academic_periods.id = teaching_journals.academic_period_id')
            ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
            ->where('teaching_journals.id', $id);

        if ($teacherId !== null) {
            $builder->where('teaching_journals.teacher_id', $teacherId);
        }

        return $builder->first();
    }

    /**
     * Ringkasan progress guru — untuk dashboard kepala sekolah / admin
     * Output: guru_id, total_pertemuan, target_jp (dari prota)
     */
    public function getTeacherProgress(int $periodId): array
    {
        $db = db_connect();

        // Jurnal terisi per guru per mapel per kelas
        $sql = "SELECT
                    t.id AS teacher_id,
                    t.name AS teacher_name,
                    tj.school_subject_id,
                    s.name AS subject_name,
                    tj.classroom_id,
                    c.name AS classroom_name,
                    COUNT(tj.id) AS total_pertemuan
                FROM teaching_journals tj
                JOIN teachers t ON t.id = tj.teacher_id
                JOIN school_subjects s ON s.id = tj.school_subject_id
                JOIN classrooms c ON c.id = tj.classroom_id
                WHERE tj.academic_period_id = ?
                  AND tj.deleted_at IS NULL
                GROUP BY t.id, tj.school_subject_id, tj.classroom_id
                ORDER BY t.name ASC, s.name ASC";

        return $db->query($sql, [$periodId])->getResultArray();
    }
}
