<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class SystemLogController extends Controller
{
    /**
     * Afficher les logs système
     */
    public function index(Request $request)
    {
        $type = $request->get('type', 'activity');
        
        if ($type === 'audit' && \Schema::hasTable('audit_logs')) {
            $logs = AuditLog::with('user')
                ->orderBy('created_at', 'desc')
                ->paginate(50);
        } else {
            $logs = ActivityLog::with('user')
                ->orderBy('created_at', 'desc')
                ->paginate(50);
        }

        return view('admin.system-logs.index', compact('logs', 'type'));
    }

    /**
     * Afficher un log
     */
    public function show($id, Request $request)
    {
        $type = $request->get('type', 'activity');
        
        if ($type === 'audit') {
            $log = AuditLog::with('user')->findOrFail($id);
        } else {
            $log = ActivityLog::with('user')->findOrFail($id);
        }

        return view('admin.system-logs.show', compact('log', 'type'));
    }

    /**
     * Nettoyer les anciens logs
     */
    public function cleanup(Request $request)
    {
        $days = $request->input('days', 90);
        
        $deletedActivity = ActivityLog::where('created_at', '<', now()->subDays($days))->delete();
        $deletedAudit = 0;
        
        if (\Schema::hasTable('audit_logs')) {
            $deletedAudit = AuditLog::where('created_at', '<', now()->subDays($days))->delete();
        }

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