<?php

namespace Modules\LabCore\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\LabCore\Entities\LabTestSession;

class LabSessionController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('lab.view_results')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $sessions = LabTestSession::withCount('results')
            ->where('business_id', $businessId)
            ->latest('id')
            ->paginate(25);

        return view('labCore::sessions.index', compact('sessions'));
    }

    public function show($id)
    {
        if (!auth()->user()->can('lab.view_results')) {
            abort(403, 'Unauthorized action.');
        }
        $businessId = request()->session()->get('user.business_id');

        $session = LabTestSession::with('results', 'device', 'agent')
            ->where('business_id', $businessId)
            ->findOrFail($id);

        return view('labCore::sessions.show', compact('session'));
    }

    public function destroy($id)
    {
        if (!auth()->user()->can('lab.manage_results')) {
            abort(403, 'Unauthorized action.');
        }
        $session = LabTestSession::findOrFail($id);
        $session->results()->delete();
        $session->delete();

        return redirect()->route('lab.results.index')->with('status', [
            'success' => 1, 'msg' => 'Session deleted.',
        ]);
    }
}
