<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * BATCH 3 — T-09
 * ptm_teacher_certifications: Koleksi sertifikasi guru (1-to-many).
 * Sumber dari ProfessionalCondition certified/not_certified (ADR-001 + ADR-002).
 */
class CreatePtmTeacherCertifications extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'                    => ['type' => 'INT',     'constraint' => 10,  'unsigned' => true, 'auto_increment' => true],
            'teacher_id'            => ['type' => 'BIGINT',  'constraint' => 20,  'unsigned' => true, 'null' => false],
            'certification_type_id' => ['type' => 'INT',     'constraint' => 10,  'unsigned' => true, 'null' => false],
            'certified_subject'     => ['type' => 'VARCHAR', 'constraint' => 150, 'null' => false, 'comment' => 'Mata pelajaran yang disertifikasi'],
            'certificate_number'    => ['type' => 'VARCHAR', 'constraint' => 100, 'null' => true],
            'nrg'                   => ['type' => 'VARCHAR', 'constraint' => 30,  'null' => true, 'comment' => 'Nomor Registrasi Guru'],
            'issuing_institution'   => ['type' => 'VARCHAR', 'constraint' => 200, 'null' => true],
            'issued_date'           => ['type' => 'DATE',    'null' => true],
            'valid_from'            => ['type' => 'DATE',    'null' => false, 'comment' => 'Tanggal mulai berlaku'],
            'valid_until'           => ['type' => 'DATE',    'null' => true, 'comment' => 'NULL = tidak ada batas waktu'],
            'status'                => ['type' => 'ENUM', 'constraint' => ['PENDING','ACTIVE','EXPIRED','REVOKED'], 'null' => false, 'default' => 'PENDING'],
            'notes'                 => ['type' => 'TEXT',    'null' => true],
            'created_by'            => ['type' => 'BIGINT',  'constraint' => 20, 'unsigned' => true, 'null' => false],
            'created_at'            => ['type' => 'DATETIME', 'null' => true],
            'updated_at'            => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey(['teacher_id', 'status']);                    // QUERY KRITIS
        $this->forge->addKey(['teacher_id', 'valid_from', 'valid_until']); // isActiveOn(date)
        $this->forge->addKey('status');
        $this->forge->addKey('nrg');
        $this->forge->addForeignKey('teacher_id',            'teachers',                  'id', 'RESTRICT', 'CASCADE');
        $this->forge->addForeignKey('certification_type_id', 'ptm_certification_types',   'id', 'RESTRICT', 'CASCADE');
        $this->forge->addForeignKey('created_by',            'users',                     'id', 'RESTRICT', 'CASCADE');
        $this->forge->createTable('ptm_teacher_certifications', true);
    }

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