<?php

namespace App\Http\Controllers\Frontdesk;

use App\Http\Controllers\Controller;
use App\Models\Otp;
use App\Models\Patient;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;

class OtpController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();

        $query = Otp::query()->with('patient:id,full_name,email,phone')->latest('id');

        if (in_array($user->role, ['lab_manager', 'lab_staff'], true)) {
            $query->whereHas('patient.orders', static fn ($q) => $q->where('lab_id', $user->lab_id));
        }

        if ($term = trim((string) $request->query('q'))) {
            $query->where(function ($q) use ($term): void {
                $q->where('identifier', 'like', "%{$term}%")
                    ->orWhereHas('patient', static function ($p) use ($term): void {
                        $p->where('full_name', 'like', "%{$term}%")
                            ->orWhere('email', 'like', "%{$term}%")
                            ->orWhere('phone', 'like', "%{$term}%");
                    });
            });
        }

        $otps = $query->paginate(20)->withQueryString();

        return view('frontdesk.otps.index', compact('otps'));
    }
}
