<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddSemesterToLateSlipLogs extends Migration
{
    public function up()
    {
        // Add nullable semester column and an index with school_year if not present
        if ($this->db->tableExists('late_slip_logs')) {
            $fields = $this->db->getFieldNames('late_slip_logs');
            if (!in_array('semester', $fields, true)) {
                $this->forge->addColumn('late_slip_logs', [
                    'semester' => [
                        'type'       => 'VARCHAR',
                        'constraint' => 32,
                        'null'       => true,
                        'after'      => 'school_year',
                    ],
                ]);
            }

            // Best-effort: add composite index if missing
            try {
                $sql = "SHOW INDEX FROM late_slip_logs WHERE Key_name = 'idx_late_slip_year_sem'";
                $exists = $this->db->query($sql)->getResultArray();
                if (empty($exists)) {
                    $this->db->query('ALTER TABLE late_slip_logs ADD INDEX idx_late_slip_year_sem (school_year, semester)');
                }
            } catch (\Throwable $e) { /* ignore */ }
        }
    }

    public function down()
    {
        if ($this->db->tableExists('late_slip_logs')) {
            try { $this->db->query('ALTER TABLE late_slip_logs DROP INDEX idx_late_slip_year_sem'); } catch (\Throwable $e) {}
            try { $this->forge->dropColumn('late_slip_logs', 'semester'); } catch (\Throwable $e) {}
        }
    }
}

