<?php

class CfRole
{
    /**
     * @var PDO
     */
    private $dbConnection;

    /**
     * CfRole constructor.
     */
    public function __construct()
    {
        $this->dbConnection = CfPdo::getInstance()->getConnection();
    }

    public function getDefaultRole()
    {
        return $this->dbConnection->query('SELECT * FROM roles WHERE is_default = true')->fetch(PDO::FETCH_ASSOC);
    }

    public function setDefaultRole($name)
    {
        $this->dbConnection->query("UPDATE roles SET is_default = false ")->execute();
        if ($name) {
            $this->dbConnection->prepare("UPDATE roles SET is_default = true WHERE name = ? ")->execute([$name]);
        }
        return true;
    }

    /**
     * @param array $filter
     */
    public function getRoles($filter = null)
    {
        $sql = 'SELECT * FROM roles';
        $execute = [];

        if ($filter) {
            $sql .= ' WHERE lower(name) = ANY(lower(?)::text[])';
            $execute = ['{"' . implode('","', $filter) . '"}'];
        }

        $stmt = $this->dbConnection->prepare($sql);
        $stmt->execute($execute);

        return $stmt->fetchAll();
    }

    public function getAllRolesNames()
    {
        return array_map(fn ($role) => $role['name'], $this->getRoles());
    }

}
