<?php

namespace App\Traits;

use App\Services\FacebookConversionService;

trait FiresFacebookEventsTrait
{
    /**
     * Get user data in a format that can be sent to Facebook for firing events.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $customer
     * @return array
     */
    protected function getUserData($request, $customer = null)
    {
        $firstName = null;
        $lastName = null;
        $normalizedPhone = null;

        if (!empty($customer['phone'])) {
            $normalizedPhone = $this->normalizeAndHashPhone($customer['phone']);
        }

        if (!empty($customer['name'])) {
            $nameParts = explode(' ', trim($customer['name']), 2);
            $firstName = $nameParts[0];
            $lastName = count($nameParts) > 1 ? $nameParts[1] : null;
        }
        if (!empty($customer['city'])) {
            $normalizedCity = strtolower(preg_replace('/[^a-z]/', '', strtolower($customer['city'])));
        }
        $clientIp = $request->header('X-Forwarded-For')
            ? explode(',', $request->header('X-Forwarded-For'))[0]
            : $request->ip();

        if ($clientIp === '127.0.0.1' || $clientIp === '::1') {
            $clientIp = null;
        }
        $fbc = session('_fbc') ?? $request->cookie('_fbc') ?? null;

        $data = [
            'em' => $request->user() && $request->user()->email
                ? [hash('sha256', strtolower(trim($request->user()->email)))]
                : null,
            'ph' => $normalizedPhone ? [$normalizedPhone] : null,
            'fn' => $firstName ? [hash('sha256', strtolower(trim($firstName)))] : null,
            'ln' => $lastName ? [hash('sha256', strtolower(trim($lastName)))] : null,
            'ct' => !empty($customer['city']) ? [hash('sha256', $normalizedCity)] : null,
            'country' => [hash('sha256', 'bd')],
            'external_id' => !empty($customer['id']) ? [hash('sha256', $customer['id'])] : null,
            'client_ip_address' => $clientIp,
            'client_user_agent' => $request->userAgent(),   
            'fbc' => $fbc,
            'fbp' => session('_fbp') ?? $request->cookie('_fbp') ?? null,
        ];
        return array_filter($data, fn($value) => !empty($value));
    }


    /**
     * Fires a PageView event to Facebook Conversion API.
     *
     * @param string|null $event_id
     * @param string|null $url
     * @return void
     */
    public function fireFacebookPageViewEvent($request, $event_id = null, $url = null)
    {
        $userData = $this->getUserData($request);

        // return $url;
        (new FacebookConversionService())->sendEvent(
            'PageView',
            $userData,
            [],
            'website',
            $event_id,
            $url
        );
    }
    /**
     * Fires a ViewContent event to Facebook Conversion API.
     *
     * @param  \App\Models\Product  $product
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $event_id
     * @return void
     */
    public function fireFacebookViewContentEvent($product, $request, $event_id = null, $page_url = null)
    {
        $userData = $this->getUserData($request);

        $customData = [
            'currency' => 'BDT',
            'value' => (float)$product->sale_price,
            'content_ids' => [(string)$product->product_code],
            'content_name' => $product->name,
            'contents' => [
                [
                    'id' => $product->product_code,
                    'quantity' => 1,
                    'item_price' => intval($product->sale_price),
                ]
            ],
            'content_type' => 'product',
        ];

        return (new FacebookConversionService())->sendEvent(
            'ViewContent',
            $userData,
            $customData,
            'website',
            $event_id,
            $page_url
        );
    }

    /**
     * Fires an AddToCart event to Facebook Conversion API.
     *
     * @param  \App\Models\Product  $product
     * @param  int  $quantity
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $event_id
     * @return void
     */
    public function fireFacebookAddToCartEvent($product, $quantity, $request, $event_id = null, $page_url = null)
    {
        $userData = $this->getUserData($request);

        $customData = [
            'currency' => 'BDT',
            'value' => (float)($product->sale_price * $quantity),
            'content_name' => $product->name,
            'content_ids' => [$product->product_code],
            'contents' => [
                [
                    'id' => $product->product_code,
                    'quantity' => intval($quantity),
                    'item_price' => intval($product->sale_price),
                ]
            ],
            'content_type' => 'product',
        ];

        return (new FacebookConversionService())->sendEvent(
            'AddToCart',
            $userData,
            $customData,
            'website',
            $event_id,
            $page_url
        );
    }



    /**
     * Fires a InitiateCheckout event to Facebook Conversion API.
     *
     * @param  \Illuminate\Support\Collection  $cartItems
     * @param  float  $total
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $event_id
     * @return void
     */
    public function fireFacebookInitiateCheckoutEvent($cartItems, $total, $request, $event_id = null, $page_url = null)
    {
        $userData = $this->getUserData($request);

        $customData = [
            'currency' => 'BDT',
            'value' => (float)$total,
            'content_ids' => $cartItems->pluck('options.product_code')->unique()->values()->toArray(),
            'contents' => $cartItems->map(fn($item) => [
                'id' => $item->options->product_code,
                'quantity' => intval($item->qty),
                'item_price' => intval($item->price),
            ])->values()->toArray(),
            'content_type' => 'product',
        ];

        return (new FacebookConversionService())->sendEvent(
            'InitiateCheckout',
            $userData,
            $customData,
            'website',
            $event_id,
            $page_url
        );
    }

    /**
     * Fires a Purchase event to Facebook Conversion API.
     *
     * @param  \Illuminate\Support\Collection  $cartItems
     * @param  float  $total
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $customer
     * @param  string|null  $event_id
     * @return void
     */
    public function fireFacebookPurchaseEvent($cartItems, $total, $request, $customer, $event_id = null, $page_url = null)
    {
        $userData = $this->getUserData($request, $customer);

        $customData = [
            'currency' => 'BDT',
            'value' => (float)$total,
            'content_ids' => $cartItems->pluck('options.product_code')->unique()->values()->toArray(),
            'contents' => $cartItems->map(fn($item) => [
                'id' => $item->options->product_code,
                'quantity' => intval($item->qty),
                'item_price' => intval($item->price),
            ])->values()->toArray(),
            'content_type' => 'product',
        ];

        return (new FacebookConversionService())->sendEvent(
            'Purchase',
            $userData,
            $customData,
            'website',
            $event_id,
            $page_url
        );
    }
    public function fireFacebookSearchEvent($searchTerm, $request)
    {
        $userData = $this->getUserData($request);

        $customData = [
            'search_string' => $searchTerm
        ];

        return (new FacebookConversionService())->sendEvent(
            'Search',
            $userData,
            $customData
        );
    }

    private function normalizeAndHashPhone($phone)
    {
        $digits = preg_replace('/\D/', '', $phone);

        if (strlen($digits) === 13 && substr($digits, 0, 3) === '880') {
            // e.g. 8801712345678 → +8801712345678
            $normalized = '+' . $digits;
        } elseif (strlen($digits) === 11 && substr($digits, 0, 1) === '0') {
            // e.g. 01712345678 → +8801712345678
            $normalized = '+880' . substr($digits, 1);
        } elseif (strlen($digits) === 10) {
            // e.g. 1712345678 → +8801712345678
            $normalized = '+880' . $digits;
        } elseif (strlen($digits) === 13 && substr($digits, 0, 4) === '0880') {
            // e.g. 08801712345678 → +8801712345678
            $normalized = '+880' . substr($digits, 4);
        } else {
            // fallback
            $normalized = '+' . $digits;
        }
        return hash('sha256', $normalized);
    }
}
