<?php
// 2025-09-10-031001_CreateEmailTemplates.php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;

class CreateEmailTemplates extends Migration
{
    protected $DBGroup = 'default';

    public function up()
    {
        $this->forge->addField([
            'id'           => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
            'template_key' => ['type'=>'VARCHAR','constraint'=>64,'null'=>false],
            'name'         => ['type'=>'VARCHAR','constraint'=>100,'null'=>false],
            'subject'      => ['type'=>'VARCHAR','constraint'=>255,'null'=>false],
            'body'         => ['type'=>'MEDIUMTEXT','null'=>false],
            'is_active'    => ['type'=>'TINYINT','constraint'=>1,'default'=>1,'null'=>false],
            'created_at'   => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
            'updated_at'   => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('template_key');

        $this->forge->createTable('email_templates', true, [
            'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
        ]);

        // Add ON UPDATE for updated_at after table creation
        $this->db->query("ALTER TABLE `email_templates`
            MODIFY `updated_at` DATETIME NOT NULL
            DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
    }

    public function down()
    {
        $this->forge->dropTable('email_templates', true);
    }
}
