<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxCommunicationLog;

class NxCommunicationLogController extends Controller
{
    public function index(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.view_logs')) {
            abort(403, 'Unauthorized action.');
        }

        $query = NxCommunicationLog::query();

        if ($request->filled('level')) {
            $query->where('level', $request->level);
        }
        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }
        if ($request->filled('search')) {
            $query->where('message', 'like', '%' . $request->search . '%');
        }

        $logs = $query->latest('id')->paginate(30)->withQueryString();

        return view('nx600Lab::logs.index', compact('logs'));
    }

    public function clear(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.view_logs')) {
            abort(403, 'Unauthorized action.');
        }

        NxCommunicationLog::query()->delete();

        return back()->with('status', ['success' => 1, 'msg' => 'Communication logs cleared.']);
    }
}
