<?php

namespace App\Controllers\Admin;

use App\Models\Control\AdminActivityLogModel;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

/**
 * Base for every super-admin (control-plane) controller. Deliberately
 * does NOT extend App\Controllers\BaseController: that class's
 * logActivity() writes to a TENANT's activity_log table via TenantModel,
 * which needs service('tenantDb') — and admin/* routes never resolve a
 * tenant at all (see Filters.php's 'tenant' except list). Using it here
 * would throw on the first log call. This mirrors it against the
 * control-DB admin_activity_log table instead.
 */
abstract class BaseAdminController extends Controller
{
    protected $helpers = ['form', 'money'];

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

    protected function currentAdminId(): ?int
    {
        $id = session('adminUserId');

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

    protected function logAdminActivity(string $module, string $action): void
    {
        (new AdminActivityLogModel())->log($this->currentAdminId(), $module, $action);
    }

    protected function redirectWithModelErrors($model)
    {
        return redirect()->back()->withInput()->with('error', implode(' ', $model->errors()));
    }
}
