<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\ActivityLogModel;
use App\Models\SettingModel;

abstract class BaseController extends Controller
{
    protected IncomingRequest|CLIRequest $request;

    protected array $helpers = [];

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

    protected function isAdmin(): bool
    {
        return session('role') === 'administrator';
    }

    protected function logActivity(string $action, string $description): void
    {
        $logModel = new ActivityLogModel();
        $logModel->log($action, $description, $this->request->getIPAddress());
    }

    protected function jsonSuccess(string $message, array $extra = []): ResponseInterface
    {
        return $this->response->setJSON(array_merge(['success' => true, 'message' => $message], $extra));
    }

    protected function jsonError(string $message, int $status = 400): ResponseInterface
    {
        return $this->response->setStatusCode($status)->setJSON(['success' => false, 'message' => $message]);
    }

    protected function getAppName(): string
    {
        $setting = new SettingModel();
        return $setting->getValue('app_name', 'FT Teluk Betung');
    }

    protected function viewData(array $extra = []): array
    {
        return array_merge([
            'app_name' => $this->getAppName(),
            'username' => session('username'),
            'nama'     => session('nama'),
            'role'     => session('role'),
        ], $extra);
    }
}
