<?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 a birthday greeting for pets whose date of birth matches the target
 * day (default: today). Deduped per pet per year. Only runs when VetClinic is
 * installed.
 *
 * Schedule: daily (e.g. 08:00).
 */
class SendPetBirthdays extends Command
{
    protected $signature = 'whatsapp:pet-birthdays {--date= : Target date Y-m-d (defaults to today)}';
    protected $description = 'Send WhatsApp birthday greetings for pets celebrating today.';

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

        $target = $this->option('date') ? \Carbon\Carbon::parse($this->option('date')) : now();
        $month = (int) $target->format('m');
        $day = (int) $target->format('d');
        $year = $target->format('Y');

        $rows = DB::table('vc_pets as p')
            ->join('contacts as c', 'c.id', '=', 'p.contact_id')
            ->whereNotNull('p.dob')
            ->whereMonth('p.dob', $month)
            ->whereDay('p.dob', $day)
            ->where('c.mobile', '!=', '')
            ->select(['p.id', 'p.business_id', 'p.petname', 'c.name as owner_name', 'c.mobile'])
            ->get();

        $sent = 0;
        foreach ($rows as $r) {
            $tags = [
                '{owner_name}'  => $r->owner_name ?? '',
                '{pet_name}'    => $r->petname ?? '',
                '{clinic_name}' => $this->businessName($r->business_id),
            ];
            $notifier->sendEvent((int) $r->business_id, 'pet_birthday', $r->mobile, null, 'bday:' . $r->id . ':' . $year, $tags);
            $sent++;
        }

        $this->info("Queued {$sent} birthday greeting(s).");
        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];
    }
}
