<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Modules\ClinicCore\Entities\ClcImagingModality;
use Modules\ClinicCore\Entities\ClcImagingRequest;
use Modules\ClinicCore\Entities\ClcImagingStudy;
use Modules\ClinicCore\Entities\ClcPatient;

/**
 * Imaging worklist — mirrors the NX600 lab worklist UX. Requests can be
 * created from a pet/appointment context; result media is uploaded onto
 * the request and shown back to the clinician (inline preview for JPG/PNG,
 * download link for PDF/DICOM).
 */
class ClcImagingController extends Controller
{
    use \Modules\ClinicCore\Http\Controllers\Traits\LogsClcActivity;

    private function biz() { return request()->session()->get('user.business_id'); }

    public function index()
    {
        if (!auth()->user()->can('clinic.view_imaging')) abort(403);

        $modalities = ClcImagingModality::forBusiness((int) $this->biz())
            ->where('status', 'active')->orderBy('sort_order')->get();
        $requests = ClcImagingRequest::with(['pet:id,patient_name,species', 'modality:id,code,name', 'studies'])
            ->where('business_id', $this->biz())
            ->orderByDesc('id')->paginate(30);

        return view('clinicCore::imaging.index', compact('requests', 'modalities'));
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('clinic.manage_imaging')) abort(403);
        $request->validate([
            'patient_id'      => 'required|integer',
            'modality_id' => 'required|integer',
            'body_region' => 'nullable|string|max:120',
            'indication'  => 'nullable|string|max:1000',
            'priority'    => 'nullable|in:routine,urgent,stat',
            'appointment_id' => 'nullable|integer',
        ]);

        $businessId = $this->biz();
        $patient = ClcPatient::where('business_id', $businessId)->findOrFail($request->patient_id);

        $req = ClcImagingRequest::create([
            'business_id'    => $businessId,
            'ref_no'         => ClcImagingRequest::nextRefNo($businessId),
            'patient_id'         => $patient->id,
            'contact_id'     => $patient->contact_id ?? null,
            'appointment_id' => $request->appointment_id,
            'modality_id'    => $request->modality_id,
            'body_region'    => $request->body_region,
            'indication'     => $request->indication,
            'priority'       => $request->priority ?: 'routine',
            'status'         => 'requested',
            'requested_by'   => auth()->id(),
            'requested_at'   => now(),
        ]);
        $this->drmLog('create', $req);

        return response()->json(['success' => true, 'id' => $req->id, 'ref_no' => $req->ref_no]);
    }

    public function updateStatus(Request $request, $id)
    {
        if (!auth()->user()->can('clinic.manage_imaging')) abort(403);
        $request->validate([
            'status' => 'required|in:requested,in_progress,reported,cancelled',
            'report' => 'nullable|string',
        ]);

        $req = ClcImagingRequest::where('business_id', $this->biz())->findOrFail($id);
        $update = ['status' => $request->status, 'report' => $request->report];
        if ($request->status === 'in_progress' && !$req->completed_at) {
            // no-op; mark when scan actually done
        }
        if ($request->status === 'reported') {
            $update['reported_at'] = now();
            $update['reported_by'] = auth()->id();
            if (!$req->completed_at) $update['completed_at'] = now();
        }
        $req->update($update);
        $this->drmLog('update', $req, ['action' => 'status_changed', 'status' => $request->status]);

        return response()->json(['success' => true]);
    }

    public function uploadStudy(Request $request, $id)
    {
        if (!auth()->user()->can('clinic.manage_imaging')) abort(403);
        $request->validate([
            'file'     => 'required|file|max:51200',
            // SIFA P5-T1 — optional radiation-dose capture on upload.
            'dose_dap' => 'nullable|numeric|min:0',
            'dose_dlp' => 'nullable|numeric|min:0',
            'ctdivol'  => 'nullable|numeric|min:0',
        ]);

        $req = ClcImagingRequest::where('business_id', $this->biz())->findOrFail($id);
        $file = $request->file('file');
        $path = $file->store("clc_imaging/{$this->biz()}/{$req->id}", 'public');

        $study = ClcImagingStudy::create([
            'imaging_request_id' => $req->id,
            'file_path'          => $path,
            'original_name'      => $file->getClientOriginalName(),
            'file_mime'          => $file->getMimeType(),
            'file_size'          => $file->getSize(),
            'uploaded_by'        => auth()->id(),
            'uploaded_at'        => now(),
            'notes'              => $request->notes,
            'dose_dap'           => $request->filled('dose_dap') ? $request->dose_dap : null,
            'dose_dlp'           => $request->filled('dose_dlp') ? $request->dose_dlp : null,
            'ctdivol'            => $request->filled('ctdivol') ? $request->ctdivol : null,
        ]);

        // Bump the request to in_progress once any media lands.
        if ($req->status === 'requested') {
            $req->update(['status' => 'in_progress']);
        }

        return response()->json([
            'success'   => true,
            'study_id'  => $study->id,
            'url'       => $study->file_url,
            'is_image'  => $study->is_image,
            'is_dicom'  => $study->is_dicom,
        ]);
    }

    public function deleteStudy(Request $request, $studyId)
    {
        if (!auth()->user()->can('clinic.manage_imaging')) abort(403);
        $study = ClcImagingStudy::findOrFail($studyId);
        $req = ClcImagingRequest::where('business_id', $this->biz())->findOrFail($study->imaging_request_id);
        if ($study->file_path) Storage::disk('public')->delete($study->file_path);
        $study->delete();
        return response()->json(['success' => true]);
    }
}
