<?php
require_once __DIR__ . '/../Core.php';

class UserPermission extends Model
{
    public function mapForUser(int $userId): array
    {
        $stmt = $this->db->prepare('SELECT permission_key, is_allowed FROM user_permissions WHERE user_id = ?');
        $stmt->execute([$userId]);
        $map = [];
        foreach ($stmt->fetchAll() as $row) {
            $map[$row['permission_key']] = (int)$row['is_allowed'] === 1;
        }
        return $map;
    }

    public function replaceForUser(int $userId, array $allowedPermissions): void
    {
        $this->db->prepare('DELETE FROM user_permissions WHERE user_id = ?')->execute([$userId]);
        $stmt = $this->db->prepare('INSERT INTO user_permissions (user_id, permission_key, is_allowed) VALUES (?, ?, 1)');
        foreach ($allowedPermissions as $permission) {
            $permission = trim((string)$permission);
            if ($permission === '') {
                continue;
            }
            $stmt->execute([$userId, $permission]);
        }
    }
}
