<?php

namespace Modules\WhatsApp\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\WhatsApp\Entities\Services\WaNotifier;

/**
 * Sends WhatsApp vaccination-due reminders for vaccinations due on the target
 * date (default: tomorrow). Deduped per vaccination per due date. Independent of
 * VetClinic's own (SMS/email) reminder. Only runs when VetClinic is installed.
 *
 * Schedule: daily (e.g. 09:00).
 */
class SendVaccinationReminders extends Command
{
    protected $signature = 'whatsapp:vaccination-reminders {--date= : Target due date Y-m-d (defaults to tomorrow)}';
    protected $description = 'Send WhatsApp reminders for vaccinations due soon.';

    public function handle(WaNotifier $notifier): int
    {
        if (!Schema::hasTable('vc_vaccinations')) {
            $this->info('VetClinic not installed — nothing to do.');
            return self::SUCCESS;
        }

        $date = $this->option('date') ?: now()->addDay()->toDateString();

        $rows = DB::table('vc_vaccinations as v')
            ->join('contacts as c', 'c.id', '=', 'v.contact_id')
            ->leftJoin('vc_pets as p', 'p.id', '=', 'v.pet_id')
            ->leftJoin('vc_vaccine_types as t', 't.id', '=', 'v.vaccine_type_id')
            ->whereDate('v.next_due_date', $date)
            ->whereNull('v.waived_at')
            ->where('c.mobile', '!=', '')
            ->select([
                'v.id', 'v.business_id', 'v.next_due_date',
                'c.name as owner_name', 'c.mobile',
                'p.petname', 't.name as vaccine_name',
            ])
            ->get();

        $sent = 0;
        foreach ($rows as $r) {
            $tags = [
                '{owner_name}'  => $r->owner_name ?? '',
                '{pet_name}'    => $r->petname ?? '',
                '{vaccine_name}' => $r->vaccine_name ?? 'vaccination',
                '{due_date}'    => (string) $r->next_due_date,
                '{clinic_name}' => $this->businessName($r->business_id),
            ];
            $notifier->sendEvent((int) $r->business_id, 'vaccination_due', $r->mobile, null, 'vacc:' . $r->id . ':' . $date, $tags);
            $sent++;
        }

        $this->info("Queued {$sent} vaccination reminder(s) for {$date}.");
        return self::SUCCESS;
    }

    private array $businessCache = [];

    private function businessName($businessId): string
    {
        $businessId = (int) $businessId;
        if (!isset($this->businessCache[$businessId])) {
            $this->businessCache[$businessId] = (string) (DB::table('business')->where('id', $businessId)->value('name') ?? '');
        }
        return $this->businessCache[$businessId];
    }
}
