<?php

namespace Modules\LabCore\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\LabCore\Entities\LabAgent;
use Modules\LabCore\Entities\LabCommunicationLog;
use Modules\LabCore\Entities\LabDevice;
use Modules\LabCore\Entities\LabDeviceError;
use Modules\LabCore\Entities\LabTestSession;
use Modules\LabCore\Entities\LabWorklist;
use Modules\LabCore\Entities\Services\DriverRegistry;

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

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

        $stats = [
            'agents'           => LabAgent::where('business_id', $businessId)->count(),
            'devices'          => LabDevice::where('business_id', $businessId)->count(),
            'pending_worklist' => LabWorklist::where('business_id', $businessId)->pending()->count(),
            'sessions_today'   => LabTestSession::where('business_id', $businessId)->whereDate('test_date', today())->count(),
            'sessions_total'   => LabTestSession::where('business_id', $businessId)->count(),
            'unack_errors'     => LabDeviceError::unacknowledged()->count(),
        ];

        $recentSessions = LabTestSession::with('results')
            ->where('business_id', $businessId)
            ->latest('id')
            ->limit(8)
            ->get();

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

        return view('labCore::dashboard.index', [
            'stats'          => $stats,
            'recentSessions' => $recentSessions,
            'recentLogs'     => $recentLogs,
            'vendors'        => DriverRegistry::options(),
        ]);
    }
}
