<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;

class LogController extends Controller
{
    private const MAX_LOG_LINES = 300;


    public function index(): void
    {
        Auth::requireLogin();

        $level = $_GET['level'] ?? '';
        $dateFrom = $_GET['date_from'] ?? '';
        $dateTo = $_GET['date_to'] ?? '';
        $page = max(1, (int)($_GET['page'] ?? 1));
        $perPage = 50;

        $allEvents = $this->readPublishEvents();
        $filtered = [];

        foreach ($allEvents as $event) {
            if ($level && strtoupper($event['level']) !== strtoupper($level)) {
                continue;
            }
            if ($dateFrom && $event['datetime'] !== '-' && $event['datetime'] < $dateFrom.' 00:00:00') {
                continue;
            }
            if ($dateTo && $event['datetime'] !== '-' && $event['datetime'] > $dateTo.' 23:59:59') {
                continue;
            }
            $filtered[] = $event;
        }

        $total = count($filtered);
        $pages = max(1, (int)ceil($total / $perPage));
        $offset = ($page - 1) * $perPage;
        $events = array_slice($filtered, $offset, $perPage);

        $this->view('logs/index', [
            'events' => $events,
            'level' => $level,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'page' => $page,
            'pages' => $pages,
            'total' => $total,
        ]);
    }

    private function readPublishEvents(): array
    {
        $db = \App\Core\Database::getInstance();
        $stmt = $db->prepare("SELECT datetime, level, message FROM cron_logs WHERE channel = 'publish' ORDER BY datetime DESC LIMIT 1000");
        $stmt->execute();
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $events = [];
        foreach ($rows as $row) {
            $events[] = [
                'datetime' => $row['datetime'],
                'level' => $row['level'],
                'message' => $row['message'],
            ];
        }
        return $events;
    }

    private function parseLine(string $line): array
    {
        if (preg_match('/^\[(.*?)\]\s+([A-Z]+):\s+(.*)$/', $line, $matches)) {
            return [
                'datetime' => $matches[1],
                'level' => $matches[2],
                'message' => $matches[3],
            ];
        }

        return [
            'datetime' => '-',
            'level' => 'INFO',
            'message' => $line,
        ];
    }
}
