<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateTeacherAssignmentsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id'                 => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'teacher_id'         => ['type' => 'BIGINT', 'unsigned' => true],
            'classroom_id'       => ['type' => 'BIGINT', 'unsigned' => true],
            'subject_id'         => ['type' => 'BIGINT', 'unsigned' => true, 'null' => true],
            'academic_period_id' => ['type' => 'BIGINT', 'unsigned' => true],
            'assignment_type'    => [
                'type'       => 'ENUM',
                'constraint' => ['bk', 'subject_teacher'],
                'default'    => 'subject_teacher',
            ],
            'created_at'         => ['type' => 'DATETIME', 'null' => true],
            'updated_at'         => ['type' => 'DATETIME', 'null' => true],
        ]);
        
        $this->forge->addPrimaryKey('id');
        $this->forge->addForeignKey('teacher_id', 'teachers', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('classroom_id', 'classrooms', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('subject_id', 'subjects', 'id', 'SET NULL', 'CASCADE');
        $this->forge->addForeignKey('academic_period_id', 'academic_periods', 'id', 'CASCADE', 'CASCADE');
        
        // Unique: satu guru tidak bisa double assign di kelas, mapel, periode yang sama
        $this->forge->addUniqueKey(['teacher_id', 'classroom_id', 'subject_id', 'academic_period_id']);
        
        $this->forge->createTable('teacher_assignments');
    }

    public function down()
    {
        $this->forge->dropTable('teacher_assignments');
    }
}