<?php

namespace App\Controllers;

use App\Models\MessageParticipantModel;
use App\Models\RoleModel;
use App\Services\NavigationPermissionService;
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
{
    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */

    protected $session;

    /**
     * @return void
     */
    protected $helpers = ['form', 'url', 'text'];

    /**
     * @return void
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Caution: Do not edit this line.
        parent::initController($request, $response, $logger);

        $this->session = service('session');
    }

    /**
     * Shared view data every screen needs (current user, unread notification
     * count, etc). Module controllers call array_merge($this->baseViewData(), [...]).
     */
    protected function baseViewData(): array
    {
        $userId = (int) ($this->session->get('user_id') ?? 0);
        $unreadMessages = 0;

        if ($userId > 0) {
            try {
                $unreadMessages = (new MessageParticipantModel())->unreadTotalForUser($userId);
            } catch (\Throwable $e) {
                $unreadMessages = 0;
            }
        }

        return [
            'currentUser' => [
                'id'       => $this->session->get('user_id'),
                'username' => $this->session->get('username'),
                'fullName' => $this->session->get('full_name'),
            ],
            'isAdmin'         => $this->isAdministrator(),
            'unreadMessages'  => $unreadMessages,
            'navPerms'        => new NavigationPermissionService(),
        ];
    }

    protected function isAdministrator(): bool
    {
        $roleSlug = $this->session->get('role_slug');

        if ($roleSlug === null && $this->session->get('role_id')) {
            $role = (new RoleModel())->find((int) $this->session->get('role_id'));
            $roleSlug = $role['slug'] ?? null;
            $this->session->set('role_slug', $roleSlug);
        }

        return $roleSlug === 'administrator';
    }
}
