<?php
namespace App\Console\Commands;

use App\Models\EmailScheduled;
use App\Models\EmailScheduledRecipient;
use App\Mail\CustomEmail;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;

class ProcessScheduledEmailCommand extends Command
{
    protected $signature = 'email:process-scheduled';
    protected $description = 'Process scheduled email messages that are due to be sent';

    public function handle()
    {
        $this->info('🔍 Checking for scheduled Email messages...');

        $dueMessages = EmailScheduled::where('status', 'scheduled')
            ->where('scheduled_at', '<=', now())
            ->with('recipients')
            ->get();

        if ($dueMessages->isEmpty()) {
            $this->info('✅ No scheduled emails due for sending.');
            return 0;
        }

        $this->info("📧 Found {$dueMessages->count()} email batches due for sending.");

        foreach ($dueMessages as $message) {
            $this->info("📤 Processing email batch ID: {$message->id}");

            try {
                $message->update(['status' => 'sending']);

                $successCount = 0;
                $failCount = 0;

                foreach ($message->recipients as $recipient) {
                    if ($recipient->email) {
                        $recipientRecord = EmailScheduledRecipient::create([
                            'email_scheduled_id' => $message->id,
                            'user_id' => $recipient->id,
                            'email_address' => $recipient->email,
                            'status' => 'pending'
                        ]);

                        try {
                            Mail::to($recipient->email)->send(
                                new CustomEmail($message->subject, $message->content, $recipient->name)
                            );

                            $recipientRecord->markAsSent();
                            $successCount++;
                            $this->line("   ✅ Sent to {$recipient->name} ({$recipient->email})");

                            usleep(100000);

                        } catch (\Exception $e) {
                            $recipientRecord->markAsFailed($e->getMessage());
                            $failCount++;
                            $this->line("   ❌ Failed to {$recipient->name} ({$recipient->email}): " . $e->getMessage());
                        }
                    } else {
                        $failCount++;
                        $this->line("   ⚠️  No email address for {$recipient->name}");
                    }
                }

                // Update final status
                $finalStatus = $failCount === 0 ? 'sent' : ($successCount === 0 ? 'failed' : 'sent');

                $message->update([
                    'status' => $finalStatus,
                    'delivery_report' => [
                        'total' => $successCount + $failCount,
                        'successful' => $successCount,
                        'failed' => $failCount,
                        'completed_at' => now()
                    ]
                ]);

                $this->info("✅ Email batch {$message->id} completed: {$successCount} sent, {$failCount} failed");

            } catch (\Exception $e) {
                $message->update([
                    'status' => 'failed',
                    'delivery_report' => [
                        'error' => $e->getMessage(),
                        'failed_at' => now()
                    ]
                ]);
                $this->error("❌ Failed to process email batch {$message->id}: " . $e->getMessage());
            }
        }

        $this->info('🎉 Scheduled email processing completed!');
        return 0;
    }
}
