<?php

namespace App\Models;

use CodeIgniter\Model;

class ClassroomModel extends Model
{
    protected $table            = 'classrooms';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = ['name', 'grade_id', 'major_id', 'capacity', 'academic_year_id'];

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

    /**
     * Ambil semua kelas beserta relasi grade & major.
     * Jika $yearId diberikan, filter berdasarkan tahun ajaran tersebut.
     * Jika null, otomatis filter ke tahun ajaran aktif.
     * Jika $yearId = 'all', tampilkan semua kelas tanpa filter TA.
     */
    public function getAllWithRelations($yearId = null)
    {
        $builder = $this->select('classrooms.*, grades.name as grade_name, majors.name as major_name, academic_years.name as year_name')
                        ->join('grades', 'grades.id = classrooms.grade_id')
                        ->join('majors', 'majors.id = classrooms.major_id', 'left')
                        ->join('academic_years', 'academic_years.id = classrooms.academic_year_id', 'left')
                        ->where('classrooms.deleted_at', null)
                        ->orderBy('grades.order', 'ASC')
                        ->orderBy('classrooms.name', 'ASC');

        if ($yearId !== 'all') {
            if ($yearId === null) {
                // Default: filter ke tahun ajaran aktif
                $activeYear = db_connect()->table('academic_years')
                    ->where('is_active', 1)
                    ->where('deleted_at', null)
                    ->get()
                    ->getRowArray();

                if ($activeYear) {
                    $builder->where('classrooms.academic_year_id', $activeYear['id']);
                }
            } else {
                $builder->where('classrooms.academic_year_id', $yearId);
            }
        }

        return $builder->findAll();
    }

    /**
     * Ambil kelas berdasarkan tahun ajaran tertentu (shorthand).
     */
    public function getByYear($yearId)
    {
        return $this->getAllWithRelations($yearId);
    }

    /**
     * Copy semua kelas dari tahun ajaran tertentu ke tahun ajaran baru.
     * Hanya copy struktur (name, grade_id, major_id, capacity), bukan data siswa.
     * Mengembalikan jumlah kelas yang berhasil dicopy.
     */
    public function copyFromYear(int $fromYearId, int $toYearId): int
    {
        $sourceCls = $this->where('academic_year_id', $fromYearId)
                          ->where('deleted_at', null)
                          ->findAll();

        if (empty($sourceCls)) {
            return 0;
        }

        $db     = db_connect();
        $now    = date('Y-m-d H:i:s');
        $copied = 0;

        foreach ($sourceCls as $cls) {
            // Cek apakah kelas dengan nama + grade yang sama sudah ada di target TA
            $exists = $db->table('classrooms')
                ->where('name', $cls['name'])
                ->where('grade_id', $cls['grade_id'])
                ->where('academic_year_id', $toYearId)
                ->where('deleted_at', null)
                ->countAllResults();

            if (!$exists) {
                $db->table('classrooms')->insert([
                    'name'             => $cls['name'],
                    'grade_id'         => $cls['grade_id'],
                    'major_id'         => $cls['major_id'],
                    'capacity'         => $cls['capacity'],
                    'academic_year_id' => $toYearId,
                    'created_at'       => $now,
                    'updated_at'       => $now,
                ]);
                $copied++;
            }
        }

        return $copied;
    }
}