<?php

namespace Modules\LabCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\LabCore\Entities\LabDevice;
use Modules\LabCore\Entities\LabWorklist;
use Modules\LabCore\Entities\Services\DriverRegistry;

class LabWorklistController extends Controller
{
    private function authorizeLab(): void
    {
        if (!auth()->user()->can('lab.manage_worklist')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->authorizeLab();
        $businessId = request()->session()->get('user.business_id');

        $entries = LabWorklist::with('device')
            ->where('business_id', $businessId)
            ->latest('id')
            ->paginate(25);

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

    public function create()
    {
        $this->authorizeLab();
        $businessId = request()->session()->get('user.business_id');

        $devices = LabDevice::where('business_id', $businessId)->orderBy('name')->get();
        $vendors = DriverRegistry::all();

        return view('labCore::worklist.create', compact('devices', 'vendors'));
    }

    public function store(Request $request)
    {
        $this->authorizeLab();
        $data = $request->validate([
            'vendor'       => 'required|string|max:30',
            'device_id'    => 'nullable|integer|exists:lab_devices,id',
            'sample_no'    => 'required|string|max:30',
            'patient_id'   => 'nullable|string|max:30',
            'patient_name' => 'nullable|string|max:80',
            'species'      => 'nullable|string|max:40',
            'sex'          => 'nullable|string|max:10',
            'age'          => 'nullable|integer|min:0|max:999',
            'tests'        => 'nullable|string',
        ]);

        $device = $data['device_id'] ? LabDevice::find($data['device_id']) : null;

        LabWorklist::create([
            'business_id'  => $request->session()->get('user.business_id'),
            'agent_id'     => $device?->agent_id,
            'device_id'    => $data['device_id'] ?? null,
            'vendor'       => $data['vendor'],
            'sample_no'    => $data['sample_no'],
            'patient_id'   => $data['patient_id'] ?? null,
            'patient_name' => $data['patient_name'] ?? null,
            'species'      => $data['species'] ?? null,
            'sex'          => $data['sex'] ?? null,
            'age'          => $data['age'] ?? null,
            'tests'        => !empty($data['tests'])
                ? array_values(array_filter(array_map('trim', explode(',', $data['tests']))))
                : null,
            'status'       => 'pending',
            'created_by'   => auth()->id(),
        ]);

        return redirect()->route('lab.worklist.index')->with('status', [
            'success' => 1, 'msg' => 'Worklist entry added.',
        ]);
    }

    public function destroy($id)
    {
        $this->authorizeLab();
        LabWorklist::findOrFail($id)->delete();

        return redirect()->route('lab.worklist.index')->with('status', [
            'success' => 1, 'msg' => 'Worklist entry removed.',
        ]);
    }
}
