<?php
namespace Dashboard\Services;

use PDO;

class RoleService
{
  public static function checkHigherRoleByUserId($userId, $priority): bool
  {
    $userRolePriority = 0;
    $userRolePriorityQuery = db()->prepare("SELECT R.priority FROM AccountRoles AR INNER JOIN Roles R ON R.id = AR.roleID WHERE AR.accountID = ? ORDER BY R.priority DESC LIMIT 1");
    $userRolePriorityQuery->execute([$userId]);
    $userRolePriorityQuery = $userRolePriorityQuery->fetch(PDO::FETCH_ASSOC);
    if ($userRolePriorityQuery) {
      $userRolePriority = $userRolePriorityQuery["priority"];
    }

    return self::isHigherPriority($userRolePriority, $priority);
  }

  public static function isHigherPriority($rolePriority, $priority): bool
  {
    $status = true;
    if (is_array($priority)) {
      foreach ($priority as $p) {
        if ($p >= $rolePriority) {
          $status = false;
          break;
        }
      }
    } else {
      $status = $rolePriority > $priority;
    }
    return $status;
  }

  public static function isDifferentPermissions($userPermissions, $permissionList): bool
  {
    $permissions = [];
    foreach ($permissionList as $permissionID) {
      $permissionQuery = db()->prepare("SELECT name FROM Permissions WHERE id = ?");
      $permissionQuery->execute([$permissionID]);
      $permissionQuery = $permissionQuery->fetch(PDO::FETCH_ASSOC);
      if ($permissionQuery) {
        $permissions[] = $permissionQuery["name"];
      }
    }

    return count(array_diff($permissions, $userPermissions)) > 0;
  }
}