<?php

namespace Modules\NX600Lab\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\NX600Lab\Entities\NxModuleSetting;
use Modules\NX600Lab\Entities\NxTestSession;
use Modules\NX600Lab\Entities\Services\VetClinicSyncService;

class NxTestSessionController extends Controller
{
    public function index(Request $request)
    {
        if (!auth()->user()->can('nx600_lab.view_results')) {
            abort(403, 'Unauthorized action.');
        }

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

        $query = NxTestSession::with('testResults')
            ->where(fn($q) => $q->where('business_id', $businessId)->orWhereNull('business_id'));

        if ($request->filled('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('sample_no', 'like', "%{$s}%")
                  ->orWhere('patient_name', 'like', "%{$s}%")
                  ->orWhere('patient_id', 'like', "%{$s}%");
            });
        }
        if ($request->filled('date_from')) {
            $query->whereDate('test_date', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('test_date', '<=', $request->date_to);
        }
        if ($request->abnormal == '1') {
            $query->whereHas('testResults', fn($q) => $q->where('is_abnormal', true));
        }

        $sessions = $query->latest('test_date')->latest('test_time')->paginate(20)->withQueryString();

        return view('nx600Lab::sessions.index', compact('sessions'));
    }

    public function show(Request $request, $id)
    {
        if (!auth()->user()->can('nx600_lab.view_results')) {
            abort(403, 'Unauthorized action.');
        }

        $session = NxTestSession::with(['testResults', 'worklist'])->findOrFail($id);

        return view('nx600Lab::sessions.show', [
            'session' => $session,
            'pet'     => $this->resolvePet($session),
        ]);
    }

    /**
     * Print-friendly lab report (browser print -> PDF).
     */
    public function print(Request $request, $id)
    {
        if (!auth()->user()->can('nx600_lab.view_results')) {
            abort(403, 'Unauthorized action.');
        }

        $session = NxTestSession::with('testResults')->findOrFail($id);
        $businessId = $request->session()->get('user.business_id');

        return view('nx600Lab::sessions.print', [
            'session'  => $session,
            'pet'      => $this->resolvePet($session),
            'settings' => NxModuleSetting::allFor((int) $businessId),
        ]);
    }

    public function destroy(Request $request, $id)
    {
        if (!auth()->user()->can('nx600_lab.manage_results')) {
            abort(403, 'Unauthorized action.');
        }

        $session = NxTestSession::findOrFail($id);
        $session->testResults()->delete();
        $session->delete();

        return redirect()->route('nx.results.index')->with('status', [
            'success' => 1,
            'msg'     => 'Test session deleted.',
        ]);
    }

    private function resolvePet(NxTestSession $session)
    {
        if (!$session->vc_pet_id || !VetClinicSyncService::vetClinicInstalled()) {
            return null;
        }
        return \Modules\VetClinic\Entities\VcPet::with('owner')->find($session->vc_pet_id);
    }
}
