<?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', 'session'];

    protected $session;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        $this->session = \Config\Services::session();
    }

    protected function isLoggedIn(): bool
    {
        return session()->has('user_id');
    }

    protected function currentUser(): ?array
    {
        $sess = session();
        if (!$sess->has('user_id')) {
            return null;
        }
        return [
            'user_id'   => $sess->get('user_id'),
            'username'  => $sess->get('username'),
            'email'     => $sess->get('email'),
            'full_name' => $sess->get('full_name'),
            'role'      => $sess->get('role'),
        ];
    }

    protected function setUserSession($user): void
    {
        session()->set([
            'user_id'   => $user['id'],
            'username'  => $user['username'],
            'email'     => $user['email'],
            'full_name' => $user['full_name'],
            'role'      => $user['role'],
        ]);
    }
}
