<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddMissingRevisionColumns extends Migration
{
    public function up()
    {
        // Check if columns exist before adding
        $db = \Config\Database::connect();
        $fields = $db->getFieldNames('tabel_history_revisi_order');

        $columnsToAdd = [];

        if (!in_array('tipe_revisi', $fields)) {
            $columnsToAdd['tipe_revisi'] = [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'null' => true,
                'default' => 'lainnya',
                'comment' => 'Tipe perubahan: ukuran, warna, material, desain, detail_change, lainnya',
                'after' => 'keterangan_permintaan_revisi'
            ];
        }

        if (!in_array('biaya_revisi', $fields)) {
            $columnsToAdd['biaya_revisi'] = [
                'type' => 'DECIMAL',
                'constraint' => '10,2',
                'default' => 0,
                'comment' => 'Biaya tambahan untuk revisi'
            ];
        }

        if (!in_array('tgl_diterima_pegawai', $fields)) {
            $columnsToAdd['tgl_diterima_pegawai'] = [
                'type' => 'DATETIME',
                'null' => true,
                'comment' => 'Tanggal revisi diterima oleh pegawai'
            ];
        }

        // Add columns if any are missing
        if (!empty($columnsToAdd)) {
            $this->forge->addColumn('tabel_history_revisi_order', $columnsToAdd);
            echo "Added missing columns to tabel_history_revisi_order\n";
        } else {
            echo "All columns already exist in tabel_history_revisi_order\n";
        }
    }

    public function down()
    {
        // Remove the columns if rolling back
        $db = \Config\Database::connect();
        $fields = $db->getFieldNames('tabel_history_revisi_order');

        if (in_array('tipe_revisi', $fields)) {
            $this->forge->dropColumn('tabel_history_revisi_order', 'tipe_revisi');
        }

        if (in_array('biaya_revisi', $fields)) {
            $this->forge->dropColumn('tabel_history_revisi_order', 'biaya_revisi');
        }

        if (in_array('tgl_diterima_pegawai', $fields)) {
            $this->forge->dropColumn('tabel_history_revisi_order', 'tgl_diterima_pegawai');
        }
    }
}
