<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;

class TrackingLogController extends Controller
{
    private const MAX_LINES = 10000;
    private const PER_PAGE = 100;

    public function tracking(Request $request)
    {
        $date = $this->resolveDate($request->query('date'));
        $level = strtolower((string) $request->query('level', 'all'));
        $q = trim((string) $request->query('q', ''));
        $page = max(1, (int) $request->query('page', 1));

        $rows = $this->readLog($date, $level, $q);

        $paginator = new LengthAwarePaginator(
            array_slice($rows, ($page - 1) * self::PER_PAGE, self::PER_PAGE),
            count($rows),
            self::PER_PAGE,
            $page,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        return view('admin.logs.tracking', [
            'rows' => $paginator,
            'date' => $date,
            'level' => $level,
            'q' => $q,
            'minDate' => Carbon::today()->subDays(14)->toDateString(),
            'maxDate' => Carbon::today()->toDateString(),
            'availableLevels' => ['all', 'info', 'warning', 'error', 'critical', 'alert', 'emergency', 'debug'],
        ]);
    }

    private function resolveDate(?string $input): string
    {
        if ($input && preg_match('/^\d{4}-\d{2}-\d{2}$/', $input)) {
            try {
                $d = Carbon::createFromFormat('Y-m-d', $input);
                if (!$d) return Carbon::today()->toDateString();
                return $d->toDateString();
            } catch (\Throwable) { /* fall through */ }
        }
        return Carbon::today()->toDateString();
    }

    private function readLog(string $date, string $level, string $q): array
    {
        $path = storage_path("logs/tracking-{$date}.log");
        if (!is_file($path) || !is_readable($path)) return [];

        $rows = [];
        $handle = @fopen($path, 'r');
        if (!$handle) return [];

        $count = 0;
        while (($line = fgets($handle)) !== false) {
            if ($count++ >= self::MAX_LINES) break;
            $line = rtrim($line, "\r\n");
            if ($line === '') continue;

            $row = $this->parseLine($line);

            if ($level !== 'all' && strtolower($row['level']) !== $level) continue;
            if ($q !== '' && stripos($row['raw'], $q) === false) continue;

            $rows[] = $row;
        }
        fclose($handle);

        return $rows;
    }

    private function parseLine(string $line): array
    {
        if (preg_match('/^\[([^\]]+)\]\s+\w+\.(\w+):\s+(.*)$/s', $line, $m)) {
            return [
                'datetime' => $m[1],
                'level' => $m[2],
                'message' => $m[3],
                'raw' => $line,
            ];
        }
        return [
            'datetime' => '',
            'level' => 'unknown',
            'message' => $line,
            'raw' => $line,
        ];
    }
}
