<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class RepairModelSchemaColumns extends Migration
{
    public function up(): void
    {
        $this->addColumnIfMissing('calendar_events', 'event_type', [
            'type'       => 'VARCHAR',
            'constraint' => 120,
            'null'       => true,
            'after'      => 'description',
        ]);

        $this->addColumnIfMissing('exams', 'school_year', [
            'type'       => 'VARCHAR',
            'constraint' => 20,
            'null'       => true,
            'after'      => 'exam_name',
        ]);

        $this->addColumnIfMissing('flag', 'action_taken', [
            'type' => 'TEXT',
            'null' => true,
            'after' => 'close_description',
        ]);

        $this->addColumnIfMissing('current_flag', 'action_taken', [
            'type' => 'TEXT',
            'null' => true,
            'after' => 'close_description',
        ]);

        $this->addColumnIfMissing('user_preferences', 'timezone', [
            'type'       => 'VARCHAR',
            'constraint' => 64,
            'null'       => true,
            'after'      => 'language',
        ]);

        $this->addColumnIfMissing('student_class', 'is_event_only', [
            'type'       => 'TINYINT',
            'constraint' => 1,
            'unsigned'   => true,
            'default'    => 0,
            'after'      => 'school_year',
        ]);
    }

    public function down(): void
    {
        foreach ([
            'calendar_events' => 'event_type',
            'exams' => 'school_year',
            'flag' => 'action_taken',
            'current_flag' => 'action_taken',
            'user_preferences' => 'timezone',
            'student_class' => 'is_event_only',
        ] as $table => $column) {
            if ($this->db->tableExists($table) && $this->db->fieldExists($column, $table)) {
                $this->forge->dropColumn($table, $column);
            }
        }
    }

    private function addColumnIfMissing(string $table, string $column, array $definition): void
    {
        if (! $this->db->tableExists($table)) {
            return;
        }

        $fields = $this->db->getFieldNames($table);

        if (in_array($column, $fields, true)) {
            return;
        }

        if (isset($definition['after']) && ! in_array($definition['after'], $fields, true)) {
            unset($definition['after']);
        }

        $this->forge->addColumn($table, [$column => $definition]);
    }
}
