<?php

namespace App\Jobs;

use App\Models\User;
use App\Services\WhatsAppService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class MassNotificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $title;
    protected $messageContent;
    protected $channels; // array: ['whatsapp', 'email']
    protected $target;   // 'all', 'customers', 'admins'

    /**
     * Create a new job instance.
     */
    public function __construct(string $title, string $messageContent, array $channels, string $target = 'all')
    {
        $this->title = $title;
        $this->messageContent = $messageContent;
        $this->channels = $channels;
        $this->target = $target;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $query = User::query();

        if ($this->target === 'customers') {
            $query->where('role', 'customer');
        } elseif ($this->target === 'admins') {
            $query->where('role', 'admin');
        }

        $users = $query->get();

        Log::info("MassNotificationJob started: Sending to " . $users->count() . " users.");

        foreach ($users as $user) {
            $personalizedTitle = str_ireplace(['{nama}', '{name}'], $user->name, $this->title);
            $personalizedMessage = str_ireplace(['{nama}', '{name}'], $user->name, $this->messageContent);

            // 1. Send Email if requested
            if (in_array('email', $this->channels) && !empty($user->email)) {
                try {
                    $subject = $personalizedTitle;
                    $body = $personalizedMessage;
                    
                    Mail::raw($body, function ($message) use ($user, $subject) {
                        $message->to($user->email)
                            ->subject($subject);
                    });
                } catch (\Exception $e) {
                    Log::error("MassNotificationJob: Failed sending Email to {$user->email}: " . $e->getMessage());
                }
            }

            // 2. Send WhatsApp if requested
            if (in_array('whatsapp', $this->channels) && !empty($user->whatsapp)) {
                try {
                    WhatsAppService::sendMessage($user->whatsapp, $personalizedMessage);
                } catch (\Exception $e) {
                    Log::error("MassNotificationJob: Failed sending WhatsApp to {$user->whatsapp}: " . $e->getMessage());
                }
            }
        }

        Log::info("MassNotificationJob finished successfully.");
    }
}
