<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Campaign;
use App\Jobs\SendCampaignEmailJob;
use App\Models\CampaignLog;

class SendScheduledCampaigns extends Command
{
    protected $signature = 'campaigns:send-scheduled';
    protected $description = 'Send scheduled campaigns when time is due';

    public function handle()
    {
        $campaigns = Campaign::where('status', 'scheduled')
            ->where('scheduled_at', '<=', now())
            ->get();

        foreach ($campaigns as $campaign) {
            $this->info("Dispatching campaign: {$campaign->name}");
            $contacts = $campaign->list->contacts()->where('subscribed', true)->get();

            foreach ($contacts as $contact) {
                CampaignLog::updateOrCreate(
                    ['campaign_id' => $campaign->id, 'contact_id' => $contact->id],
                    ['status' => 'pending']
                );
                SendCampaignEmailJob::dispatch($campaign, $contact);
            }

            $campaign->update(['status' => 'sent']);
        }

        return Command::SUCCESS;
    }
}
