<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddStudentFieldsForManagement extends Migration
{
    public function up()
    {
        // Rename nis -> nisn (Dapodik compatible; unique index follows column rename)
        $this->db->query('ALTER TABLE ' . $this->db->prefixTable('students') . ' CHANGE nis nisn VARCHAR(50) NOT NULL');

        // Add gender (L/P)
        $this->forge->addColumn('students', [
            'gender' => [
                'type'       => 'VARCHAR',
                'constraint' => 1,
                'null'       => true,
                'after'      => 'name',
            ],
        ]);

        // Add is_active (default 1)
        $this->forge->addColumn('students', [
            'is_active' => [
                'type'       => 'TINYINT',
                'constraint' => 1,
                'default'    => 1,
                'after'      => 'class_id',
            ],
        ]);

        // Make class_id nullable (for unmapped / Dapodik sync)
        $this->forge->dropForeignKey('students', 'students_class_id_foreign');
        $this->forge->modifyColumn('students', [
            'class_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
        ]);
        $this->forge->addForeignKey('class_id', 'classes', 'id', 'SET NULL', 'CASCADE', 'students_class_id_foreign');
    }

    public function down()
    {
        $this->forge->dropForeignKey('students', 'students_class_id_foreign');
        $this->forge->modifyColumn('students', [
            'class_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => false,
            ],
        ]);
        $this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE', 'students_class_id_foreign');

        $this->forge->dropColumn('students', 'is_active');
        $this->forge->dropColumn('students', 'gender');

        $this->db->query('ALTER TABLE ' . $this->db->prefixTable('students') . ' CHANGE nisn nis VARCHAR(50) NOT NULL');
    }
}
