<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ApiLog;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ApiLogController extends Controller
{
    /**
     * Afficher les logs API
     */
    public function index(Request $request)
    {
        $query = ApiLog::query();

        // Filtres
        if ($request->method) {
            $query->where('method', $request->method);
        }
        if ($request->status) {
            $query->where('status_code', $request->status);
        }
        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        if ($request->search) {
            $query->where(function($q) use ($request) {
                $q->where('endpoint', 'like', '%' . $request->search . '%')
                  ->orWhere('ip_address', 'like', '%' . $request->search . '%');
            });
        }

        $logs = $query->orderBy('created_at', 'desc')
            ->paginate(50)
            ->appends($request->query());

        // Statistiques
        $stats = [
            'total' => ApiLog::count(),
            'today' => ApiLog::whereDate('created_at', today())->count(),
            'errors' => ApiLog::where('status_code', '>=', 400)->count(),
            'avg_response_time' => round(ApiLog::avg('response_time') ?? 0, 2),
        ];

        return view('admin.api-logs.index', compact('logs', 'stats'));
    }

    /**
     * Afficher un log
     */
    public function show($id)
    {
        $log = ApiLog::findOrFail($id);
        return view('admin.api-logs.show', compact('log'));
    }

    /**
     * Supprimer les anciens logs
     */
    public function cleanup(Request $request)
    {
        $days = $request->input('days', 30);
        
        $deleted = ApiLog::where('created_at', '<', now()->subDays($days))->delete();

        return back()->with('success', "{$deleted} logs supprimés (plus de {$days} jours).");
    }
}
