<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Repositories\AuditLogRepository;

final class AuditLogController
{
    public function handle(): void
    {
        Auth::requireLogin();
        $pdo = DB::pdo();
        $repo = new AuditLogRepository($pdo);

        if (!$repo->tableReady()) {
            Response::flash('danger', 'يجب تشغيل ملف التحديث: sql/migrate_v1_19_auth_admin.sql');
            Response::view('pages/admin/audit_logs', ['ready' => false]);
            return;
        }

        require_permission('admin.logs.view');

        $filters = [
            'user_id' => Request::int('user_id'),
            'action_code' => trim((string)Request::get('action_code', '')),
            'from' => trim((string)Request::get('from', '')),
            'to' => trim((string)Request::get('to', '')),
        ];
        $page = max(1, Request::int('page', 1));
        $perPage = 50;

        Response::view('pages/admin/audit_logs', [
            'ready' => true,
            'logs' => $repo->paginated($filters, $page, $perPage),
            'users' => $repo->users(),
            'actions' => $repo->actions(),
            'filters' => $filters,
            'page' => $page,
            'per_page' => $perPage,
            'total' => $repo->count($filters),
        ]);
    }
}
