<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class UpdateAssessmentScoresTable extends Migration
{
    public function up()
    {
        // Tambah kolom yang dibutuhkan ke assessment_scores
        $fields = [
            // Kelas siswa ini dikoreksi (penting karena 1 event bisa banyak kelas)
            'classroom_id'      => ['type' => 'BIGINT', 'unsigned' => true, 'null' => true, 'after' => 'student_id'],

            // Jawaban siswa (string karakter)
            'jawaban_pg'        => ['type' => 'TEXT', 'null' => true, 'after' => 'classroom_id'],
            'jawaban_bs'        => ['type' => 'TEXT', 'null' => true, 'after' => 'jawaban_pg'],

            // Skor mentah per jenis soal (0-100)
            'skor_pg'           => ['type' => 'DECIMAL', 'constraint' => '5,2', 'null' => true, 'after' => 'jawaban_bs'],
            'skor_bs'           => ['type' => 'DECIMAL', 'constraint' => '5,2', 'null' => true, 'after' => 'skor_pg'],
            'skor_isian'        => ['type' => 'DECIMAL', 'constraint' => '5,2', 'null' => true, 'after' => 'skor_bs'],
            'skor_essay'        => ['type' => 'DECIMAL', 'constraint' => '5,2', 'null' => true, 'after' => 'skor_isian'],

            // Nilai akhir sudah dihitung dengan bobot (ROUNDUP, 0-100)
            'nilai_akhir'       => ['type' => 'TINYINT', 'unsigned' => true, 'null' => true, 'after' => 'skor_essay'],

            // Notif kalau jawaban siswa kurang/lebih dari kunci
            'notif_pg'          => ['type' => 'VARCHAR', 'constraint' => 50, 'null' => true, 'after' => 'nilai_akhir'],
            'notif_bs'          => ['type' => 'VARCHAR', 'constraint' => 50, 'null' => true, 'after' => 'notif_pg'],
        ];

        $this->forge->addColumn('assessment_scores', $fields);

        // Tambah FK classroom_id
        $this->db->query("ALTER TABLE assessment_scores ADD CONSTRAINT assessment_scores_classroom_id_foreign FOREIGN KEY (classroom_id) REFERENCES classrooms(id) ON DELETE SET NULL");
    }

    public function down()
    {
        $this->db->query("ALTER TABLE assessment_scores DROP FOREIGN KEY assessment_scores_classroom_id_foreign");

        $this->forge->dropColumn('assessment_scores', [
            'classroom_id',
            'jawaban_pg', 'jawaban_bs',
            'skor_pg', 'skor_bs', 'skor_isian', 'skor_essay',
            'nilai_akhir',
            'notif_pg', 'notif_bs',
        ]);
    }
}