<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxDeviceConnection;
use Modules\NX600Lab\Entities\NxDeviceError;
use Modules\NX600Lab\Entities\NxModuleSetting;

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

        $businessId = $request->session()->get('user.business_id');

        $connections = NxDeviceConnection::latest('id')->paginate(15, ['*'], 'conn_page')->withQueryString();
        $errors      = NxDeviceError::latest('id')->paginate(15, ['*'], 'err_page')->withQueryString();

        return view('nx600Lab::devices.index', [
            'connections' => $connections,
            'errors'      => $errors,
            'settings'    => NxModuleSetting::allFor((int) $businessId),
            'activeCount' => NxDeviceConnection::where('status', 'connected')->count(),
        ]);
    }

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

        NxDeviceError::findOrFail($id)->acknowledge();

        return back()->with('status', ['success' => 1, 'msg' => 'Error acknowledged.']);
    }
}
