<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\SystemLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;

class SystemLogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = SystemLog::with('user');

        if ($request->filled('level')) {
            $query->where('level', $request->input('level'));
        }

        if ($request->filled('search')) {
            $s = $request->input('search');
            $query->where(function ($q) use ($s) {
                $q->where('message', 'like', "%{$s}%")
                  ->orWhere('action', 'like', "%{$s}%")
                  ->orWhere('model_type', 'like', "%{$s}%");
            });
        }

        if ($request->filled('date')) {
            $query->whereDate('created_at', $request->input('date'));
        }

        $logs = $query->orderByDesc('created_at')->paginate(50);

        return response()->json($logs);
    }

    public function errorLogs(): JsonResponse
    {
        $logPath = storage_path('logs/laravel.log');

        if (!File::exists($logPath)) {
            return response()->json(['entries' => [], 'size' => 0, 'last_modified' => null]);
        }

        $size = File::size($logPath);

        // Read last 100KB to avoid memory issues with very large logs
        $handle = fopen($logPath, 'r');
        $readBytes = min($size, 102400);
        fseek($handle, -$readBytes, SEEK_END);
        $content = fread($handle, $readBytes);
        fclose($handle);

        // Parse entries: each starts with [YYYY-MM-DD ...]
        $rawEntries = preg_split('/(?=\[\d{4}-\d{2}-\d{2})/', $content, -1, PREG_SPLIT_NO_EMPTY);

        $entries = collect($rawEntries)
            ->filter(fn($e) => trim($e) !== '')
            ->map(function ($entry) {
                preg_match('/\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]/', $entry, $dateMatch);
                preg_match('/\.(ERROR|WARNING|INFO|DEBUG|CRITICAL)/', $entry, $levelMatch);

                return [
                    'timestamp' => $dateMatch[1] ?? 'unknown',
                    'level'     => strtolower($levelMatch[1] ?? 'info'),
                    'message'   => mb_substr(trim($entry), 0, 400),
                ];
            })
            ->reverse()
            ->values()
            ->take(200);

        return response()->json([
            'entries'       => $entries,
            'size'          => $size,
            'size_human'    => $this->formatBytes($size),
            'last_modified' => Carbon::createFromTimestamp(File::lastModified($logPath))->toIso8601String(),
        ]);
    }

    public function clearErrorLogs(): JsonResponse
    {
        $logPath = storage_path('logs/laravel.log');
        if (File::exists($logPath)) {
            File::put($logPath, '');
        }

        return response()->json(['message' => 'Log file cleared.']);
    }

    public function levelStats(): JsonResponse
    {
        $stats = SystemLog::selectRaw('level, count(*) as count')
            ->groupBy('level')
            ->pluck('count', 'level');

        return response()->json($stats);
    }

    private function formatBytes(int $bytes): string
    {
        if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
        if ($bytes >= 1024)    return round($bytes / 1024, 2) . ' KB';
        return $bytes . ' B';
    }
}
