<?php

namespace App\Console\Commands;

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

class BroadcastWhatsApp extends Command
{
    protected $signature = 'broadcast:whatsapp {broadcastId}';
    protected $description = 'Process a queued WhatsApp 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;
        }

        $apiKey = Setting::get('fonnte_api_key', config('services.fonnte.key'));
        if (!$apiKey) {
            $this->error('Fonnte API key not configured.');
            return 1;
        }

        $delaySeconds = (int) Setting::get('wa_send_delay_seconds', 10);
        $sent = 0;
        $failed = 0;

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

        foreach ($data as $i => $item) {
            // Validate item data
            if (!is_array($item) || empty($item['phone']) || empty($item['message'])) {
                $failed++;
                Log::warning("Broadcast WA: invalid data at index {$i}");
                continue;
            }

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

            try {
                $response = Http::withHeaders([
                    'Authorization' => $apiKey,
                ])->post('https://api.fonnte.com/send', [
                    'target' => $item['phone'],
                    'message' => $item['message'],
                    'countryCode' => '62',
                ]);

                if ($response->successful() && $response->json('status')) {
                    $sent++;
                } else {
                    $failed++;
                    Log::warning("Broadcast WA failed for {$item['phone']}: " . ($response->json('reason') ?? 'Unknown'));
                }
            } catch (\Exception $e) {
                $failed++;
                Log::error("Broadcast WA exception for {$item['phone']}: " . $e->getMessage());
            }
        }

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

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