<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

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

        $this->upsertConfig('youth_fee', '200.00', ['180', '180.00']);
        $this->upsertConfig('new_tuition_youth_amount', '200.00', ['180', '180.00']);
    }

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

        $this->rollbackConfig('youth_fee', '180.00');
        $this->rollbackConfig('new_tuition_youth_amount', '180.00');
    }

    protected function upsertConfig(string $key, string $value, array $legacyValues = []): void
    {
        $row = $this->db->table('configuration')
            ->select('id, config_value')
            ->where('config_key', $key)
            ->orderBy('id', 'ASC')
            ->get()
            ->getRowArray();

        if (!$row) {
            $this->db->table('configuration')->insert([
                'config_key' => $key,
                'config_value' => $value,
            ]);
            return;
        }

        $current = trim((string) ($row['config_value'] ?? ''));
        if ($current === '' || in_array($current, $legacyValues, true)) {
            $this->db->table('configuration')
                ->where('config_key', $key)
                ->update(['config_value' => $value]);
        }
    }

    protected function rollbackConfig(string $key, string $value): void
    {
        $this->db->table('configuration')
            ->where('config_key', $key)
            ->where('config_value', '200.00')
            ->update(['config_value' => $value]);
    }
}
