<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxCommunicationLog;
use Modules\NX600Lab\Entities\NxWorklist;
use Modules\NX600Lab\Entities\Services\NxLabTrendsService;
use Modules\NX600Lab\Entities\Services\VetClinicSyncService;

/**
 * Endpoints used by the VetClinic side of the integration — i.e. the
 * "Lab Tests" tab rendered on a pet's profile and on the appointment screen.
 * Only reachable when the VetClinic module is installed and sync is enabled.
 */
class VetClinicBridgeController extends Controller
{
    /**
     * Raise an NX600 lab order for a VetClinic pet, straight from the
     * pet's profile or appointment page. Responds with JSON for AJAX callers.
     */
    public function storePetOrder(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.manage_worklist')) {
            abort(403, 'Unauthorized action.');
        }

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

        if (!VetClinicSyncService::syncEnabled($businessId)) {
            return $this->respond($request, [
                'success' => 0,
                'msg'     => 'VetClinic sync is disabled. Enable it in NX600 Lab settings first.',
            ]);
        }

        $request->validate([
            'vc_pet_id'  => 'required|integer',
            'sample_no'  => 'nullable|string|max:13',
            'test_names' => 'nullable|string',
        ]);

        $pet = \Modules\VetClinic\Entities\VcPet::where('business_id', $businessId)
            ->findOrFail($request->vc_pet_id);

        $sampleNo = trim((string) $request->sample_no) ?: NxWorklist::nextSampleNo();

        if (NxWorklist::withTrashed()->where('sample_no', $sampleNo)->exists()) {
            return $this->respond($request, [
                'success' => 0,
                'msg'     => "Sample number '{$sampleNo}' is already in use.",
            ]);
        }

        $tests = [];
        if ($request->filled('test_names')) {
            $tests = array_slice(array_values(array_filter(array_map(
                fn($n) => substr(trim($n), 0, 8),
                preg_split('/[,\r\n]+/', $request->test_names)
            ))), 0, 30);
        }

        $data = array_merge(
            VetClinicSyncService::worklistFieldsForPet($pet, $businessId),
            [
                'business_id' => $businessId,
                'sample_no'   => $sampleNo,
                'test_names'  => $tests,
                'is_sent'     => false,
                'created_by'  => auth()->id(),
            ]
        );

        NxWorklist::create($data);

        NxCommunicationLog::info(
            "Lab order created from VetClinic for pet '{$pet->petname}' (sample {$sampleNo})",
            'worklist',
            ['vc_pet_id' => $pet->id],
            null,
            $sampleNo
        );

        return $this->respond($request, [
            'success' => 1,
            'msg'     => "Lab order '{$sampleNo}' raised for {$pet->petname}.",
        ]);
    }

    /**
     * Return just the lab panel body (worklist + results) for a pet, as an
     * HTML fragment. Used by the "Refresh" control on the lab tab.
     */
    public function petPanel(Request $request, $petId)
    {
        if (!auth()->user()->can('nx600_lab.access_module')) {
            abort(403, 'Unauthorized action.');
        }

        if (!VetClinicSyncService::vetClinicInstalled()) {
            abort(404);
        }

        $businessId = $request->session()->get('user.business_id');
        $pet = \Modules\VetClinic\Entities\VcPet::where('business_id', $businessId)->findOrFail($petId);

        return view('nx600Lab::bridge._pet_lab_body', ['pet' => $pet]);
    }

    /**
     * Full-page lab-trends view for a VetClinic pet — line chart per parameter
     * plus a cumulative comparison table across all the pet's lab sessions.
     */
    public function petTrends(Request $request, $petId)
    {
        if (!auth()->user()->can('nx600_lab.access_module')) {
            abort(403, 'Unauthorized action.');
        }
        if (!VetClinicSyncService::vetClinicInstalled()) {
            abort(404);
        }

        $businessId = $request->session()->get('user.business_id');
        $pet = \Modules\VetClinic\Entities\VcPet::with('owner')
            ->where('business_id', $businessId)->findOrFail($petId);

        $trends = NxLabTrendsService::forPet((int) $pet->id, (int) $businessId);

        return view('nx600Lab::bridge.pet_lab_trends', compact('pet', 'trends'));
    }

    /**
     * JSON for AJAX callers, redirect-back for plain form posts.
     */
    private function respond(Request $request, array $result)
    {
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json($result, $result['success'] ? 200 : 422);
        }

        return back()->with('status', $result);
    }
}
