<?php

namespace Modules\OphthalmologyClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcPatient;
use Modules\OphthalmologyClinic\Entities\OpthGlassesRx;

/**
 * Glasses (spectacle) prescriptions + the standard optical Rx print view.
 * Business-scoped, gated by opth.glasses_rx.manage.
 */
class OpthGlassesRxController extends Controller
{
    private function biz()
    {
        return session('user.business_id');
    }

    private function guardPatient($patientId): ClcPatient
    {
        if (! auth()->user() || ! auth()->user()->can('opth.glasses_rx.manage')) {
            abort(403, 'Unauthorized action.');
        }
        return ClcPatient::where('business_id', $this->biz())->findOrFail($patientId);
    }

    public function store(Request $request, $patientId)
    {
        $patient = $this->guardPatient($patientId);

        $data = $request->validate([
            'appointment_id' => 'nullable|integer',
            'sphere_od'      => 'nullable|numeric', 'sphere_os'   => 'nullable|numeric',
            'cylinder_od'    => 'nullable|numeric', 'cylinder_os' => 'nullable|numeric',
            'axis_od'        => 'nullable|integer|min:0|max:180', 'axis_os' => 'nullable|integer|min:0|max:180',
            'add_od'         => 'nullable|numeric', 'add_os'      => 'nullable|numeric',
            'pd_mm'          => 'nullable|numeric|min:0|max:99',
            'lens_type'      => 'nullable|string|in:' . implode(',', array_keys(OpthGlassesRx::LENS_TYPES)),
            'notes'          => 'nullable|string|max:1000',
        ]);

        $blank = fn ($k) => (array_key_exists($k, $data) && $data[$k] !== '') ? $data[$k] : null;

        $rx = OpthGlassesRx::create([
            'business_id'    => $this->biz(),
            'patient_id'     => $patient->id,
            'appointment_id' => $blank('appointment_id'),
            'sphere_od'      => $blank('sphere_od'),   'sphere_os'   => $blank('sphere_os'),
            'cylinder_od'    => $blank('cylinder_od'), 'cylinder_os' => $blank('cylinder_os'),
            'axis_od'        => $blank('axis_od'),     'axis_os'     => $blank('axis_os'),
            'add_od'         => $blank('add_od'),      'add_os'      => $blank('add_os'),
            'pd_mm'          => $blank('pd_mm'),
            'lens_type'      => $blank('lens_type'),
            'notes'          => $blank('notes'),
            'prescribed_by'  => auth()->id(),
            'prescribed_at'  => now(),
        ]);

        return response()->json([
            'success'     => true,
            'rx_id'       => $rx->id,
            'print_url'   => route('opth.glasses.print', [$patient->id, $rx->id]),
            'msg'         => 'Glasses prescription saved.',
        ]);
    }

    public function destroy($patientId, $rxId)
    {
        $patient = $this->guardPatient($patientId);

        $rx = OpthGlassesRx::where('business_id', $this->biz())
            ->where('patient_id', $patient->id)->findOrFail($rxId);
        $rx->delete();

        return response()->json(['success' => true, 'msg' => 'Prescription deleted.']);
    }

    /** Standard optical Rx print layout. */
    public function print($patientId, $rxId)
    {
        $patient = $this->guardPatient($patientId);

        $rx = OpthGlassesRx::where('business_id', $this->biz())
            ->where('patient_id', $patient->id)->findOrFail($rxId);

        $business = \App\Business::find($this->biz());

        return view('ophthClinic::glasses.print', compact('patient', 'rx', 'business'));
    }
}
