<?php
/**
 * Magento 2 Google Analytics 4 (GA4) GTM
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Anowave license that is
 * available through the world-wide-web at this URL:
 * https://www.anowave.com/license-agreement/
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category 	Anowave
 * @package 	Anowave_Ec
 * @copyright 	Copyright (c) 2026 Anowave (https://www.anowave.com/)
 * @license  	https://www.anowave.com/license-agreement/
 */

namespace Anowave\Ec\Model\Api\TikTok;

use Anowave\Ec\Model\Curl;
use Anowave\Ec\Helper\Data;

abstract class Api 
{
    /**
     * TikTok API endpoint
     */
    const ENDPOINT = 'https://business-api.tiktok.com/open_api/v1.3/pixel/track/';

    /**
     * @var Curl
     */
    protected $curl;

    /**
     * @var Data
     */
    protected $helper;

    /**
     * TikTok Pixel Code
     * 
     * @var string 
     */
    protected $pixel_code = '';

    /**
     * Constructor 
     */
    public function __construct
    (
        Curl $curl,
        Data $helper
    )
    {
        $this->curl = $curl;    
        $this->helper = $helper;
    }

    
    /**
     * Get params 
     * 
     * @param array $params
     * @param mixed array
     * @param  'referrer'
     * 
     * @return array
     */
    protected function getParams(array $params = [], array $page = ['url' => '', 'referrer' => '']) : array
    {
        return array_merge($params, 
        [
            "pixel_code"    => $this->pixel_code,
            "event_id"      => $this->uuid(),
            "timestamp"     => gmdate("Y-m-d\TH:i:s\Z"),
            "context" => 
            [
                "ad" => 
                [
                    "callback" => $_COOKIE['ttclid'] ?? ''
                ],
                "page"          => $page,
                "user"          => $this->getUserData(),
                "user_agent"    => $_SERVER['HTTP_USER_AGENT'] ?? '',
                "ip"            => $_SERVER["REMOTE_ADDR"]
            ],
            "currency" => $this->helper->getCurrentStoreCurrency()
        ]);
    }

    /**
     * Get user data 
     * 
     * @return array
     */
    private function getUserData() : array 
    {
        return 
        [
            "external_id"   => hash('sha256', 0),
            "phone_number"  => null,
            "email"         => null,
            "ttp"           => $_COOKIE['_ttp'] ?? ''
        ];
    }

    /**
     * Create unique identifier 
     * 
     * @return string
     */
    private function uuid() : string
    {
        if (function_exists('com_create_guid') === true)
        {
            return trim(com_create_guid(), '{}');
        }
        
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
    }
}