<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use App\Models\Anggota; // pastikan ini ada di atas


class SendWaInvitationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 3;            // maksimal dicoba 3x
    public $retryAfter = 60;      // tunggu 60 detik sebelum retry
    public $anggota;
    public $message;

    public function __construct($anggota, $message)
    {
        $this->anggota = $anggota;
        $this->message = $message;
    }

    public function handle()
    {
        $phone = preg_replace('/^0/', '62', $this->anggota->no_wa);
        $apiKey = config('services.wa.api_key');
        $sender = config('services.wa.sender');
        $url = "https://wa.codeucil.my.id/send-message?api_key={$apiKey}&sender={$sender}&number={$phone}&message=" . urlencode($this->message);

        try {
            $client = new Client();
            $response = $client->get($url);
            $result = json_decode($response->getBody(), true);

            // Ambil ulang anggota dari DB
            $anggota = Anggota::find($this->anggota->id);

            if (!$result['status']) {
                $anggota->wa_sent = false;
                $anggota->wa_error_log = $result['msg'] ?? 'WA gagal tanpa pesan';
                $anggota->save();
                throw new \Exception($anggota->wa_error_log);
            }

            $anggota->wa_sent = true;
            $anggota->wa_error_log = null;
            $anggota->save();
        } catch (\Exception $e) {
            $anggota = Anggota::find($this->anggota->id);
            $anggota->wa_sent = false;
            $anggota->wa_error_log = $e->getMessage();
            $anggota->save();

            Log::error("WA Error to {$this->anggota->no_wa}: " . $e->getMessage());
            throw $e;
        }
    }
}
