<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddSystemSettingsAndResetToken extends Migration
{
    public function up()
    {
        // 1. Create system_settings table
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'key_name' => [
                'type'       => 'VARCHAR',
                'constraint' => '100',
                'unique'     => true,
            ],
            'key_value' => [
                'type' => 'TEXT',
                'null' => true,
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('system_settings', true);

        // Insert default SMTP settings
        $db = \Config\Database::connect();
        $builder = $db->table('system_settings');
        $builder->insertBatch([
            ['key_name' => 'smtp_host', 'key_value' => 'smtp.gmail.com'],
            ['key_name' => 'smtp_port', 'key_value' => '465'],
            ['key_name' => 'smtp_crypto', 'key_value' => 'ssl'],
            ['key_name' => 'smtp_user', 'key_value' => ''],
            ['key_name' => 'smtp_pass', 'key_value' => ''],
            ['key_name' => 'smtp_from', 'key_value' => 'noreply@kopdigi.go.id'],
            ['key_name' => 'app_name', 'key_value' => 'Koperasi Digital Merah Putih'],
            ['key_name' => 'active_year', 'key_value' => '2026'],
        ]);

        // 2. Add reset_token columns to users table
        $fields = [
            'reset_token' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
                'null' => true,
            ],
            'reset_expires_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
        ];
        $this->forge->addColumn('users', $fields);
    }

    public function down()
    {
        $this->forge->dropTable('system_settings', true);
        $this->forge->dropColumn('users', ['reset_token', 'reset_expires_at']);
    }
}
