<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class FixStudentSectionDistributionDraftIndexes extends Migration
{
    public function up()
    {
        if (! $this->db->tableExists('student_section_distribution_drafts')) {
            return;
        }

        $this->dropIndexIfExists('student_section_distribution_drafts', 'class_id_school_year_status');
        $this->dropIndexIfExists('student_section_distribution_drafts', 'class_section_id_school_year');
        $this->dropIndexIfExists('student_section_distribution_drafts', 'distribution_draft_class_year_status');
        $this->dropIndexIfExists('student_section_distribution_drafts', 'distribution_draft_section_year');

        $this->db->query(
            'CREATE INDEX distribution_draft_class_year_status ' .
            'ON student_section_distribution_drafts (class_id, school_year, status)'
        );
        $this->db->query(
            'CREATE INDEX distribution_draft_section_year ' .
            'ON student_section_distribution_drafts (class_section_id, school_year)'
        );
    }

    public function down()
    {
        if (! $this->db->tableExists('student_section_distribution_drafts')) {
            return;
        }

        $this->dropIndexIfExists('student_section_distribution_drafts', 'distribution_draft_class_year_status');
        $this->dropIndexIfExists('student_section_distribution_drafts', 'distribution_draft_section_year');
    }

    private function dropIndexIfExists(string $table, string $indexName): void
    {
        $row = $this->db->query(
            'SHOW INDEX FROM ' . $this->db->protectIdentifiers($table, true) .
            ' WHERE Key_name = ' . $this->db->escape($indexName)
        )->getRowArray();

        if ($row) {
            $this->db->query(
                'ALTER TABLE ' . $this->db->protectIdentifiers($table, true) .
                ' DROP INDEX ' . $this->db->protectIdentifiers($indexName)
            );
        }
    }
}
