<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateStudentSectionDistributionDrafts extends Migration
{
    public function up()
    {
        if ($this->db->tableExists('student_section_distribution_drafts')) {
            return;
        }

        $this->forge->addField([
            'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'student_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'class_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'class_section_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'school_year' => ['type' => 'VARCHAR', 'constraint' => 20],
            'previous_school_year' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true],
            'previous_final_score' => ['type' => 'DECIMAL', 'constraint' => '6,2', 'null' => true],
            'score_group' => ['type' => 'VARCHAR', 'constraint' => 20],
            'status' => ['type' => 'VARCHAR', 'constraint' => 20, 'default' => 'pending'],
            'batch_key' => ['type' => 'VARCHAR', 'constraint' => 64],
            'created_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
            'applied_at' => ['type' => 'DATETIME', 'null' => true],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey(['student_id', 'school_year'], 'unique_distribution_draft_student_year');
        $this->forge->addKey(['class_id', 'school_year', 'status'], false, false, 'distribution_draft_class_year_status');
        $this->forge->addKey(['class_section_id', 'school_year'], false, false, 'distribution_draft_section_year');
        $this->forge->createTable('student_section_distribution_drafts');
    }

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