<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateAssessmentClassSettingsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id'                => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'assessment_id'     => ['type' => 'BIGINT', 'unsigned' => true],
            'classroom_id'      => ['type' => 'BIGINT', 'unsigned' => true],
            'teacher_id'        => ['type' => 'BIGINT', 'unsigned' => true, 'null' => true],

            // KKTP / KKM
            'kktp'              => ['type' => 'TINYINT', 'default' => 75],

            // Bobot per jenis soal (total harus 100)
            'bobot_pg'          => ['type' => 'TINYINT', 'default' => 0],
            'bobot_bs'          => ['type' => 'TINYINT', 'default' => 0],
            'bobot_isian'       => ['type' => 'TINYINT', 'default' => 0],
            'bobot_essay'       => ['type' => 'TINYINT', 'default' => 0],

            // Kunci jawaban (string karakter, misal "AABBCCDDAA")
            'kunci_pg'          => ['type' => 'TEXT', 'null' => true],
            'kunci_bs'          => ['type' => 'TEXT', 'null' => true],

            // Status: apakah bobot sudah diisi (bobot_filled = 1 berarti tabel koreksi aktif)
            'bobot_filled'      => ['type' => 'TINYINT', 'constraint' => 1, 'default' => 0],

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

        $this->forge->addPrimaryKey('id');
        $this->forge->addForeignKey('assessment_id', 'assessments',  'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('classroom_id',  'classrooms',   'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('teacher_id',    'teachers',     'id', 'SET NULL', 'CASCADE');

        // 1 assessment + 1 kelas = 1 setting
        $this->forge->addUniqueKey(['assessment_id', 'classroom_id']);

        $this->forge->createTable('assessment_class_settings');
    }

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