<?php

namespace App\Console\Commands;

use App\Jobs\SendPushNotifications;
use App\Models\Campaign;
use App\Models\User;
use App\Notifications\PushNotification;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendScheduledNotifications extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notifications:send-scheduled';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send scheduled notifications to users';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Log::info('Starting to send scheduled notifications.');
        $campaigns = Campaign::with(
            'campaignAudience.user',
        )->where('status', 'LIKE', '%Scheduled%')->get();
        
        foreach($campaigns as $camp){
            if($camp->isScheduledForNow()){
                $users = [];
                if(!empty($camp->campaignAudience)){
                    foreach($camp->campaignAudience as $campAud){
                        if($campAud->user != null){
                            $users[] = $campAud->user;
                        }
                    }
    
                    try{
                        SendPushNotifications::dispatch(
                            $users,
                            $camp->title,
                            $camp->description,
                            $camp->image
                        );
            
                        $camp->update([
                            'status' => 'Delivered',
                            'delivered_at' => date('Y-m-d H:i:s')
                        ]);
    
                    }catch(Exception $ex){
                        Log::error("Campaign notification error scheduled", array('data' => $ex->getMessage(), 'line' => $ex->getLine()));
                    }
                    Log::info('Scheduled notifications sent successfully.');
    
                    $users = [];
                }
            }
            
        }
            
    }
}
