<?php

namespace App\Console\Commands;

use App\Models\Setting;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class BroadcastEmail extends Command
{
    protected $signature = 'broadcast:email {broadcastId}';
    protected $description = 'Process a queued email broadcast in the background';

    public function handle(): int
    {
        $broadcastId = $this->argument('broadcastId');
        $data = cache($broadcastId);

        if (!$data || !is_array($data)) {
            $this->error('Broadcast data not found or expired.');
            return 1;
        }

        $siteName = Setting::get('site_name', 'Bursa Kerja');
        $sendDelay = (int) Setting::get('notification_send_delay_seconds', 3);
        $sent = 0;
        $failed = 0;

        $this->info("Processing email broadcast to " . count($data) . " recipients...");

        foreach ($data as $i => $item) {
            if (!isset($item['email']) || !isset($item['message']) || !isset($item['subject'])) {
                $failed++;
                Log::warning("Broadcast email: invalid data at index {$i}");
                continue;
            }

            if ($i > 0 && $sendDelay > 0) {
                sleep($sendDelay);
            }

            try {
                $htmlContent = $this->buildEmailHtml($item['subject'], $item['message'], $siteName);
                $recipientName = $item['name'] ?? '';
                $recipientEmail = $item['email'];
                $subject = $item['subject'];

                Mail::html($htmlContent, function ($mail) use ($recipientEmail, $recipientName, $subject) {
                    $mail->to($recipientEmail, $recipientName)
                         ->subject($subject);
                });
                $sent++;
            } catch (\Exception $e) {
                $failed++;
                Log::error("Broadcast email failed for {$item['email']}: " . $e->getMessage());
            }
        }

        // Clean up cache
        cache()->forget($broadcastId);

        $this->info("Broadcast done. Sent: {$sent}, Failed: {$failed}");
        return 0;
    }

    private function buildEmailHtml(string $subject, string $body, string $siteName): string
    {
        return <<<HTML
        <!DOCTYPE html>
        <html>
        <head><meta charset="utf-8"></head>
        <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background: #f5f5f5;">
            <div style="background: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <div style="text-align: center; margin-bottom: 20px;">
                    <h2 style="color: #4F46E5; margin: 0;">{$siteName}</h2>
                </div>
                <hr style="border: none; border-top: 2px solid #E5E7EB; margin: 20px 0;">
                <h3 style="color: #1F2937;">{$subject}</h3>
                <div style="background: #F9FAFB; border-radius: 8px; padding: 15px; margin: 15px 0; line-height: 1.6;">
                    {$body}
                </div>
                <hr style="border: none; border-top: 1px solid #E5E7EB; margin: 20px 0;">
                <p style="color: #6B7280; font-size: 12px; text-align: center;">
                    Email ini dikirim oleh {$siteName}
                </p>
            </div>
        </body>
        </html>
        HTML;
    }
}
