<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddTataUsahaRoleToUsersTable extends Migration
{
    public function up()
    {
        // 1. Modify the role column ENUM to add 'tata_usaha'
        $this->db->query("ALTER TABLE users MODIFY COLUMN role ENUM('superadmin','admin','operator','guru','tata_usaha') NOT NULL DEFAULT 'operator'");

        // 2. Insert dummy Tata Usaha user if not exists
        $existing = $this->db->table('users')->where('username', 'tu@simak.id')->get()->getRow();
        if (!$existing) {
            $this->db->table('users')->insert([
                'name'       => 'Staff Tata Usaha',
                'username'   => 'tu@simak.id',
                'email'      => 'tu@simak.id',
                'password'   => password_hash('tu123456', PASSWORD_DEFAULT),
                'role'       => 'tata_usaha',
                'is_active'  => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function down()
    {
        // 1. Delete dummy Tata Usaha user
        $this->db->table('users')->where('username', 'tu@simak.id')->delete();

        // 2. Revert the ENUM to previous state
        $this->db->table('users')->where('role', 'tata_usaha')->update(['role' => 'operator']);
        
        $this->db->query("ALTER TABLE users MODIFY COLUMN role ENUM('superadmin','admin','operator','guru') NOT NULL DEFAULT 'operator'");
    }
}
