<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class RbacModel extends Model
{
    public function roles(): array
    {
        return $this->db->query("SELECT * FROM roles ORDER BY id ASC")->fetchAll();
    }

    public function permissions(): array
    {
        return $this->db->query("SELECT * FROM permissions ORDER BY group_name ASC, code ASC")->fetchAll();
    }

    public function permissionsForRole(int $roleId): array
    {
        $stmt = $this->db->prepare("
            SELECT permission_id
            FROM role_permissions
            WHERE role_id = :role_id
        ");
        $stmt->execute([':role_id' => $roleId]);
        return array_map('intval', array_column($stmt->fetchAll(), 'permission_id'));
    }

    public function replaceRolePermissions(int $roleId, array $permissionIds): void
    {
        $del = $this->db->prepare("DELETE FROM role_permissions WHERE role_id = :role_id");
        $del->execute([':role_id' => $roleId]);

        $ins = $this->db->prepare("
            INSERT INTO role_permissions (role_id, permission_id)
            VALUES (:role_id, :permission_id)
        ");

        foreach ($permissionIds as $permissionId) {
            $ins->execute([
                ':role_id' => $roleId,
                ':permission_id' => (int) $permissionId,
            ]);
        }
    }
}
