<?php

namespace App\Console\Commands;

use App\Jobs\SendDailyManagementReportJob;
use App\Models\Report\ManagementReportRecipient;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

class SendDailyManagementReports extends Command
{
    protected $signature = 'reports:send-daily-management
                            {--date= : Report date (YYYY-MM-DD), using an 18:00 cutoff}';

    protected $description = 'Queue the daily management KPI email for every active whitelisted recipient';

    public function handle(): int
    {
        $timezone = config('app.timezone');
        $cutoff = $this->option('date')
            ? Carbon::createFromFormat('Y-m-d', (string) $this->option('date'), $timezone)->setTime(18, 0)
            : now($timezone);

        $reportDate = $cutoff->toDateString();
        $recipients = ManagementReportRecipient::withoutGlobalScopes()
            ->where('is_active', true)
            ->where(function ($query) use ($reportDate) {
                $query->whereNull('last_report_date')
                    ->orWhereDate('last_report_date', '!=', $reportDate);
            })
            ->get(['id']);

        foreach ($recipients as $recipient) {
            SendDailyManagementReportJob::dispatch($recipient->id, $cutoff->toIso8601String());
        }

        $this->info("Queued {$recipients->count()} daily management report email(s) for {$reportDate}.");

        return self::SUCCESS;
    }
}
