<?php

namespace Modules\ClinicCore\Console;

use Illuminate\Console\Command;
use Modules\ClinicCore\Entities\ClcReminderSetting;
use Modules\ClinicCore\Entities\ClcReminderTemplate;
use Modules\ClinicCore\Entities\ClcReminderLog;
use Modules\ClinicCore\Entities\ClcVaccination;
use Modules\ClinicCore\Entities\ClcPatientContactDetail;
use Modules\ClinicCore\Http\Controllers\ClcReminderController;
use Carbon\Carbon;

class ClcSendVaccineReminders extends Command
{
    protected $signature   = 'clc:send-vaccine-reminders {business_id? : Specific business ID (omit to process all)}';
    protected $description = 'Send vaccination reminders (email + SMS via core notification engine) for due and overdue vaccinations';

    public function handle()
    {
        $argId = $this->argument('business_id');

        if ($argId) {
            $businesses = \App\Business::where('id', $argId)->get();
        } else {
            // Pick up businesses with reminders enabled on either channel —
            // dispatchReminders fans out internally based on which channel
            // toggles are on.
            $enabledIds = ClcReminderSetting::where('is_enabled', true)
                ->where(function ($q) {
                    $q->where('email_enabled', true)
                      ->orWhere('sms_enabled', true);
                })
                ->pluck('business_id');
            $businesses = \App\Business::whereIn('id', $enabledIds)->get();
        }

        if ($businesses->isEmpty()) {
            $this->info('No businesses with reminders enabled on any channel.');
            return 0;
        }

        $controller = new ClcReminderController();
        $totalSent = 0; $totalSkipped = 0; $totalFailed = 0;

        foreach ($businesses as $business) {
            $this->info("Processing: {$business->name} (ID: {$business->id})");
            $result = $controller->dispatchReminders($business->id);
            $this->line("  Sent: {$result['sent']}, Skipped: {$result['skipped']}, Failed: {$result['failed']}");
            $totalSent    += $result['sent'];
            $totalSkipped += $result['skipped'];
            $totalFailed  += $result['failed'];
        }

        $this->info("Completed. Total — sent: {$totalSent}, skipped: {$totalSkipped}, failed: {$totalFailed}");
        return 0;
    }
}
