<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AuditLogController extends Controller
{
    public function index(Request $request)
    {
        $query = AuditLog::query()->orderByDesc('created_at');
        if ($request->filled('module')) { $query->where('module', $request->module); }
        if ($request->filled('action')) { $query->where('action', $request->action); }
        if ($request->filled('status')) { $query->where('status', $request->status); }
        if ($request->filled('user')) { $query->where('user_email', 'like', '%'.$request->user.'%'); }
        $logs = $query->paginate(30);
        return view('audit.logs', compact('logs'));
    }

    public function show($uuid)
    {
        $log = AuditLog::where('uuid', $uuid)->firstOrFail();
        return view('audit.detail', compact('log'));
    }

    public function export(Request $request): StreamedResponse
    {
        $filename = 'ngbvd_audit_logs_' . now()->format('Ymd_His') . '.csv';
        return response()->streamDownload(function () {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['Date', 'User', 'Module', 'Action', 'Method', 'URL', 'Status', 'Response']);
            AuditLog::orderByDesc('created_at')->limit(5000)->chunk(500, function ($rows) use ($out) {
                foreach ($rows as $row) {
                    fputcsv($out, [$row->created_at, $row->user_email, $row->module, $row->action, $row->method, $row->url, $row->status, $row->response_code]);
                }
            });
            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }
}
