<?php

namespace Modules\NX600Lab\Http\Controllers;

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

/**
 * Standalone patient registry. Used when the VetClinic module is not synced;
 * synced deployments raise lab orders against VetClinic pets instead.
 */
class NxPatientController extends Controller
{
    public function index(Request $request)
    {
        $this->authorizeAccess();

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

        $query = NxPatient::where('business_id', $businessId);
        if ($request->filled('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('patient_name', 'like', "%{$s}%")
                  ->orWhere('patient_id', 'like', "%{$s}%");
            });
        }

        $patients = $query->latest('id')->paginate(20)->withQueryString();

        return view('nx600Lab::patients.index', [
            'patients'   => $patients,
            'speciesMap' => NxModuleSetting::speciesMap($businessId),
        ]);
    }

    public function store(Request $request)
    {
        $this->authorizeAccess();

        $request->validate([
            'patient_name' => 'required|string|max:60',
            'patient_id'   => 'nullable|string|max:13',
            'sex'          => 'required|integer',
            'age'          => 'nullable|integer|min:0|max:999',
            'species'      => 'required|integer',
        ]);

        NxPatient::create([
            'business_id'  => $request->session()->get('user.business_id'),
            'patient_name' => $request->patient_name,
            'patient_id'   => $request->patient_id,
            'sex'          => (int) $request->sex,
            'age'          => (int) ($request->age ?? 999),
            'species'      => (int) $request->species,
        ]);

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

    public function update(Request $request, $id)
    {
        $this->authorizeAccess();

        $businessId = $request->session()->get('user.business_id');
        $patient = NxPatient::where('business_id', $businessId)->findOrFail($id);

        $request->validate([
            'patient_name' => 'required|string|max:60',
            'patient_id'   => 'nullable|string|max:13',
            'sex'          => 'required|integer',
            'age'          => 'nullable|integer|min:0|max:999',
            'species'      => 'required|integer',
        ]);

        $patient->update([
            'patient_name' => $request->patient_name,
            'patient_id'   => $request->patient_id,
            'sex'          => (int) $request->sex,
            'age'          => (int) ($request->age ?? 999),
            'species'      => (int) $request->species,
        ]);

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

    public function destroy(Request $request, $id)
    {
        $this->authorizeAccess();

        $businessId = $request->session()->get('user.business_id');
        NxPatient::where('business_id', $businessId)->findOrFail($id)->delete();

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

    private function authorizeAccess(): void
    {
        if (!auth()->user()->can('nx600_lab.manage_patients')) {
            abort(403, 'Unauthorized action.');
        }
    }
}
