<?php

namespace App\Jobs;

use App\Models\Setting;
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\Http;
use Illuminate\Support\Facades\Log;

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

    public $tries = 3;

    public function backoff(): array
    {
        return [10, 30, 60];
    }

    protected string $eventName;
    protected string $eventId;
    protected array $userData;
    protected array $customData;
    protected string $sourceUrl;

    /**
     * Create a new job instance.
     */
    public function __construct(string $eventName, string $eventId, array $userData, array $customData, string $sourceUrl)
    {
        $this->eventName = $eventName;
        $this->eventId = $eventId;
        $this->userData = $userData;
        $this->customData = $customData;
        $this->sourceUrl = $sourceUrl;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $pixelId = Setting::getValue('meta_pixel_id');
        $accessToken = Setting::getValue('meta_capi_token');

        if (!$pixelId || !$accessToken) {
            Log::info('Meta CAPI not sent: Pixel ID or Access Token is missing.');
            return;
        }

        $url = "https://graph.facebook.com/v19.0/{$pixelId}/events";

        $eventData = [
            'event_name' => $this->eventName,
            'event_time' => time(),
            'event_id' => $this->eventId,
            'event_source_url' => $this->sourceUrl,
            'action_source' => 'website',
            'user_data' => $this->userData,
            'custom_data' => $this->customData,
        ];

        $payload = [
            'data' => [$eventData],
        ];

        // Attach test event code if provided in Settings
        if ($testCode = Setting::getValue('meta_capi_test_code')) {
            $payload['test_event_code'] = $testCode;
        }

        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
            ])->post($url . '?access_token=' . $accessToken, $payload);

            if ($response->failed()) {
                $errorMsg = 'Meta CAPI transmission failed: ' . $response->body();
                Log::error($errorMsg);
                throw new \Exception($errorMsg);
            }

            Log::info('Meta CAPI event sent successfully: ' . $this->eventName . ' EventID: ' . $this->eventId);
        } catch (\Exception $e) {
            Log::error('Meta CAPI request exception: ' . $e->getMessage());
            throw $e;
        }
    }
}
