<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxCommunicationLog;
use Modules\NX600Lab\Entities\NxDeviceConnection;
use Modules\NX600Lab\Entities\NxDeviceError;
use Modules\NX600Lab\Entities\NxTestSession;
use Modules\NX600Lab\Entities\NxWorklist;
use Modules\NX600Lab\Entities\Services\VetClinicSyncService;

class NxDashboardController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('nx600_lab.access_module')) {
            abort(403, 'Unauthorized action.');
        }

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

        $stats = [
            'pending_worklist' => NxWorklist::where('business_id', $businessId)->where('is_sent', false)->count(),
            'sessions_today'   => NxTestSession::whereDate('test_date', today())->count(),
            'sessions_total'   => NxTestSession::count(),
            'unack_errors'     => NxDeviceError::where('acknowledged', false)->count(),
        ];

        $abnormalToday = NxTestSession::whereDate('test_date', today())
            ->whereHas('testResults', fn($q) => $q->where('is_abnormal', true))
            ->count();

        $lastConnection = NxDeviceConnection::latest('id')->first();

        $recentSessions = NxTestSession::with('testResults')
            ->latest('id')
            ->limit(8)
            ->get();

        $recentLogs = NxCommunicationLog::latest('id')->limit(10)->get();

        return view('nx600Lab::dashboard.index', [
            'stats'          => $stats,
            'abnormalToday'  => $abnormalToday,
            'lastConnection' => $lastConnection,
            'recentSessions' => $recentSessions,
            'recentLogs'     => $recentLogs,
            'syncEnabled'    => VetClinicSyncService::syncEnabled($businessId),
        ]);
    }
}
