<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;   // @phpstan-ignore-line (used in docblock)
use CodeIgniter\HTTP\IncomingRequest; // @phpstan-ignore-line (used in docblock)
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

/**
 * BaseController — provides shared services to all controllers.
 */
abstract class BaseController extends Controller
{
    /** @var IncomingRequest|CLIRequest */
    protected $request;

    protected $helpers = ['url', 'form', 'text', 'custom'];

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

    // ----------------------------------------------------------------
    // Shared helpers
    // ----------------------------------------------------------------

    /**
     * Return the current admin's ID from session.
     */
    protected function adminId(): int
    {
        return (int) session()->get('admin_id');
    }

    /**
     * Flash a success message.
     */
    protected function flashSuccess(string $msg): void
    {
        session()->setFlashdata('success', $msg);
    }

    /**
     * Flash an error message.
     */
    protected function flashError(string $msg): void
    {
        session()->setFlashdata('error', $msg);
    }

    /**
     * Render an admin view with the shared layout.
     */
    protected function render(string $view, array $data = []): string
    {
        $data['currentAdmin'] = session()->get('admin_name');
        $data['adminRole']    = session()->get('admin_role');
        $data['locale']       = app_locale();

        return view($view, $data);
    }

    /**
     * Return 403 JSON if not super_admin.
     */
    protected function requireSuperAdmin(): void
    {
        if (session()->get('admin_role') !== 'super_admin') {
            $this->flashError(lang('Admin.access_denied'));
            redirect()->back()->send();
            exit;
        }
    }
}
