<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WebhookHelper
{
    public static function send($user, $payload)
    {
        if (!$user || empty($user->webhook_url)) {
            return;
        }

        // Melakukan pengiriman sebanyak 3 kali berturut-turut
        for ($i = 1; $i <= 3; $i++) {
            try {
                // Menambahkan informasi percobaan ke dalam payload
                $payload['attempt'] = $i;

                $response = Http::timeout(5)->post($user->webhook_url, $payload);

                // Memeriksa apakah server client merespons dengan status 200-299
                if ($response->successful()) {
                    Log::info("WEBHOOK SUCCESS (Attempt $i)", [
                        'user_id' => $user->id,
                        'url'     => $user->webhook_url,
                        'status'  => $response->status(),
                        'event'   => $payload['event'] ?? 'unknown'
                    ]);
                } else {
                    // Mencatat log jika terkirim tapi client merespons dengan error (misal 500 / 404)
                    Log::warning("WEBHOOK RESPONDED WITH ERROR (Attempt $i)", [
                        'user_id' => $user->id,
                        'url'     => $user->webhook_url,
                        'status'  => $response->status(),
                        'body'    => $response->body()
                    ]);
                }
                    
            } catch (\Throwable $e) {
                Log::error("WEBHOOK FAILED TO SEND (Attempt $i)", [
                    'user_id' => $user->id,
                    'url'     => $user->webhook_url,
                    'error'   => $e->getMessage()
                ]);
            }
        }
    }
}