<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class RemoveClassAssignmentSemester extends Migration
{
    public function up()
    {
        if (
            $this->db->tableExists('teacher_class')
            && $this->db->fieldExists('semester', 'teacher_class')
        ) {
            foreach ($this->indexesContainingColumn('teacher_class', 'semester') as $index) {
                $this->db->query(
                    'DROP INDEX ' . $this->db->escapeIdentifiers($index) . ' ON ' . $this->db->escapeIdentifiers('teacher_class')
                );
            }

            $this->db->query(
                'ALTER TABLE ' . $this->db->escapeIdentifiers('teacher_class')
                . ' DROP COLUMN ' . $this->db->escapeIdentifiers('semester')
            );
        }
    }

    public function down()
    {
        if (
            $this->db->tableExists('teacher_class')
            && ! $this->db->fieldExists('semester', 'teacher_class')
        ) {
            $this->forge->addColumn('teacher_class', [
                'semester' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 25,
                    'null'       => false,
                    'default'    => '',
                ],
            ]);
        }
    }

    private function indexesContainingColumn(string $table, string $column): array
    {
        $result = $this->db->query(
            'SHOW INDEX FROM ' . $this->db->escapeIdentifiers($table)
            . ' WHERE Column_name = ' . $this->db->escape($column)
        );

        $indexes = [];
        foreach ($result->getResultArray() as $row) {
            $index = (string) ($row['Key_name'] ?? '');
            if ($index !== '' && $index !== 'PRIMARY') {
                $indexes[] = $index;
            }
        }

        return array_values(array_unique($indexes));
    }
}
