<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddIqraToTahfidzSetoran extends Migration
{
    public function up()
    {
        // 1. Modify existing columns to be nullable
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `surah_id` TINYINT UNSIGNED NULL");
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `ayat_start` SMALLINT UNSIGNED NULL DEFAULT NULL");
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `ayat_end` SMALLINT UNSIGNED NULL DEFAULT NULL");

        // 2. Add new columns for Iqra
        $this->db->query("ALTER TABLE `tahfidz_setoran` ADD COLUMN `is_iqra` TINYINT(1) NOT NULL DEFAULT 0 AFTER `ayat_end`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` ADD COLUMN `iqra_no` TINYINT UNSIGNED NULL DEFAULT NULL AFTER `is_iqra`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` ADD COLUMN `iqra_page_start` SMALLINT UNSIGNED NULL DEFAULT NULL AFTER `iqra_no`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` ADD COLUMN `iqra_page_end` SMALLINT UNSIGNED NULL DEFAULT NULL AFTER `iqra_page_start`");
    }

    public function down()
    {
        // 1. Revert columns to NOT NULL (Note: only safe if there are no NULLs remaining, but down is for rollback)
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `surah_id` TINYINT UNSIGNED NOT NULL");
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `ayat_start` SMALLINT UNSIGNED NOT NULL DEFAULT 1");
        $this->db->query("ALTER TABLE `tahfidz_setoran` MODIFY COLUMN `ayat_end` SMALLINT UNSIGNED NOT NULL DEFAULT 1");

        // 2. Drop the new columns
        $this->db->query("ALTER TABLE `tahfidz_setoran` DROP COLUMN `is_iqra`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` DROP COLUMN `iqra_no`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` DROP COLUMN `iqra_page_start`");
        $this->db->query("ALTER TABLE `tahfidz_setoran` DROP COLUMN `iqra_page_end`");
    }
}
