<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddUsernameToUsersTable extends Migration
{
    public function up()
    {
        // 1. Tambah kolom username dulu (nullable dulu)
        $this->forge->addColumn('users', [
            'username' => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
                'null'       => true,
                'after'      => 'id',
                'unique'     => true,
            ],
        ]);

        // 2. Isi username untuk data yang sudah ada (copy dari email)
        $this->db->query("UPDATE users SET username = email WHERE username IS NULL");

        // 3. Ubah username menjadi NOT NULL
        $this->forge->modifyColumn('users', [
            'username' => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
                'null'       => false,
            ],
        ]);

        // 4. Ubah email menjadi nullable
        $this->forge->modifyColumn('users', [
            'email' => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
                'null'       => true,
            ],
        ]);
    }

    public function down()
    {
        // Kembalikan email ke NOT NULL
        $this->forge->modifyColumn('users', [
            'email' => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
                'null'       => false,
            ],
        ]);

        // Hapus kolom username
        $this->forge->dropColumn('users', 'username');
    }
}