<?php

namespace Modules\Vrc\Console;

use Illuminate\Console\Command;
use Modules\Vrc\Entities\VrcServiceReminder;
use Modules\Vrc\Services\Contracts\NotificationServiceContract;

/**
 * Dispatches due service reminders via the ERP notifier and marks them sent
 * (spec §6.12). Scheduled daily from the VrcServiceProvider.
 */
class SendRemindersCommand extends Command
{
    protected $signature = 'vrc:send-reminders {--date=}';

    protected $description = 'Send due VRC service reminders via the ERP notifier';

    public function handle(NotificationServiceContract $notifier): int
    {
        $date = $this->option('date');
        $due = VrcServiceReminder::due($date)->get();

        $sent = 0;
        foreach ($due as $reminder) {
            $body = __('vrc::lang.notify_service_reminder', [
                'plate' => optional($reminder->vehicle)->plate_number ?: '',
            ]);

            $ok = $notifier->send(
                (int) $reminder->business_id,
                (int) $reminder->erp_customer_id,
                $reminder->channel ?: 'sms',
                $body
            );

            if ($ok) {
                $reminder->update(['status' => 'sent', 'sent_at' => now()]);
                $sent++;
            }
        }

        $this->info("VRC reminders dispatched: {$sent}");

        return self::SUCCESS;
    }
}
