<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddAiSettingsToTeachers extends Migration
{
    public function up()
    {
        // 1. Tambah kolom ai_provider dan ai_api_key
        $fields = [];
        if (!$this->db->fieldExists('ai_provider', 'teachers')) {
            $fields['ai_provider'] = [
                'type'       => 'VARCHAR',
                'constraint' => 50,
                'default'    => 'gemini',
                'after'      => 'user_id'
            ];
        }
        if (!$this->db->fieldExists('ai_api_key', 'teachers')) {
            $fields['ai_api_key'] = [
                'type'  => 'TEXT',
                'null'  => true,
                'after' => 'ai_provider'
            ];
        }
        if (!empty($fields)) {
            $this->forge->addColumn('teachers', $fields);
        }

        // 2. Migrasi data lama dari gemini_api_key ke ai_api_key
        if ($this->db->fieldExists('gemini_api_key', 'teachers')) {
            $this->db->query("UPDATE teachers SET ai_api_key = gemini_api_key WHERE gemini_api_key IS NOT NULL AND gemini_api_key != ''");
        }

        // 3. Hapus kolom gemini_api_key
        if ($this->db->fieldExists('gemini_api_key', 'teachers')) {
            $this->forge->dropColumn('teachers', 'gemini_api_key');
        }
    }

    public function down()
    {
        // Kembalikan kolom gemini_api_key
        if (!$this->db->fieldExists('gemini_api_key', 'teachers')) {
            $fields = [
                'gemini_api_key' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 255,
                    'null'       => true,
                    'after'      => 'user_id'
                ]
            ];
            $this->forge->addColumn('teachers', $fields);
        }

        // Kembalikan data dari ai_api_key ke gemini_api_key
        if ($this->db->fieldExists('gemini_api_key', 'teachers') && $this->db->fieldExists('ai_api_key', 'teachers') && $this->db->fieldExists('ai_provider', 'teachers')) {
            $this->db->query("UPDATE teachers SET gemini_api_key = ai_api_key WHERE ai_provider = 'gemini' AND ai_api_key IS NOT NULL AND ai_api_key != ''");
        }

        // Hapus kolom baru
        if ($this->db->fieldExists('ai_provider', 'teachers')) {
            $this->forge->dropColumn('teachers', 'ai_provider');
        }
        if ($this->db->fieldExists('ai_api_key', 'teachers')) {
            $this->forge->dropColumn('teachers', 'ai_api_key');
        }
    }
}
