<?php

namespace App\Models;

use CodeIgniter\Model;

class BkAssignmentModel extends Model
{
    protected $table            = 'bk_assignments';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = ['teacher_id', 'classroom_id', 'academic_period_id'];

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

    // Ambil semua assignment BK dengan relasi
    public function getAllWithRelations($periodId = null)
    {
        $builder = $this->select('
                bk_assignments.*,
                teachers.name as teacher_name,
                teachers.nip,
                classrooms.name as classroom_name,
                grades.name as grade_name,
                academic_periods.semester,
                academic_years.name as year_name
            ')
            ->join('teachers', 'teachers.id = bk_assignments.teacher_id')
            ->join('classrooms', 'classrooms.id = bk_assignments.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->join('academic_periods', 'academic_periods.id = bk_assignments.academic_period_id')
            ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
            ->orderBy('grades.order', 'ASC')
            ->orderBy('classrooms.name', 'ASC');
        
        if ($periodId) {
            $builder->where('bk_assignments.academic_period_id', $periodId);
        }
        
        return $builder->findAll();
    }

    // Ambil kelas yang sudah diassign BK untuk periode tertentu
    public function getAssignedClassrooms($periodId)
    {
        return $this->select('classroom_id, teacher_id')
                    ->where('academic_period_id', $periodId)
                    ->findAll();
    }

    // Ambil BK untuk kelas tertentu di periode tertentu
    public function getByClassroom($classroomId, $periodId)
    {
        return $this->where('classroom_id', $classroomId)
                    ->where('academic_period_id', $periodId)
                    ->first();
    }

    // Simpan assignment (hapus yang tidak dipilih)
    public function saveAssignments($teacherId, $classroomIds, $periodId)
    {
        // Hapus semua assignment untuk guru ini di periode ini
        $this->where('teacher_id', $teacherId)
             ->where('academic_period_id', $periodId)
             ->delete();
        
        // Insert assignment baru untuk setiap kelas yang dipilih
        $success = 0;
        foreach ($classroomIds as $classroomId) {
            // Cek apakah kelas sudah punya BK lain di periode ini
            $existing = $this->where('classroom_id', $classroomId)
                             ->where('academic_period_id', $periodId)
                             ->first();
            
            if ($existing && $existing['teacher_id'] != $teacherId) {
                // Kelas sudah punya BK lain, skip
                continue;
            }
            
            $this->insert([
                'teacher_id' => $teacherId,
                'classroom_id' => $classroomId,
                'academic_period_id' => $periodId,
            ]);
            $success++;
        }
        
        return $success;
    }
}