<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddAcademicYearIdToClassrooms extends Migration
{
    public function up()
    {
        // Tambah kolom academic_year_id (nullable dulu untuk migrasi data)
        $this->forge->addColumn('classrooms', [
            'academic_year_id' => [
                'type'       => 'BIGINT',
                'unsigned'   => true,
                'null'       => true,
                'default'    => null,
                'after'      => 'capacity',
            ],
        ]);

        // Data migration: assign semua classroom lama ke tahun ajaran aktif
        $db = \Config\Database::connect();

        $activeYear = $db->table('academic_years')
            ->where('is_active', 1)
            ->where('deleted_at', null)
            ->get()
            ->getRowArray();

        if ($activeYear) {
            $db->table('classrooms')
               ->where('academic_year_id', null)
               ->update(['academic_year_id' => $activeYear['id']]);
        }

        // Tambah foreign key
        $this->forge->addForeignKey('academic_year_id', 'academic_years', 'id', 'SET NULL', 'CASCADE', 'classrooms');

        // Tambah index untuk performa query filter per TA
        $db->query('ALTER TABLE classrooms ADD INDEX idx_classrooms_academic_year_id (academic_year_id)');
    }

    public function down()
    {
        // Hapus FK dan kolom
        $db = \Config\Database::connect();
        $db->query('ALTER TABLE classrooms DROP FOREIGN KEY classrooms_academic_year_id_foreign');
        $db->query('ALTER TABLE classrooms DROP INDEX idx_classrooms_academic_year_id');

        $this->forge->dropColumn('classrooms', 'academic_year_id');
    }
}
