<?php
// app/Database/Seeds/SuperAdminSeeder.php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use App\Models\AdminModel;
use App\Models\RoleModel;

class SuperAdminSeeder extends Seeder
{
    public function run()
    {
        // 1. Buat Role "Super Admin"
        $roleModel = new RoleModel();
        $role = $roleModel->where('name', 'Super Admin')->first();
        
        if (!$role) {
            $roleId = $roleModel->insert([
                'name'        => 'Super Admin',
                'description' => 'Has all permissions across the system.'
            ]);
        } else {
            $roleId = $role->id;
        }

        // 2. Ambil semua permission yang ada
        $allPermissions = $this->db->table('permissions')->get()->getResultArray();
        $permissionIds = array_column($allPermissions, 'id');

        // 3. Berikan semua permission ke role "Super Admin"
        $rolePermissionsData = [];
        foreach ($permissionIds as $permId) {
            $rolePermissionsData[] = ['role_id' => $roleId, 'permission_id' => $permId];
        }
        
        if (!empty($rolePermissionsData)) {
            // Hapus permission lama (jika ada) dan insert yang baru untuk memastikan sinkron
            $this->db->table('role_permissions')->where('role_id', $roleId)->delete();
            $this->db->table('role_permissions')->insertBatch($rolePermissionsData);
        }

        // 4. Buat User Admin
        $adminModel = new AdminModel();
        $admin = $adminModel->where('email', 'devgka@gmail.com')->first();
        
        if (!$admin) {
            $adminId = $adminModel->insert([
                'name'     => 'Administrator',
                'email'    => 'devgka@gmail.com',
                'password' => password_hash('GreatNation', PASSWORD_DEFAULT) // Ganti 'password' dengan password yang kuat
            ]);
        } else {
            $adminId = $admin->id;
        }

        // 5. Hubungkan User Admin ke Role "Super Admin"
        $adminRoleData = ['admin_id' => $adminId, 'role_id' => $roleId];
        $this->db->table('admin_roles')->ignore(true)->insert($adminRoleData);

        // (Opsional) Berikan akses ke semua gereja (jika ada gereja di database)
        $allChurches = $this->db->table('churches')->get()->getResultArray();
        if ($allChurches) {
            $adminChurchesData = [];
            foreach ($allChurches as $church) {
                $adminChurchesData[] = ['admin_id' => $adminId, 'church_id' => $church['id']];
            }
            if (!empty($adminChurchesData)) {
                $this->db->table('admin_churches')->where('admin_id', $adminId)->delete();
                $this->db->table('admin_churches')->insertBatch($adminChurchesData);
            }
        }
    }
}