<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetClinic\Entities\VcVaccination;
use Modules\VetClinic\Entities\VcVaccineType;
use Modules\VetClinic\Entities\VcPet;
use Modules\VetClinic\Entities\VcModuleSetting;
use Modules\VetClinic\Entities\VcDoctor;
use Carbon\Carbon;
use Yajra\DataTables\Facades\DataTables;

class VcVaccinationController extends Controller
{
    use \Modules\VetClinic\Http\Controllers\Traits\LogsVcActivity;

    public function index()
    {
        if (!auth()->user()->can('vet_clinic.manage_vaccinations')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId   = request()->session()->get('user.business_id');
        $today        = Carbon::today();
        $reminderDays = (int) VcModuleSetting::get($businessId, 'reminder_days', 30);

        // Only track not_taken, non-waived records for due/overdue counts
        $base = VcVaccination::where('business_id', $businessId)
            ->where('taken_status', 'not_taken')
            ->whereNull('waived_at');

        $stats = [
            'overdue'  => (clone $base)->where('administered_date', '<', $today)->count(),
            'due_soon' => (clone $base)->whereBetween('administered_date', [$today, $today->copy()->addDays(30)])->count(),
            'upcoming' => (clone $base)->where('administered_date', '>', $today->copy()->addDays(30))->count(),
            'total'    => VcVaccination::where('business_id', $businessId)->count(),
            'waived'   => VcVaccination::where('business_id', $businessId)->whereNotNull('waived_at')->count(),
        ];

        $urgentVaccinations = (clone $base)
            ->where('administered_date', '<=', $today->copy()->addDays($reminderDays))
            ->with(['pet.owner', 'vaccineType'])
            ->orderBy('administered_date')
            ->limit(30)
            ->get();

        $doctors = VcDoctor::where('business_id', $businessId)->active()->orderBy('name')->get();

        return view('vetClinic::vaccinations.index', compact('stats', 'urgentVaccinations', 'reminderDays', 'doctors'));
    }

    public function list(Request $request)
    {
        if (!auth()->user()->can('vet_clinic.manage_vaccinations')) {
            abort(403, 'Unauthorized action.');
        }

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

        $query = VcVaccination::with(['pet.owner', 'vaccineType'])
            ->where('business_id', $businessId);

        // Status quick-filter (overdue / due_soon / upcoming / waived)
        if ($request->status === 'waived') {
            $query->whereNotNull('waived_at');
        } elseif ($request->status) {
            // Active due-status filters always exclude waived records
            $query->whereNull('waived_at');
            if ($request->status === 'overdue') {
                $query->where('taken_status', 'not_taken')
                      ->where('administered_date', '<', $today);
            } elseif ($request->status === 'due_soon') {
                $query->where('taken_status', 'not_taken')
                      ->whereBetween('administered_date', [$today, $today->copy()->addDays(30)]);
            } elseif ($request->status === 'upcoming') {
                $query->where('taken_status', 'not_taken')
                      ->where('administered_date', '>', $today->copy()->addDays(30));
            }
        }

        // Taken-status filter (At Clinic / External / Not Taken)
        if ($request->filled('taken_status')) {
            $query->where('taken_status', $request->taken_status);
        }

        if ($request->category) {
            $query->whereHas('vaccineType', fn($q) => $q->where('category', $request->category));
        }
        if ($request->vaccine_type_id) {
            $query->where('vaccine_type_id', $request->vaccine_type_id);
        }

        // Date range filter on the "effective due date":
        // - not_taken records → administered_date IS the due date for this dose
        // - taken records     → next_due_date    IS when the next dose is due
        if ($request->filter_due_from || $request->filter_due_to) {
            $from = $request->filter_due_from;
            $to   = $request->filter_due_to;
            $query->where(function ($q) use ($from, $to) {
                $q->where(function ($sq) use ($from, $to) {
                    $sq->where('taken_status', 'not_taken');
                    if ($from) $sq->whereDate('administered_date', '>=', $from);
                    if ($to)   $sq->whereDate('administered_date', '<=', $to);
                })->orWhere(function ($sq) use ($from, $to) {
                    $sq->whereIn('taken_status', ['taken_in', 'taken_out']);
                    if ($from) $sq->whereDate('next_due_date', '>=', $from);
                    if ($to)   $sq->whereDate('next_due_date', '<=', $to);
                });
            });
        }

        $dateFormat = session('business.date_format', 'd M Y');

        return DataTables::of($query)
            ->addColumn('administered_date_col', fn($row) => $row->administered_date
                ? \Carbon\Carbon::parse($row->administered_date)->format($dateFormat) : '—')
            ->addColumn('pet_col', function ($row) {
                $name    = optional($row->pet)->petname ?? '—';
                $url     = $row->pet ? route('vc.pets.show', $row->pet->id) : '#';
                $species = optional($row->pet)->species
                    ? '<small class="text-muted"> · ' . e($row->pet->species) . '</small>' : '';
                return '<a href="' . $url . '" style="font-weight:600;">' . e($name) . '</a>' . $species;
            })
            ->addColumn('owner_col', function ($row) {
                $owner  = optional($row->pet)->owner;
                $name   = optional($owner)->name ?? '—';
                $mobile = optional($owner)->mobile ?? '';
                if (!$owner) return '—';
                $detailId = \Modules\VetClinic\Entities\VcPetOwnerDetail::where('contact_id', $owner->id)->value('id');
                $url = $detailId ? route('vc.pet-owners.show', $detailId) : '#';
                return '<a href="' . $url . '" style="font-weight:600;">' . e($name) . '</a>'
                    . ($mobile ? '<br><small class="text-muted"><i class="fa fa-phone"></i> ' . e($mobile) . '</small>' : '');
            })
            ->addColumn('vaccine_name', fn($row) => optional($row->vaccineType)->name ?? '—')
            ->addColumn('due_col', function ($row) use ($today, $dateFormat) {
                // Waived records get a special badge
                if ($row->waived_at) {
                    $reasonLabels = [
                        'deceased'        => 'Pet Deceased',
                        'refused'         => 'Owner Refused',
                        'contraindicated' => 'Contraindicated',
                        'other'           => 'Other',
                    ];
                    $reasonLabel = $reasonLabels[$row->waived_reason] ?? ($row->waived_reason ?? 'Waived');
                    $waivedFmt   = $row->waived_at->format($dateFormat);
                    return '<span class="label label-default" style="background:#78909c;"><i class="fa fa-ban"></i> Waived</span>'
                         . '<br><small class="text-muted" style="font-size:10px;">' . e($reasonLabel) . ' · ' . $waivedFmt . '</small>';
                }

                // not_taken → administered_date IS the due date for this scheduled dose
                // taken     → next_due_date IS when the next dose is due
                $effectiveDue = ($row->taken_status === 'not_taken')
                    ? $row->administered_date
                    : $row->next_due_date;
                if (!$effectiveDue) return '—';
                $days      = (int) $today->diffInDays($effectiveDue, false);
                $formatted = \Carbon\Carbon::parse($effectiveDue)->format($dateFormat);
                if ($days < 0) {
                    $badge = '<span class="label label-danger"><i class="fa fa-exclamation-circle"></i> ' . abs($days) . ' days overdue</span>';
                } elseif ($days === 0) {
                    $badge = '<span class="label label-warning"><i class="fa fa-clock"></i> Due today</span>';
                } elseif ($days <= 30) {
                    $badge = '<span class="label label-warning">In ' . $days . ' days</span>';
                } else {
                    $badge = '<span class="label label-success">In ' . $days . ' days</span>';
                }
                return '<div style="font-size:12px;">' . $formatted . '</div>' . $badge;
            })
            ->addColumn('status_badge', function ($row) {
                $takenMap = [
                    'taken_in'  => ['label' => '<i class="fa fa-hospital"></i> Clinic',   'class' => 'success'],
                    'taken_out' => ['label' => '<i class="fa fa-home"></i> External',     'class' => 'info'],
                    'not_taken' => ['label' => '<i class="fa fa-clock"></i> Not Taken', 'class' => 'warning'],
                ];
                if ($row->taken_status && isset($takenMap[$row->taken_status])) {
                    $t = $takenMap[$row->taken_status];
                    return '<span class="label label-' . $t['class'] . '">' . $t['label'] . '</span>';
                }
                $colors = ['administered' => 'success', 'scheduled' => 'info', 'cancelled' => 'default'];
                return '<span class="label label-' . ($colors[$row->status] ?? 'default') . '">' . ucfirst($row->status) . '</span>';
            })
            ->addColumn('reminder_col', function ($row) {
                if ($row->reminder_sent) {
                    return '<span class="label label-success" style="font-size:11px;"><i class="fa fa-check"></i> Sent</span>';
                }
                if ($row->next_due_date) {
                    return '<button class="btn btn-xs btn-warning btn-mark-reminded" data-id="' . $row->id . '" title="Mark reminder sent"><i class="fa fa-bell"></i> Remind</button>';
                }
                return '—';
            })
            ->addColumn('action', function ($row) {
                $owner      = optional($row->pet)->owner;
                $phone      = preg_replace('/[^0-9]/', '', optional($owner)->mobile ?? '');
                if ($phone && substr($phone, 0, 1) === '0') { $phone = '20' . substr($phone, 1); }
                $ownerEmail = optional($owner)->email ?? '';
                $petName    = e(optional($row->pet)->petname ?? 'your pet');
                $vaccineName= e(optional($row->vaccineType)->name ?? 'vaccination');
                $ownerName  = e(optional($owner)->name ?? 'Pet Owner');
                $dueDate    = $row->administered_date
                    ? \Carbon\Carbon::parse($row->administered_date)->format(session('business.date_format', 'd M Y')) : '';

                $petLink = $row->pet
                    ? '<a href="' . route('vc.pets.show', $row->pet->id) . '" class="btn btn-xs btn-info" title="Pet Profile"><i class="fa fa-paw"></i></a> '
                    : '';

                $viewBtn = '<button class="btn btn-xs btn-default btn-vax-view" data-id="' . $row->id . '" title="View Details"><i class="fa fa-eye"></i></button> ';
                $editBtn = '<button class="btn btn-xs btn-warning btn-vax-edit" data-id="' . $row->id . '" title="Edit"><i class="fa fa-edit"></i></button> ';

                $waMsg = rawurlencode("Dear {$ownerName}, this is a reminder that {$petName} is due for {$vaccineName} vaccination on {$dueDate}. Please contact us to schedule an appointment.");
                $wa = $phone
                    ? '<a href="https://wa.me/' . $phone . '?text=' . $waMsg . '" target="_blank" class="btn btn-xs btn-success" title="WhatsApp Reminder"><i class="fab fa-whatsapp"></i></a> '
                    : '';

                $email = $ownerEmail
                    ? '<button class="btn btn-xs btn-primary btn-email-remind" data-id="' . $row->id . '"
                         data-email="' . e($ownerEmail) . '" data-owner="' . $ownerName . '"
                         data-pet="' . $petName . '" data-vaccine="' . $vaccineName . '" data-due="' . e($dueDate) . '"
                         title="Email Reminder: ' . e($ownerEmail) . '"><i class="fa fa-envelope"></i></button> '
                    : '<button class="btn btn-xs btn-default" disabled title="No email on file"><i class="fa fa-envelope text-muted"></i></button> ';

                $del = '<button class="btn btn-xs btn-danger btn-delete-vaccination" data-id="' . $row->id . '" title="Delete"><i class="fa fa-trash"></i></button>';

                if ($row->waived_at) {
                    $waiveBtn = '<button class="btn btn-xs btn-default btn-unwaive-vax" data-id="' . $row->id . '" title="Remove Waiver — restore to active"><i class="fa fa-undo"></i></button> ';
                } else {
                    $waiveBtn = '<button class="btn btn-xs btn-secondary btn-waive-vax" data-id="' . $row->id . '" data-pet="' . $petName . '" data-vaccine="' . $vaccineName . '" title="Waive this vaccination" style="background:#78909c;color:#fff;"><i class="fa fa-ban"></i></button> ';
                }

                return $petLink . $viewBtn . $editBtn . $waiveBtn . $wa . $email . $del;
            })
            ->rawColumns(['action', 'status_badge', 'pet_col', 'owner_col', 'due_col', 'reminder_col', 'administered_date_col'])
            ->make(true);
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('vet_clinic.manage_vaccinations')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'pet_id'           => 'required|integer',
            'vaccine_type_id'  => 'required|integer',
            'administered_date' => 'required|date',
        ]);

        $businessId  = request()->session()->get('user.business_id');
        $pet         = VcPet::where('business_id', $businessId)->findOrFail($request->pet_id);
        $vaccineType = VcVaccineType::findOrFail($request->vaccine_type_id);

        $nextDue = $request->next_due_date
            ?? Carbon::parse($request->administered_date)->addMonths($vaccineType->valid_for_months)->toDateString();

        $takenStatus = $request->taken_status ?: 'taken_in';
        $recordStatus = in_array($takenStatus, ['taken_in', 'taken_out']) ? 'administered' : 'scheduled';

        $vax = VcVaccination::create([
            'business_id'         => $businessId,
            'pet_id'              => $pet->id,
            'contact_id'          => $pet->contact_id,
            'vaccine_type_id'     => $request->vaccine_type_id,
            'dose'                => $request->dose,
            'appointment_id'      => $request->appointment_id,
            'medicine_id'         => $request->medicine_id,
            'batch_no'            => $request->batch_no,
            'administered_date'   => $request->administered_date,
            'next_due_date'       => $nextDue,
            'administered_by'     => $request->administered_by,
            'weight_at_time'      => $request->weight_at_time,
            'temperature_at_time' => $request->temperature_at_time,
            'status'              => $recordStatus,
            'taken_status'        => $takenStatus,
            'notes'               => $request->notes,
        ]);

        // Auto-create next scheduled record if vaccine was actually taken and has a next due date
        if (in_array($takenStatus, ['taken_in', 'taken_out']) && $nextDue) {
            $alreadyExists = VcVaccination::where('pet_id', $pet->id)
                ->where('vaccine_type_id', $request->vaccine_type_id)
                ->where('administered_date', $nextDue)
                ->where('taken_status', 'not_taken')
                ->exists();

            if (!$alreadyExists) {
                $nextNextDue = Carbon::parse($nextDue)->addMonths($vaccineType->valid_for_months)->toDateString();
                VcVaccination::create([
                    'business_id'     => $businessId,
                    'pet_id'          => $pet->id,
                    'contact_id'      => $pet->contact_id,
                    'vaccine_type_id' => $request->vaccine_type_id,
                    'administered_date'=> $nextDue,
                    'next_due_date'   => $nextNextDue,
                    'status'          => 'scheduled',
                    'taken_status'    => 'not_taken',
                ]);
            }
        }

        $this->vcLog('create', $vax);
        $dateFormat = session('business.date_format', 'd M Y');
        return response()->json([
            'success'     => true,
            'msg'         => __('vetClinic::lang.saved_successfully'),
            'vaccination' => [
                'id'                  => $vax->id,
                'vaccine_name'        => $vaccineType->name,
                'taken_status'        => $vax->taken_status,
                'dose'                => $vax->dose,
                'administered_date'   => Carbon::parse($vax->administered_date)->format($dateFormat),
                'next_due_date'       => $nextDue ? Carbon::parse($nextDue)->format($dateFormat) : null,
                'batch_no'            => $vax->batch_no,
                'weight_at_time'      => $vax->weight_at_time,
                'temperature_at_time' => $vax->temperature_at_time,
                'notes'               => $vax->notes,
            ],
        ]);
    }

    public function edit($id)
    {
        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::with(['vaccineType', 'pet.owner'])->where('business_id', $businessId)->findOrFail($id);
        $dateFormat = session('business.date_format', 'd M Y');

        return response()->json(array_merge($vax->toArray(), [
            'vaccine_type_name'         => optional($vax->vaccineType)->name,
            'vaccine_type_manufacturer' => optional($vax->vaccineType)->manufacturer,
            'vaccine_type_category'     => optional($vax->vaccineType)->category,
            'pet_name'                  => optional($vax->pet)->petname,
            'pet_species'               => optional($vax->pet)->species,
            'pet_breed'                 => optional($vax->pet)->breed,
            'owner_name'                => optional(optional($vax->pet)->owner)->name,
            'owner_mobile'              => optional(optional($vax->pet)->owner)->mobile,
            'administered_date_iso'     => $vax->administered_date ? $vax->administered_date->format('Y-m-d') : null,
            'next_due_date_iso'         => $vax->next_due_date ? $vax->next_due_date->format('Y-m-d') : null,
            'administered_date_fmt'     => $vax->administered_date ? $vax->administered_date->format($dateFormat) : null,
            'next_due_date_fmt'         => $vax->next_due_date ? $vax->next_due_date->format($dateFormat) : null,
            'vaccine_types'             => VcVaccineType::active()->forBusiness($businessId)->orderBy('name')->get(['id', 'name'])->toArray(),
            'doctors_list'              => VcDoctor::where('business_id', $businessId)->active()->orderBy('name')->get(['id', 'name'])->toArray(),
        ]));
    }

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

        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::where('business_id', $businessId)->findOrFail($id);

        $data = $request->only(['vaccine_type_id', 'dose', 'administered_date', 'next_due_date',
                                 'batch_no', 'weight_at_time', 'temperature_at_time', 'notes',
                                 'status', 'taken_status']);

        // Sync status with taken_status
        if (isset($data['taken_status'])) {
            $data['status'] = in_array($data['taken_status'], ['taken_in', 'taken_out']) ? 'administered' : 'scheduled';
        }

        $prevTakenStatus = $vax->taken_status;
        $original = $vax->getOriginal();
        $vax->update($data);
        $dirty = array_keys($vax->getChanges());
        if ($dirty) {
            $this->vcLog('update', $vax, [
                'before' => array_intersect_key($original, array_flip($dirty)),
                'after'  => array_intersect_key($vax->getAttributes(), array_flip($dirty)),
                'fields' => $dirty,
            ]);
        }

        // Auto-create next scheduled record if vaccine was just marked as taken
        $nowTaken = in_array($data['taken_status'] ?? '', ['taken_in', 'taken_out']);
        $wasNotTaken = in_array($prevTakenStatus, ['not_taken', null]);
        if ($nowTaken && $wasNotTaken && $vax->next_due_date && $vax->vaccine_type_id) {
            $vaccineType = VcVaccineType::find($vax->vaccine_type_id);
            $nextDue = $vax->next_due_date->format('Y-m-d');
            $alreadyExists = VcVaccination::where('pet_id', $vax->pet_id)
                ->where('vaccine_type_id', $vax->vaccine_type_id)
                ->where('administered_date', $nextDue)
                ->where('taken_status', 'not_taken')
                ->exists();
            if (!$alreadyExists && $vaccineType) {
                $nextNextDue = Carbon::parse($nextDue)->addMonths($vaccineType->valid_for_months)->toDateString();
                VcVaccination::create([
                    'business_id'      => $businessId,
                    'pet_id'           => $vax->pet_id,
                    'contact_id'       => $vax->contact_id,
                    'vaccine_type_id'  => $vax->vaccine_type_id,
                    'administered_date'=> $nextDue,
                    'next_due_date'    => $nextNextDue,
                    'status'           => 'scheduled',
                    'taken_status'     => 'not_taken',
                ]);
            }
        }

        return response()->json(['success' => true, 'msg' => __('vetClinic::lang.updated_successfully')]);
    }

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

        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::where('business_id', $businessId)->findOrFail($id);
        $snap = $vax->getAttributes();
        $this->vcLog('delete', $vax, ['before' => $this->_vcFilterAttrs($snap)]);
        $vax->delete();

        return response()->json(['success' => true, 'msg' => __('vetClinic::lang.deleted_successfully')]);
    }

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

        $request->validate([
            'reason' => 'required|in:deceased,refused,contraindicated,other',
            'note'   => 'nullable|string|max:255',
        ]);

        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::where('business_id', $businessId)->findOrFail($id);

        $vax->update([
            'waived_at'     => now(),
            'waived_reason' => $request->reason,
            'waived_note'   => $request->note,
            'waived_by'     => auth()->id(),
        ]);
        $this->vcLog('waive', $vax, ['after' => ['waived_reason' => $request->reason, 'waived_note' => $request->note]]);

        return response()->json(['success' => true, 'msg' => 'Vaccination waived successfully.']);
    }

    public function unwaive($id)
    {
        if (!auth()->user()->can('vet_clinic.manage_vaccinations')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::where('business_id', $businessId)->findOrFail($id);

        $vax->update([
            'waived_at'     => null,
            'waived_reason' => null,
            'waived_note'   => null,
            'waived_by'     => null,
        ]);
        $this->vcLog('unwaive', $vax);

        return response()->json(['success' => true, 'msg' => 'Waiver removed — vaccination restored.']);
    }

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

        $businessId = request()->session()->get('user.business_id');
        VcVaccination::where('business_id', $businessId)->findOrFail($id)->update(['reminder_sent' => true]);

        return response()->json(['success' => true, 'msg' => __('vetClinic::lang.reminder_marked')]);
    }

    public function sendEmailReminder($id)
    {
        if (!auth()->user()->can('vet_clinic.manage_vaccinations')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $vax = VcVaccination::with(['pet.owner', 'vaccineType'])->where('business_id', $businessId)->findOrFail($id);

        $owner = optional($vax->pet)->owner;
        $email = optional($owner)->email ?? null;
        if (!$email) {
            return response()->json(['success' => false, 'msg' => 'Owner has no email address.']);
        }

        $petName     = optional($vax->pet)->petname ?? 'your pet';
        $vaccineName = optional($vax->vaccineType)->name ?? 'vaccination';
        $ownerName   = optional($owner)->name ?? 'Pet Owner';
        $dueDate     = $vax->administered_date
            ? Carbon::parse($vax->administered_date)->format(session('business.date_format', 'd M Y'))
            : 'soon';
        $business = \App\Business::find($businessId);
        $businessName = optional($business)->name ?? 'Vet Clinic';

        try {
            \Mail::raw(
                "Dear {$ownerName},\n\n"
                . "This is a friendly reminder that your pet {$petName} is due for their {$vaccineName} vaccination on {$dueDate}.\n\n"
                . "Please contact us to schedule an appointment at your earliest convenience.\n\n"
                . "Best regards,\n{$businessName}",
                function ($message) use ($email, $ownerName, $vaccineName, $petName) {
                    $message->to($email, $ownerName)
                            ->subject("Vaccination Reminder: {$petName} — {$vaccineName}");
                }
            );

            $vax->update(['reminder_sent' => true]);
            return response()->json(['success' => true, 'msg' => "Email reminder sent to {$email}"]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'msg' => 'Failed to send email: ' . $e->getMessage()]);
        }
    }

    public function searchVaccineTypes(Request $request)
    {
        $businessId = request()->session()->get('user.business_id');
        $term       = $request->input('q', '');
        $species    = strtolower(trim($request->input('species', '')));

        $columns = ['id', 'name', 'manufacturer', 'species_target', 'valid_for_months'];
        if (\Illuminate\Support\Facades\Schema::hasColumn('vc_vaccine_types', 'category')) {
            $columns[] = 'category';
        }

        $types = VcVaccineType::active()->forBusiness($businessId)
            ->where('name', 'LIKE', '%' . $term . '%')
            ->orderBy('name')
            ->limit(50)
            ->get($columns);

        // Lenient species filter: only narrow down when the pet's species is one
        // of the well-known ones AND the vaccine explicitly targets specific species.
        // Empty / "other" / unknown species → show everything.
        $knownSpecies = ['dog', 'cat', 'rabbit', 'bird', 'horse', 'cow', 'sheep', 'goat'];
        if ($species && in_array($species, $knownSpecies)) {
            $types = $types->filter(function ($t) use ($species) {
                if (empty($t->species_target)) return true;
                $targets = array_map('strtolower', (array) $t->species_target);
                return in_array($species, $targets) || in_array('all', $targets);
            })->values();
        }

        $categoryLabels = [
            'core_vaccine'     => 'Core Vaccine',
            'non_core_vaccine' => 'Non-Core Vaccine',
            'spot_on'          => 'Spot-on',
            'deworming'        => 'Deworming',
            'oral'             => 'Oral',
            'nasal'            => 'Nasal',
            'topical'          => 'Topical',
            'preventive'       => 'Preventive',
            'other'            => 'Other',
        ];

        return response()->json($types->map(fn($t) => [
            'id'               => $t->id,
            'text'             => $t->name,
            'category'         => $t->category ?? 'core',
            'category_label'   => $categoryLabels[$t->category ?? 'core'] ?? 'Core',
            'manufacturer'     => $t->manufacturer,
            'species_target'   => $t->species_target,
            'valid_for_months' => $t->valid_for_months,
        ]));
    }
}
