<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateScheduleEntries extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id'                => ['type' => 'INT', 'unsigned' => true, 'auto_increment' => true],

            // Relasi ke header jadwal
            'schedule_id'       => ['type' => 'INT', 'unsigned' => true,
                                    'comment' => 'FK ke schedules'],

            // Relasi ke beban mengajar (sumber data)
            'schedule_load_id'  => ['type' => 'INT', 'unsigned' => true,
                                    'comment' => 'FK ke schedule_loads'],

            // Denormalized untuk query cepat (tidak perlu join setiap saat)
            'teacher_id'        => ['type' => 'INT', 'unsigned' => true],
            'classroom_id'      => ['type' => 'INT', 'unsigned' => true],
            'school_subject_id' => ['type' => 'INT', 'unsigned' => true],

            // Posisi dalam jadwal
            'day'               => ['type' => 'TINYINT', 'unsigned' => true,
                                    'comment' => '1=Senin, 2=Selasa, ..., 6=Sabtu'],
            'slot_number'       => ['type' => 'TINYINT', 'unsigned' => true,
                                    'comment' => 'Urutan jam ke-'],
            'timeslot_id'       => ['type' => 'INT', 'unsigned' => true,
                                    'comment' => 'FK ke schedule_timeslots'],

            // Flag apakah sudah diedit manual
            'is_manual'         => ['type' => 'TINYINT', 'constraint' => 1, 'default' => 0,
                                    'comment' => '0=hasil generate, 1=diubah manual'],

            'created_at'        => ['type' => 'DATETIME', 'null' => true],
            'updated_at'        => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);

        // Index untuk validasi hard constraint (query cepat saat generate & cek konflik)
        // HC1 & HC3: guru tidak boleh di slot yang sama
        $this->forge->addKey(['schedule_id', 'teacher_id', 'day', 'slot_number']);

        // HC2: kelas tidak boleh di slot yang sama
        $this->forge->addKey(['schedule_id', 'classroom_id', 'day', 'slot_number']);

        // Untuk tampilan grid per kelas
        $this->forge->addKey(['schedule_id', 'classroom_id', 'day']);

        // Untuk tampilan grid per guru
        $this->forge->addKey(['schedule_id', 'teacher_id', 'day']);

        $this->forge->createTable('schedule_entries', true);
    }

    public function down()
    {
        $this->forge->dropTable('schedule_entries', true);
    }
}