<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class RefactorScheduleLoads extends Migration
{
    public function up()
    {
        // 1. Hapus kolom max_per_day (tidak dipakai lagi)
        if ($this->db->fieldExists('max_per_day', 'schedule_loads')) {
            $this->forge->dropColumn('schedule_loads', 'max_per_day');
        }

        // 2. Hapus kolom preferred_slot_type (tidak dipakai lagi)
        if ($this->db->fieldExists('preferred_slot_type', 'schedule_loads')) {
            $this->forge->dropColumn('schedule_loads', 'preferred_slot_type');
        }

        // 3. Tambah kolom split_config (penyimpanan pecahan blok)
        if (!$this->db->fieldExists('split_config', 'schedule_loads')) {
            $this->forge->addColumn('schedule_loads', [
                'split_config' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 50,
                    'default'    => '',
                    'after'      => 'hours_per_week',
                    'comment'    => 'Pecahan blok, contoh: "2,2" untuk 4 jam atau "3,2" untuk 5 jam'
                ]
            ]);
        }

        // 4. Tambah kolom split_order (opsional, untuk urutan prioritas blok)
        if (!$this->db->fieldExists('split_order', 'schedule_loads')) {
            $this->forge->addColumn('schedule_loads', [
                'split_order' => [
                    'type'       => 'TINYINT',
                    'constraint' => 1,
                    'default'    => 0,
                    'after'      => 'split_config',
                    'comment'    => '0=urut normal, 1=balik (blok besar dulu)'
                ]
            ]);
        }
    }

    public function down()
    {
        // Kembalikan kolom yang dihapus
        if (!$this->db->fieldExists('max_per_day', 'schedule_loads')) {
            $this->forge->addColumn('schedule_loads', [
                'max_per_day' => [
                    'type'       => 'TINYINT',
                    'unsigned'   => true,
                    'default'    => 2,
                    'comment'    => 'Maks jam mapel ini dalam 1 hari'
                ]
            ]);
        }

        if (!$this->db->fieldExists('preferred_slot_type', 'schedule_loads')) {
            $this->forge->addColumn('schedule_loads', [
                'preferred_slot_type' => [
                    'type'       => "ENUM('any','pagi','siang')",
                    'default'    => 'any',
                    'comment'    => 'Preferensi waktu mengajar'
                ]
            ]);
        }

        // Hapus kolom baru
        $this->forge->dropColumn('schedule_loads', 'split_config');
        $this->forge->dropColumn('schedule_loads', 'split_order');
    }
}