<?php

namespace Core\App\Controllers;

use Core\App\Models\SecurityLog;
use Core\System\Response;

class SystemErrorsController
{
    public function index(): void
    {
        $model = new SecurityLog();
        $requestedType = trim((string)($_GET['type'] ?? 'issues'));
        $limit = (int)($_GET['limit'] ?? 200);
        if ($limit < 20) $limit = 20;
        if ($limit > 500) $limit = 500;
        $search = trim((string)($_GET['q'] ?? ''));

        $issueTypes = ['error', 'warning'];
        $allTypes = $model->getDistinctTypes();
        $filterOptions = ['issues'];
        foreach ($allTypes as $type) {
            if (!in_array($type, $filterOptions, true)) {
                $filterOptions[] = $type;
            }
        }
        if ($requestedType !== 'issues' && !in_array($requestedType, $filterOptions, true)) {
            $requestedType = 'issues';
        }

        $typesToLoad = $requestedType === 'issues' ? $issueTypes : [$requestedType];
        $logs = $model->getLatestByTypes($limit, $typesToLoad, $search);

        $stats = [
            'issues' => $model->countByTypes($issueTypes),
            'error' => $model->countByType('error'),
            'warning' => $model->countByType('warning'),
            'all_types' => [],
        ];
        foreach ($allTypes as $type) {
            $stats['all_types'][$type] = $model->countByType($type);
        }

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/system/errors.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function clear(): void
    {
        \Core\System\Csrf::check();

        $model = new SecurityLog();
        $action = trim((string)($_POST['action'] ?? ''));
        $days   = max(1, (int)($_POST['days'] ?? 30));

        switch ($action) {
            case 'clear_errors_old':
                $deleted = $model->clearByTypesOlderThan(['error'], $days);
                Response::redirect('/admin/system/errors?done=1&type=error&rows=' . $deleted);
                return;
            case 'clear_warnings_old':
                $deleted = $model->clearByTypesOlderThan(['warning'], $days);
                Response::redirect('/admin/system/errors?done=1&type=warning&rows=' . $deleted);
                return;
            case 'clear_all_issue_logs':
                $deleted = $model->clearByTypes(['error', 'warning']);
                Response::redirect('/admin/system/errors?done=1&type=issues&rows=' . $deleted);
                return;
            default:
                Response::redirect('/admin/system/errors?error=1');
        }
    }
}
