<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\SensitiveFieldChange;
use Illuminate\Http\Request;

class AuditLogController extends Controller
{
    public function __construct()
    {
        $this->middleware('role:admin,comptabilite');
    }

    public function index(Request $request)
    {
        $query = AuditLog::with('user');

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

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

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

        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

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

        return view('audit-logs.index', compact('logs'));
    }

    public function show(AuditLog $log)
    {
        return view('audit-logs.show', compact('log'));
    }

    public function sensitiveChanges(Request $request)
    {
        $query = SensitiveFieldChange::with(['user', 'changedBy']);

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

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

        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

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

        return view('audit-logs.sensitive-changes', compact('changes'));
    }

    public function userActivity(Request $request)
    {
        $userId = $request->input('user_id');
        
        $logs = AuditLog::where('user_id', $userId)
            ->orderByDesc('created_at')
            ->paginate(50);

        return view('audit-logs.user-activity', compact('logs', 'userId'));
    }

    public function modelHistory($model, $modelId)
    {
        $logs = AuditLog::where('model', $model)
            ->where('model_id', $modelId)
            ->orderByDesc('created_at')
            ->get();

        return view('audit-logs.model-history', compact('logs', 'model', 'modelId'));
    }
}
