<?php

namespace App\Services;

use App\Models\SiteConfiguration;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class FacebookConversionService
{
    protected $pixelId;
    protected $accessToken;
    protected $apiUrl;
    protected $apiVersion;
    protected $testCode;

    public function __construct()
    {
        $siteConfiguration = SiteConfiguration::select('fb_pixel_id', 'fb_access_token', 'fb_api_version', 'test_event_code')->first();
        $this->pixelId = $siteConfiguration->fb_pixel_id ?? null;
        $this->testCode = $siteConfiguration->test_event_code ?? null;
        $this->accessToken = $siteConfiguration->fb_access_token ?? null;
        $this->apiVersion = $siteConfiguration->fb_api_version ?? 'v23.0';
        $this->apiUrl = "https://graph.facebook.com/{$this->apiVersion}/{$this->pixelId}/events";
    }

    /**
     * Send an event to Facebook Conversion API
     *
     * @param string $eventName
     * @param array $userData
     * @param array $customData
     * @param string $actionSource
     * @param string|null $eventId
     *
     * @return null
     */
    public function sendEvent(string $eventName, array $userData, array $customData, string $actionSource = 'website', ?string $eventId = null, ?string $pageUrl = null)
    {
        $payload = [
            'data' => [
                [
                    'event_name' => $eventName,
                    'event_time' => time(),
                    'event_id' => $eventId ?? Str::uuid()->toString(),
                    'event_source_url' => $pageUrl ?? url()->current(),
                    'action_source' => $actionSource,
                    'user_data' => $userData,
                    'custom_data' => $customData,
                ]
            ],
            'access_token' => $this->accessToken,
        ];
        if ($this->testCode) {
            $payload['test_event_code'] = $this->testCode;
        }
        $response = Http::post($this->apiUrl, $payload);

        if ($response->failed()) {
            Log::error('Facebook CAPI Failed', ['response' => $response->body()]);
        }

        return $response->json();
    }

    public function verify($pixelId, $accessToken)
    {


        $url = "https://graph.facebook.com/{$this->apiVersion}/{$pixelId}";

        $response = Http::get($url, [
            'access_token' => $accessToken
        ]);

        $data = $response->json();

        // ✅ Case 1: Pixel ID exists but missing permissions
        if (
            isset($data['error']['code']) && $data['error']['code'] == 100 &&
            str_contains($data['error']['message'], 'Missing Permission')
        ) {
            return response()->json([
                'status' => true,
                'message' => 'Pixel verified successfully Given Info are valid'
            ]);
        }
        // ❌ Case 2: Wrong Pixel ID
        if (
            isset($data['error']['code']) && $data['error']['code'] == 100 &&
            isset($data['error']['error_subcode']) && $data['error']['error_subcode'] == 33
        ) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid Pixel ID: ' . $data['error']['message']
            ], 400);
        }
        // ❌ Case 3: Wrong Access Token
        if (
            isset($data['error']['code']) && $data['error']['code'] == 190 &&
            (str_contains($data['error']['message'], 'Malformed access token') || str_contains($data['error']['message'], 'Invalid OAuth access token'))
        ) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid Access Token: ' . $data['error']['message']
            ], 400);
        }



        // ✅ Case 4: Pixel Verified
        if (isset($data['id']) && $data['id'] == $pixelId) {
            return response()->json([
                'status' => true,
                'message' => 'Pixel verified successfully Given Info are valid',
                'data' => $data
            ]);
        }

        // ❌ Fallback: Unknown error
        return response()->json([
            'status' => false,
            'message' => 'Verification failed',
            'data' => $data
        ], 400);
    }
}
