<?php

namespace App\Models;

use CodeIgniter\Model;

class AssessmentModel extends Model
{
    protected $table            = 'assessments';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'assessment_type_id', 'name', 'description', 'academic_period_id',
        'subject_id', 'classroom_id', 'grade_id', 'teacher_id',
        'start_date', 'end_date', 'is_open', 'is_visible', 'created_by',
        // Jenis soal
        'has_pg', 'has_bs', 'has_isian', 'has_essay',
        // Mode dan jumlah soal isian/essay
        'isian_mode', 'isian_total_soal',
        'essay_mode', 'essay_total_soal',
        // Bobot admin-controlled (untuk event bersama)
        'bobot_by_admin',
        'admin_bobot_pg', 'admin_bobot_bs', 'admin_bobot_isian', 'admin_bobot_essay',
    ];

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

    // Ambil semua asesmen dengan relasi (untuk admin) — exclude ASH karena ASH hanya milik guru
    public function getAllAssessments($periodId = null)
    {
        $builder = $this->select('assessments.*,
                            at.name as assessment_type_name, at.code as assessment_type_code,
                            ap.semester, ay.name as academic_year,
                            ss.name as subject_name,
                            c.name as classroom_name,
                            g.name as grade_name,
                            t.name as teacher_name,
                            u.name as creator_name')
                    ->join('assessment_types at', 'at.id = assessments.assessment_type_id')
                    ->join('academic_periods ap', 'ap.id = assessments.academic_period_id')
                    ->join('academic_years ay', 'ay.id = ap.academic_year_id')
                    ->join('school_subjects ss', 'ss.id = assessments.subject_id', 'left')
                    ->join('classrooms c', 'c.id = assessments.classroom_id', 'left')
                    ->join('grades g', 'g.id = assessments.grade_id', 'left')
                    ->join('teachers t', 't.id = assessments.teacher_id', 'left')
                    ->join('users u', 'u.id = assessments.created_by')
                    ->where('at.code !=', 'ASH');

        if ($periodId) {
            $builder->where('assessments.academic_period_id', $periodId);
        }

        return $builder->orderBy('assessments.created_at', 'DESC')->findAll();
    }

    /**
     * Ambil event asesmen untuk guru berdasarkan teaching_assignments.
     * Mengembalikan daftar event + mapel + kelas yang diampu guru tsb.
     * 
     * Untuk ASTS/ASAS/ASAT (created_by admin, bukan ASH):
     *   - event berlaku semua kelas, jadi join ke teaching_assignments
     *     untuk tahu kelas mana yang diampu guru ini
     * Untuk ASH (created_by guru sendiri):
     *   - sudah ada classroom_id & subject_id di assessments
     */
    public function getAssessmentsForTeacher($teacherId, $periodId = null)
    {
        $db = \Config\Database::connect();

        // Ambil semua kelas + mapel yang diajar guru ini
        $assignments = $db->table('teaching_assignments ta')
            ->select('ta.classroom_id, ta.subject_id, ss.name as subject_name, c.name as classroom_name, g.name as grade_name, g.order as grade_order')
            ->join('school_subjects ss', 'ss.id = ta.subject_id')
            ->join('classrooms c', 'c.id = ta.classroom_id')
            ->join('grades g', 'g.id = c.grade_id')
            ->where('ta.teacher_id', $teacherId)
            ->where('ta.academic_period_id', $periodId)
            ->get()->getResultArray();

        if (empty($assignments)) return [];

        // Ambil semua event asesmen yang aktif untuk periode ini
        $builder = $this->select('assessments.*, at.name as assessment_type_name, at.code as assessment_type_code')
                        ->join('assessment_types at', 'at.id = assessments.assessment_type_id')
                        ->where('assessments.is_visible', 1)
                        ->where('assessments.deleted_at', null);

        if ($periodId) {
            $builder->where('assessments.academic_period_id', $periodId);
        }

        $events = $builder->orderBy('assessments.created_at', 'DESC')->findAll();

        // Susun hasil: per event, per mapel, per kelas
        $result = [];
        foreach ($events as $event) {
            $isAsh = ($event['assessment_type_code'] === 'ASH');

            if ($isAsh) {
                // ASH: sudah spesifik classroom_id & subject_id
                // Cek apakah guru ini mengajar mapel itu di kelas itu
                foreach ($assignments as $assign) {
                    if ($assign['classroom_id'] == $event['classroom_id']
                        && $assign['subject_id'] == $event['subject_id']
                    ) {
                        $result[] = array_merge($event, [
                            'classroom_id'   => $assign['classroom_id'],
                            'classroom_name' => $assign['classroom_name'],
                            'grade_name'     => $assign['grade_name'],
                            'subject_id'     => $assign['subject_id'],
                            'subject_name'   => $assign['subject_name'],
                        ]);
                        break;
                    }
                }
            } else {
                // ASTS/ASAS/ASAT: berlaku semua kelas, tampilkan per kelas yang diampu guru ini
                foreach ($assignments as $assign) {
                    $result[] = array_merge($event, [
                        'classroom_id'   => $assign['classroom_id'],
                        'classroom_name' => $assign['classroom_name'],
                        'grade_name'     => $assign['grade_name'],
                        'subject_id'     => $assign['subject_id'],
                        'subject_name'   => $assign['subject_name'],
                    ]);
                }
            }
        }

        return $result;
    }

    // Ambil event ASH milik guru berdasarkan user_id (bukan teacher_id)
    public function getAshByUserId($userId, $periodId = null)
    {
        $builder = $this->select('assessments.*, at.name as assessment_type_name, ss.name as subject_name, c.name as classroom_name')
                        ->join('assessment_types at', 'at.id = assessments.assessment_type_id')
                        ->join('school_subjects ss', 'ss.id = assessments.subject_id', 'left')
                        ->join('classrooms c', 'c.id = assessments.classroom_id', 'left')
                        ->where('at.code', 'ASH')
                        ->where('assessments.created_by', $userId)
                        ->where('assessments.deleted_at', null);

        if ($periodId) {
            $builder->where('assessments.academic_period_id', $periodId);
        }

        return $builder->orderBy('assessments.created_at', 'DESC')->findAll();
    }
}