<?php

namespace App\Controllers;

use App\Models\UserModel;
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 = ['url', 'form', 'app'];

    /**
     * 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
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Load here all helpers you want to be available in your controllers that extend BaseController.
        // Caution: Do not put the this below the parent::initController() call below.
        // $this->helpers = ['form', 'url'];

        // Caution: Do not edit this line.
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.
        // $this->session = service('session');
        $this->refreshLoggedInUser();
    }

    private function refreshLoggedInUser(): void
    {
        $session = session();

        if (! $session->get('isLoggedIn')) {
            return;
        }

        $accountType = $this->currentAccountType();
        $accountId = (int) ($session->get('accountId') ?? $session->get('userId'));

        if ($accountId < 1) {
            $session->destroy();

            return;
        }

        $account = (new UserModel())->find($accountId);
        $sessionData = $account ? [
            'userName'            => $account['name'],
            'userEmail'           => $account['email'],
            'userRole'            => $account['role'],
            'userPhoto'           => $account['photo'] ?? null,
            'userPhotoDirectory'  => 'users',
        ] : null;

        if (! $account
            || (int) $account['is_active'] !== 1
            || $sessionData === null
            || $accountType !== 'user'
            || ! in_array(($account['role'] ?? ''), ['administrator', 'kasir'], true)
        ) {
            $session->destroy();

            return;
        }

        $session->set(array_merge($sessionData, [
            'accountType' => $accountType,
            'accountId'   => $accountId,
        ]));
    }

    protected function currentAccountType(): string
    {
        return (string) (session()->get('accountType') ?: 'user');
    }

    protected function isUserAccount(): bool
    {
        return $this->currentAccountType() === 'user';
    }

    protected function homePath(): string
    {
        return '/admin';
    }

    protected function isAdministratorRole(): bool
    {
        return $this->isUserAccount()
            && session()->get('userRole') === 'administrator';
    }

    protected function isKasirRole(): bool
    {
        return $this->isUserAccount()
            && session()->get('userRole') === 'kasir';
    }

    protected function isInventoryRole(): bool
    {
        return $this->isAdministratorRole() || $this->isKasirRole();
    }

    protected function requireAdministrator(string $redirectTo, string $message = 'Akses ditolak. Hanya administrator yang dapat melakukan aksi ini.')
    {
        if ($this->isAdministratorRole()) {
            return null;
        }

        return redirect()->to($redirectTo)->with('error', $message);
    }

    protected function requireInventoryAccess(string $redirectTo, string $message = 'Akses ditolak. Anda tidak memiliki akses ke modul ini.')
    {
        if ($this->isInventoryRole()) {
            return null;
        }

        return redirect()->to($redirectTo)->with('error', $message);
    }

}
