<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AlterStudentsForGraduation extends Migration
{
    public function up()
    {
        // 1. Add graduated_academic_year_id — hanya jika belum ada
        if (!$this->db->fieldExists('graduated_academic_year_id', 'students')) {
            $fields = [
                'graduated_academic_year_id' => [
                    'type'       => 'BIGINT',
                    'unsigned'   => true,
                    'null'       => true,
                    'after'      => 'exit_reason',
                ],
            ];
            $this->forge->addColumn('students', $fields);
        }

        // Add foreign key constraint
        $this->forge->addForeignKey('graduated_academic_year_id', 'academic_years', 'id', 'SET NULL', 'CASCADE');

        // 2. Add UNIQUE constraint to nisn
        $this->forge->modifyColumn('students', [
            'nisn' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'null'       => true,
                'unique'     => true,
            ],
        ]);
    }

    public function down()
    {
        // Remove foreign key first
        $this->forge->dropForeignKey('students', 'students_graduated_academic_year_id_foreign');

        // Drop column
        $this->forge->dropColumn('students', 'graduated_academic_year_id');

        // Remove UNIQUE constraint from nisn
        $this->forge->modifyColumn('students', [
            'nisn' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'null'       => true,
                'unique'     => false,
            ],
        ]);
    }
}
