<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

/**
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 *
 * Extend this class in any new controllers:
 * ```
 *     class Home extends BaseController
 * ```
 *
 * For security, be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
    protected $helpers = ['form', 'url', 'text', 'academy', 'vite'];

    protected mixed $currentUser = null;
    protected array $currentRoles = [];
    protected ?string $primaryRole = null;

    /**
     * @return void
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void
    {
        parent::initController($request, $response, $logger);

        if (auth()->loggedIn()) {
            $this->currentUser  = auth()->user();
            $authorization      = service('authorization');
            $this->currentRoles = $authorization->getRolesForUser((int) $this->currentUser->id);
            $this->primaryRole  = $authorization->getPrimaryRole((int) $this->currentUser->id);
        }

        service('renderer')->setVar('authUser', $this->currentUser);
        service('renderer')->setVar('authRoles', $this->currentRoles);
        service('renderer')->setVar('primaryRole', $this->primaryRole);
    }

    protected function isAdmin(): bool
    {
        return in_array('admin', $this->currentRoles, true);
    }

    protected function isCoach(): bool
    {
        return in_array('coach', $this->currentRoles, true);
    }

    protected function forbidden(string $message = 'Nu ai permisiunea necesara pentru aceasta sectiune.'): ResponseInterface
    {
        return $this->response
            ->setStatusCode(ResponseInterface::HTTP_FORBIDDEN)
            ->setBody(view('errors/html/error_403', ['message' => $message]));
    }
}
