<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class AuthSeeder extends Seeder
{
    public function run()
    {
        $roles = [
            ['role_code' => 'ADMIN', 'role_name' => 'Administrator'],
            ['role_code' => 'WALI_KELAS', 'role_name' => 'Wali Kelas'],
            ['role_code' => 'GURU_BK', 'role_name' => 'Guru BK'],
            ['role_code' => 'GURU_MAPEL', 'role_name' => 'Guru Mata Pelajaran'],
            ['role_code' => 'ORANG_TUA', 'role_name' => 'Orang Tua'],
        ];

        foreach ($roles as $role) {
            $exists = $this->db->table('roles')->where('role_code', $role['role_code'])->countAllResults();
            if ($exists === 0) {
                $this->db->table('roles')->insert($role);
            }
        }

        $adminEmail = env('ADMIN_EMAIL', 'admin@example.com');
        $adminPassword = env('ADMIN_PASSWORD', 'admin123');

        $userExists = $this->db->table('users')->where('email', $adminEmail)->countAllResults();
        if ($userExists > 0) {
            return;
        }

        $this->db->table('users')->insert([
            'name'          => 'Admin',
            'email'         => $adminEmail,
            'password_hash' => password_hash($adminPassword, PASSWORD_DEFAULT),
            'is_active'     => 1,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ]);
        $adminId     = $this->db->insertID();
        $adminRole   = $this->db->table('roles')->where('role_code', 'ADMIN')->get()->getRow();
        if ($adminRole) {
            $this->db->table('user_roles')->insert([
                'user_id' => $adminId,
                'role_id' => $adminRole->id,
            ]);
        }
    }
}
