<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    // Ambil daftar kelas yang diajar seorang guru di periode tertentu
    public function getTeacherClassrooms(int $teacherId, ?int $periodId = null): array
    {
        $db = \Config\Database::connect();
        $sql = "SELECT DISTINCT c.id, c.name
                FROM teaching_assignments ta
                JOIN classrooms c ON c.id = ta.classroom_id
                WHERE ta.teacher_id = ?
                  AND c.deleted_at IS NULL";
        $params = [$teacherId];

        if ($periodId) {
            $sql .= " AND ta.academic_period_id = ?";
            $params[] = $periodId;
        }

        $sql .= " ORDER BY c.name ASC";
        return $db->query($sql, $params)->getResultArray();
    }

    // Ambil daftar mapel yang diajar seorang guru di periode tertentu
    public function getTeacherSubjects(int $teacherId, ?int $periodId = null): array
    {
        $db = \Config\Database::connect();
        $sql = "SELECT DISTINCT ss.id, ss.name
                FROM teaching_assignments ta
                JOIN school_subjects ss ON ss.id = ta.subject_id
                WHERE ta.teacher_id = ?";
        $params = [$teacherId];

        if ($periodId) {
            $sql .= " AND ta.academic_period_id = ?";
            $params[] = $periodId;
        }

        $sql .= " ORDER BY ss.name ASC";
        return $db->query($sql, $params)->getResultArray();
    }

    // Ambil assignment untuk kelas dan periode tertentu
    public function getByClassroom($classroomId, $periodId)
    {
        return $this->select('teaching_assignments.*, teachers.name as teacher_name')
                    ->join('teachers', 'teachers.id = teaching_assignments.teacher_id')
                    ->where('teaching_assignments.classroom_id', $classroomId)
                    ->where('teaching_assignments.academic_period_id', $periodId)
                    ->findAll();
    }

    // Ambil assignment dalam bentuk map (subject_id => teacher_id)
    public function getMapByClassroom($classroomId, $periodId)
    {
        $assignments = $this->where('classroom_id', $classroomId)
                            ->where('academic_period_id', $periodId)
                            ->findAll();

        $map = [];
        foreach ($assignments as $a) {
            $map[$a['subject_id']] = $a['teacher_id'];
        }

        return $map;
    }

    // Simpan assignment massal untuk satu kelas
    public function saveAssignments($classroomId, $periodId, $assignments)
    {
        // Hapus semua assignment lama untuk kelas ini di periode ini
        $this->where('classroom_id', $classroomId)
             ->where('academic_period_id', $periodId)
             ->delete();

        // Insert assignment baru
        $success = 0;
        foreach ($assignments as $subjectId => $teacherId) {
            if (empty($teacherId)) continue;

            $this->insert([
                'teacher_id' => $teacherId,
                'classroom_id' => $classroomId,
                'subject_id' => $subjectId,
                'academic_period_id' => $periodId,
            ]);
            $success++;
        }

        return $success;
    }
}
