<?php

namespace App\Controllers;

use App\Models\ActivityLogModel;
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 $helpers = ['form', 'money'];

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

    protected function currentUserId(): ?int
    {
        $id = session('userId');

        return $id !== null ? (int) $id : null;
    }

    /**
     * Every write worth auditing should call this — see Module 9's
     * activity log spec (timestamp, user_id, module, action).
     */
    protected function logActivity(string $module, string $action): void
    {
        (new ActivityLogModel())->log($this->currentUserId(), $module, $action, $this->request->getIPAddress());
    }

    /**
     * Common pattern across every CRUD controller: a model's insert()/
     * update() returned false because its own $validationRules rejected
     * the data. Flashes the model's error messages the same way a
     * controller-level $this->validate() failure would.
     */
    protected function redirectWithModelErrors($model)
    {
        return redirect()->back()->withInput()->with('error', implode(' ', $model->errors()));
    }
}
