<?php
namespace Modules\Cart\Controllers;

use Illuminate\Support\Facades\Log;
use View;
use Theme;
use Module;
use App\Helpers\ApiClient;
use Illuminate\Http\Request;
use Megaads\ApifyClient\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Modules\Cart\Controllers\Controller;
use Modules\Cart\Models\Country;
use Modules\Cart\Models\OrderMeta;
use Modules\Cart\Models\Discount;
use Modules\Cart\Models\Order;
use Sunra\PhpSimple\HtmlDomParser;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function __construct() {
        parent::__construct();
    }

    public function checkout() {
        $this->buildShareData();
        $cartItems = view()->shared('cartItems');
        if (count($cartItems) == 0) {
            return redirect()->to(route('cart'));
        }
        view()->share('pageType', "purchase");
        view()->share('metaTitle', __('Checkout'));
        return Module::view('checkout.index');
    }

    private function buildShareData() {
        $user = \Auth::guard("customer")->user();
        $cartItems = $this->getCartItems();
        $countries = $this->getCountries();
        $strCodes = "";
        $totalValue = 0;
        $isValidPaypalByProduct = true;
        $invalidPaypalName = getOption("invalid_paypal_keywords", "");
        $invalidPaypalName = explode(",", $invalidPaypalName);
        $invalidPaypalTrademarks = $this->getProductTrademarks();
        $foundKey = false;
        $foundKeyTrademarks = false;
        $productIds = [];
        foreach ($cartItems as $item) {
            $productIds[] = $item['product_id'];
            $strCodes .= $item['sku'].',';
            $totalValue += $item['price'] * $item['quantity'];
            try {
                foreach ($invalidPaypalName as $key) {
                    if ($key != "") {
                        $escapedKey = preg_quote(strtolower($key), '/');
                        $escapedKey = $escapedKey . "s?";
                        $escapedKey = preg_replace('/\s+/', '\W+', $escapedKey);
                        if (preg_match("/\b$escapedKey\b|^$escapedKey\b|\b$escapedKey$/", strtolower($item['product_name']))) {
                            $foundKey = true;
                            $result[] = $key;
                            break;
                        }
                    }
                }
                if (!$foundKey) {
                    foreach ($invalidPaypalTrademarks as $key) {
                        if ($key != "") {
                            $escapedKey = preg_quote(strtolower($key), '/');
                            $escapedKey = $escapedKey . "s?";
                            $escapedKey = preg_replace('/\s+/', '\W+', $escapedKey);
                            if (preg_match("/\b$escapedKey\b|^$escapedKey\b|\b$escapedKey$/", strtolower($item['product_name']))) {
                                $foundKeyTrademarks = true;
                                $result[] = $key;
                                break;
                            }
                        }
                    }
                }
                if ($foundKey || $foundKeyTrademarks) {
                    $isValidPaypalByProduct = false;
                }
            } catch (\Exception $e) {
            }
        }
        if (!empty($cartItems)) {
            view()->share('imagePreload', getImageCdn($cartItems[0]['image_url'], 540, 540, false));
        }
        view()->share('strCode', substr($strCodes, 0, -1));
        view()->share('totalValue', $totalValue);
        view()->share('cartItems', $cartItems);
        $this->onViewOrderItem($cartItems);
        $account = getPaypalKey();
        $usePaypalByLimit = false;
        $paypalKey = config("cart::paypal.clientId");
        if (isset($account) && isset($account["name"])) {
            $usePaypalByLimit = true;
            $paypalKey = $account["clientId"];
        }
        $stripeKey = config("cart::stripe.public_key");
        if (isset($_GET['mode']) && $_GET['mode'] == 'test') {
            $paypalKey = config("cart::paypal.sandbox_clientId");
            $stripeKey = config("cart::stripe.test_public_key");
        }
        $cardForm = config('cart::sa.card_form', 'stripe');
        if ($cardForm == 'paypal') {
            $paypalKey = config("cart::paypal.clientId_card");
        }
        $productsBySeller = [];
        // $productsBySeller = $this->checkStripeConnect($productIds);
        // if (!empty($productsBySeller)) {
        //     $stripeKey = config("cart::stripe.connected_public_key");
        // }
        $merchantItentifier = "";
        $configCertPath = config("cart::sa.apple_cert_path", "/printerval_apple_pay_prod/apple_pay_crt.pem");
        if (file_exists(storage_path($configCertPath))) {
            $clientCertificatePath = storage_path($configCertPath);
            $merchantItentifier = openssl_x509_parse(file_get_contents($clientCertificatePath))['subject']['UID'];
        }
        View::share('merchantItentifier', $merchantItentifier);

        View::share('usePaypalByLimit', $usePaypalByLimit);
        View::share('paypalKey', $paypalKey);
        View::share('countries', $countries);
        View::share('user', $user);
        View::share('isValidPaypalByProduct', $isValidPaypalByProduct);
        View::share('stripeKey', $stripeKey);
        View::share('productsBySeller', $productsBySeller);
    }

    private function checkStripeConnect($productIds) {
        $response = ApiClient::buildCustomRequest("/seller/check-verified-stripe?product_ids=" . implode(",", $productIds), "GET", []);
        if (isset($response['status']) && $response['status'] == 'successful') {
            $listValid = new \stdClass();
            foreach ($response['result'] as $key => $value) {
                if ($value) {
                    $listValid->{$key} = $value;
                }
            }
            return $listValid;
        }
        return new \stdClass();
    }

    private function onViewOrderItem($cartItems) {
        if (!$this->isPageRefresh($cartItems, 'checkout')) {
            $items = $this->getUntrackItem($cartItems, 'checkout');
            Module::action('viewCheckout', [
                'items' => $items,
            ]);
        }
    }

    protected function getLocations() {
        $data = NULL;
        $query = ApiClient::buildClient("location");
        $query->select(['id', 'name', 'is_urban', 'sorder']);
        $query->filter("parent_id", Client::SELECTION_EQUAL, 0);
        $result = $query->get();
        if ( isset($result['status'])
        && $result['status'] == 'successful'
        && count($result['result']) > 0) {
            $data = $result['result'];
            $data = $this->buildLocationData($data);
        }
        return $data;
    }

    protected function getCart() {
        $data = NULL;
        $query = ApiClient::buildClient("cart");
        $query->filter("token", Client::SELECTION_EQUAL, "test");
        $query->embed('cartItems');
        $query->embed('cartItems.product');
        if (shouldUseNewInterface()) {
            $query->addField("use_new_interface", true);
        }
        $result = $query->first();

        if (isset($result['status'])
        && $result['status'] == 'successful'
        && $result['result']
        && count($result['result']) > 0 ) {
            $data = $result['result'];
        }
        return $data;
    }

    protected function buildLocationData($data) {
        $temp = [
            [
                'id' => -1,
                'name' => 'Select City',
                'is_urban' => -1,
                'sorder' => -1
            ]
        ];
        foreach($data as $index => $item) {
            if ( $item['id'] == 24 ) {
                unset($data[$index]);
                $temp[] = $item;
            }
            if ( $item['id'] == 31 ) {
                unset($data[$index]);
                $temp[] = $item;
            }
        }
        $data = array_merge($temp, $data);
        return $data;
    }

    public function isShowConversion($order) {
        $retVal = true;

        if (isset($order['order_metas']) && count($order['order_metas'])) {
            foreach ($order['order_metas'] as $item) {
                if ($item['key'] == 'showed_conversion' && $item['value']) {
                    $retVal = false;
                }
            }
        }
        $locale = env('APP_LOCALE');
        if (empty($locale)){
            $locale = 'US';
        }
        $locale = $locale . '_';

        $isCustomLocale = config('cart::sa.custom_locale', false);
        if ($isCustomLocale) {
            $localeCacheKey = env('LOCALE_CACHE_KEY', NULL);
            if (!empty($localeCacheKey)) {
                $locale = $localeCacheKey . '_';
            }    
        }
        
        if (Redis::get('IS_SHOW_CONVERSION_' . $locale . $order['id'])) {
            $retVal = false;
        } else {
            Redis::set('IS_SHOW_CONVERSION_' . $locale . $order['id'], 1);
        }

        if ($retVal) {
            OrderMeta::create([
                'order_id' => $order['id'],
                'key' => 'showed_conversion',
                'value' => 1
            ]);
        }

        return $retVal;
    }

    public function finish (Request $request) {
       header("Cache-Control: no-store, must-revalidate, max-age=0");
       header("Pragma: no-cache");
       header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        $orderId = $request->input('order_id');
        $locale = env('APP_LOCALE');
        if ($locale) {
            $locale = "/" . $locale;
        }
        \Log::useDailyFiles(storage_path() . '/logs/view-finish.log');

        if ($orderId) {
            $order = $this->getOrder($orderId);
            if ($order) {
                if ($this->isShowConversion($order)) {
                    $maxTimeShipping = $this->getOrderMaxShippingTime($orderId);
                    $isOldCustomer = $this->getIsOldCustomer($orderId);
                    if (count($order["child_orders"]) > 0) {
                        foreach ($order["child_orders"] as $key => $value) {
                            $order["profit"] += $value["profit"];
                            if (isset($order['total_fee_cost']) && isset($value['total_fee_cost'])){
                                $order["total_fee_cost"] += $value["total_fee_cost"];
                            }
                            if (isset($order['offsite_ads_value']) && isset($value['offsite_ads_value'])){
                                $order["offsite_ads_value"] += $value["offsite_ads_value"];
                            }
                            $order["amount"] += $value["amount"];
                            $order["shipping_fee"] += $value["shipping_fee"];
                            $order["discount"] += $value["discount"];
                            if (isset($order["items"]) && isset($value["items"])) {
                                $order["items"] = array_merge($order["items"], $value["items"]);
                            }
                        }
                    }
                    View::share('maxTimeShipping', floatVal($maxTimeShipping) + 5);
                    View::share('order', $order);
                    $items = isset($order['items']) ? $order['items'] : [];
                    $this->clearPageRefresh($items);
                    $customer = isset($order['customer']) ? $order['customer'] : [];
                    View::share('customerOrder', $customer);
                    if (isset($order['attributes']['from']) && !empty($order['attributes']['from'])){
                        preg_match('/facebook|instagram/',$order['attributes']['from'],$matches);
                        if (!empty($matches)){
                            View::share('purchaseEventPixel', 'purchaseEventPixel');
                            View::share('fromSource', 'facebook');
                        }
                    }
                    $isRemakeOrder = false;
                    if (isset($order['attributes']['origin_order_id'])){
                        $isRemakeOrder = true;
                        View::share('ignoreType', 'remakeOrder');
                    }
                    if (isset($order['hasSellerProduct'])){
                        View::share('purchaseEventSeller', 'purchase_seller');
                    }

                    Module::action('purchase', [
                        'items' => $items,
                        'amount' => $order['amount'],
                        'shipping_fee' => $order['shipping_fee'],
                        'discount' => $order['discount'],
                        'payment_type' => $order['payment_type'],
                        'payment_status' => $order['payment_status'],
                        'name' => isset($customer['name']) ? $customer['name'] : '',
                        'email' => isset($customer['email']) ? $customer['email'] : '',
                        'phone' => isset($customer['phone']) ? $customer['phone'] : '',
                        'promotion_code' => $order['promotion_code'],
                    ]);

                    if ($order['payment_type'] != 'RESERVE' && !$isRemakeOrder){
                        $this->trackingPlaceOrder($order);
                        $this->facebookConversion($order);
                        $this->pinterestConversion($order);
                        $this->snapchatConversion($order);
                        $this->tiktokConversion($order);
                        $this->redditConversion($order);
                        $this->awinConversion($order);
                    }
                    if (config("discount::sa.use_discount", false)) {
                        $this->triggerAsyncRequest(config("app.url") . $locale . "/discount/increment?order_id=" . $order["id"], "GET", [], []);
                    }
                    if (empty($order["profit"])){
                        $this->pushNotifyToDiscord('Order ID: ' . $orderId . ' - Profit is empty', json_encode($order));
                    }
                    $itemIds = [];
                    $totalQuantity = 0;
                    $itemCategories = [];
                    foreach ($order["items"] as $item) {
                        $itemIds[] = $item["product_id"];
                        $totalQuantity += $item["quantity"];
                        if (isset($item['category_id'])){
                            $itemCategories[$item['category_id']] = $item['category_id'];
                        }
                    }
                    View::share('totalQuantity', $totalQuantity);
                    View::share('itemCategories', $itemCategories);
                    $isSendFeedBack = $this->isSendFeedback($itemIds);
                    View::share('isSendFeedBack', $isSendFeedBack);
                    \Log::info("Locale - " . $locale . " - View finish - Order ID: " . $orderId);
                    view()->share('metaTitle', __('Finish'));
                    if ($isRemakeOrder && $order['amount'] == 0) {
                        ApiClient::buildCustomRequest("/finish-exchange-order?", 'POST', ['order_id' => $orderId, 'service_token' => 'megaads@123'], []);
                    }
                    $isValidShowTip = $this->isValidShowTip($order);
                    View::share('isValidShowTip', $isValidShowTip);
                    return Module::view('checkout.finish');
                } else {
                    \Log::info("Cart redirect: " . $locale . " - isShowConversion - Order ID: " . $orderId);
                    return redirect()->route('cart');
                }
            } else {
                \Log::info("Cart redirect: " . $locale . " - " . $orderId);
                return redirect()->route('cart');
            }
        } else {
            \Log::info("Cart redirect: " . $locale . " - Not found order ID: " . $orderId);
            return redirect()->route('cart');
        }

    }

    public function isValidShowTip($order) {
        $isValidShowTip = "";
        if ($order['tips'] == 0) {
            if ($order["payment_type"] == "PAYPAL" || $order["payment_type"] == "PAYPAL_EXPRESS") {
                $isValidShowTip = "paypal";
            } else {
                $isValidShowTip = "stripe";
            }
        }
        return $isValidShowTip;
    }

    public function cancel (Request $request) {
        header("Cache-Control: no-store, must-revalidate, max-age=0");
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        $orderId = $request->input('order_id');
        view()->share('metaTitle', __('Cancel'));
        if ($orderId) {
            $order = $this->getOrder($orderId);
            if ($order) {
                View::share('order', $order);
            }
        }
        return Module::view('checkout.cancel');
    }

    public function getOrder($orderId) {
        $result = false;
        $data = ApiClient::buildCustomRequest("/order/retrieve/$orderId", 'GET', [], ["api-token: megaads@123"]);
        if (array_key_exists("status", $data) && $data['status'] == 'successful') {
            $result = (array) $data["result"];
        }
        return $result;
    }

    public function getOrderMaxShippingTime($orderId) {
        $result = 0;
        $data = ApiClient::buildCustomRequest("/shipping-fee/max-shipping-time?order_id=" . $orderId, 'GET', [], []);
        if (array_key_exists("result", $data)) {
            $result = $data['result'];
        }

        return $result;
    }

    public function getIsOldCustomer($orderId) {
        $result = 0;
        $data = ApiClient::buildCustomRequest("/order/is-old-customer?order_id=" . $orderId, 'GET', [], []);
        if (array_key_exists("result", $data)) {
            $result = $data['result'];
        }

        return $result;
    }

    private function getCartItems($token = null) {
        $cartItems = [];
        $query = ApiClient::buildClient("cart/get-cart-item");
        if (!$token) {
            $token = getFingerprint();
        }
        $user = \Auth::guard("customer")->user();
        $query->addField("token", $token);
        $query->addField("customerId", isset($user->id) ? $user->id : null);
        if (shouldUseNewInterface()) {
            $query->addField("use_new_interface", true);
        }
        $result = $query->get();
        if (isset($result['status']) && $result['status'] == 'successful') {
            $cartItems = $result['items'];
        }
        return $cartItems;
    }

    public function calculateDeliveryTime(Request $request) {
        $retVal = '<p>An error occurred during the shipping time. Please enter a more accurate address.</p>';

        if ($request->has('countryCode') && $request->has('zipCode')) {
            $countryCode = $request->input('countryCode');
            $zipCode = trim($request->input('zipCode'));
            $cityName = '';
            $stateName = '';

            /** Search Country Code */
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://wwwapps.ups.com/asc/search");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=UTF-8'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, "requester=CTC&country=$countryCode&postal=$zipCode");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $locations = curl_exec($ch);
            curl_close($ch);

            if (!empty($locations)) {
                $locations = json_decode($locations);
                if (!empty($locations->location_list)) {
                    $location = $locations->location_list[0];
                    if (!empty($location->polDiv2)) {
                        $cityName = urlencode(str_replace('&#32;', ' ', $location->polDiv2));
                    }
                    if (!empty($location->polDiv1)) {
                        $stateName = urlencode(str_replace('&#32;', ' ', $location->polDiv1));
                    }
                }
            }


            $currentDate = new \DateTime();
            $currentDate->modify('+5 day');

            $params = "refreshmod1=&shipDate=" . $currentDate->format('Y-m-d') . "&quoteType=transitTimeOnly&origCountry=CN&origCity=QIANSHAN&origPostalCode=246320&origStates=+&
            shipmentType=smallPkg&destCountry=$countryCode&destCity=$cityName&destPostalCode=$zipCode&destStates=$stateName&
            pickerDate=". urlencode($currentDate->format('d/m/Y')) ."&currencyScalar=500&currencyUnits=THB&weight=1&weightType=KGS";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://wwwapps.ups.com/ctc/results");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=UTF-8'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            $err = curl_error($ch);
            curl_close($ch);

            if ($err) {
                return $retVal;
            }

            $retVal = '<p>Orders are usually processed within <span>3-5</span> business days</p>';

            try {
                $dom = HtmlDomParser::str_get_html($response);
                $serviceRows = $dom->getElementById('servicerow0');
                if (!empty($serviceRows)) {
                    $tdColumns = $serviceRows->find('td');
                    if (count($tdColumns) == 3) {
                        $timeColumn = $tdColumns[1]->find('p');
                        if (isset($timeColumn[2])) {
                            $time = str_replace(' ', ' ', html_entity_decode($timeColumn[2]->plaintext, ENT_QUOTES, "UTF-8"));
                            $delivery = new \DateTime($time);
                            $retVal .= "<p>Standard shipping between <span>{$delivery->format('M d, Y')} - {$delivery->modify('+5 day')->format('M d, Y')}</span></p>";
                        }
                    }
                }

            } catch (\Exception $ex) { }
        }

        return $retVal;
    }

    public function checkoutAction(Request $request) {
        if ($request->has('type') && $request->has('data')) {
            $type = $request->input('type');
            $data = $request->input('data');
            Module::action($type, $data);
        }
    }

    protected function triggerAsyncRequest($url, $method = "GET", $params = [], $headers = []) {
        $channel = curl_init();
        curl_setopt($channel, CURLOPT_URL, $url);
        // curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
        curl_setopt($channel, CURLOPT_TIMEOUT, 120);
        curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
        if($method == "post" || $method == "POST") {
            curl_setopt($channel, CURLOPT_POST, true);
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($params));
        }
        if ($headers) {
            curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($channel, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($channel);
        curl_close($channel);
        return json_decode($data, true);
    }

    private function getShippingConfig() {
        $config = getOption("shipping_fee_config");
        if (!$config) {
            $config = config('cart::shipping.locations', []);
        }
        return $config;
    }

    /**
     *Tracking placed order for email marketing klaviyo.com
     * @order array
     */
    private function trackingPlaceOrder($order){
        $token = config('cart::sa.privateApiKeyKlaviyo');
        if (!empty($token)){
            $retVal = [
                'type' => 'event'
            ];
            $attributes = [
                'time' => date('Y-m-d\TH:i:s'),
                'value' => $order['amount'],
                'unique_id' => $order['code'],
            ];
            $metric = [
                'data' => [
                    'type' => 'metric',
                    'attributes' => ['name' => 'Placed Order'],
                ]
            ];
            $attributes['metric'] = $metric;
            $customerProperties = [];
            if (isset($order['customer'])){
                $customerProperties['email'] = $order['customer']['email'];
                $location = [];
                $location['city'] = $order['city_name'];
                $location['region'] = $order['state_name'];
                $location['zip'] = $order['zip_code'];
                $location['country'] = isset($order['country']['iso'])?$order['country']['iso']:'';
                $customerProperties['location'] = $location;
            }
            $locale = env('APP_LOCALE');
            $urlLocation = config("app.url");
            $urlLocation .= '/'.$locale;
            $items = [];
            $names = [];
            foreach($order['items'] as $item){
                $names[] = $item['name'];
                $trackItem = [
                    'ProductID' => $item['product_id'],
                    'SKU' => $item['sku'],
                    'ProductName' => $item['name'],
                    'Quantity' => $item['quantity'],
                    'ItemPrice' => $item['price'],
                    'RowTotal' => $item['price'] * $item['quantity'],
                    'ProductURL' => $urlLocation . $item['url'],
                    'ImageURL' => $item['image_url']
                ];
                $items[] = $trackItem;
            }
            $properties = [
                'OrderId' => $order['code'],
                'ItemNames' => $names,
                'Items' => $items
            ];
            $attributes['properties'] = $properties;
            $attributes['profile'] = [
                'data' =>[
                    'type' => 'profile',
                    'attributes' => $customerProperties
                ]
            ];
            $retVal['attributes'] = $attributes;
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, "https://a.klaviyo.com/api/events");
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode(['data' => $retVal]));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 600);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Accept: application/json",
                "Content-Type: application/json",
                "Revision: 2023-10-15",
                "Authorization: Klaviyo-API-Key ".$token
            ]);
            $data = curl_exec($channel);
            curl_close($channel);
            \Log::info("klaviyo Conversion ".$data ." " . $order['id'] . " - data: " . json_encode(['data' => $retVal]));
        }
    }
    /**
     *Tracking placed order for facebook
     * @order array
     */
    private function facebookConversion($order){
        $isSendConversion = true;
        $ignoreSource = optionsByDomain("ignore_source_conversion",false);
        if (!$ignoreSource){
            if (isset($order['attributes']['from']) && !empty($order['attributes']['from'])){
                preg_match('/facebook|instagram/',$order['attributes']['from'],$matches);
                if (empty($matches)){
                    $isSendConversion = false;
                    \Log::info("Facebook Conversion - " . $order['id'] . " - data: ". $order['attributes']['from']);
                }
            }else{
                $isSendConversion = false;
                \Log::info("Facebook Conversion - " . $order['id'] . " - data: No from source");
            }
        }
        $pixelData = optionsByDomain("meta_pixel_ids");
        if (!$ignoreSource){
            $pixelData = optionsByDomain("test_meta_pixel_ids");
        }

        if (!empty($pixelData)){
            \Log::info("Facebook Conversion - " . $order['id'] . " - data: send");
            $conversionData = [];
            $countryCode = null;
            $locale = env('APP_LOCALE');
            if (empty($locale)){
                $locale = 'us';
            }

            $conversionData['event_name'] = "Purchase";
            $conversionData['event_time'] = time();
            $conversionData['event_id'] = $order['code'];
            $conversionData['user_data'] = $this->getUserData($order);
            $conversionData['event_source_url'] = url()->full();
            $conversionData['action_source'] = "website";
            $conversionData['custom_data'] = $this->getCustomDataForFacebook($order, $locale);
            if (is_array($pixelData)){
                foreach ($pixelData as $pixel){
                    if (is_object($pixel)){
                        $pixel = get_object_vars($pixel);
                    }
                    $pixelId = $pixel['pixel_id'];
                    $accessToken = $pixel['access_token'];
                    $url = "https://graph.facebook.com/v17.0/$pixelId/events?access_token=$accessToken";
                    $channel = curl_init();
                    curl_setopt($channel, CURLOPT_URL, $url);
                    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode(['data' => [$conversionData]]));
                    curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
                    curl_setopt($channel, CURLOPT_TIMEOUT_MS, 600);
                    curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                    curl_setopt($channel, CURLOPT_HTTPHEADER, [
                        "Accept: text/html",
                        "Content-Type: application/json"
                    ]);
                    $data = curl_exec($channel);
                    curl_close($channel);
                    \Log::info("Facebook Conversion - $pixelId " . $order['id'] . " - data: " . json_encode($data));
                }
            }
        }

    }
    private function getCustomDataForFacebook($order){
        $retVal = [];
        $contentIds = [];
        foreach($order['items'] as $item){
            $contentIds[] = $item['sku'];
        }
        $retVal['content_ids'] = $contentIds;
        $retVal['currency'] = env('CURRENCY_UNIT','USD');
        $retVal['order_id'] = $order['code'];
        $profit = $order['profit'];
        if (isset($order['other_fee'])){
            $profit = $order['profit'] - $order['other_fee'];
        }
        $retVal['value'] = $profit;
        return $retVal;
    }

    private function getUserData($order){
        $userData = [];
        if (isset($order['customer'])){
            $userData['em'] = hash('sha256', $order['customer']['email']);
            $userData['ph'] = hash('sha256', $order['customer']['phone']);
            $userData['fn'] = hash('sha256', $order['customer']['full_name']);
            $userData['ln'] = hash('sha256', $order['customer']['full_name']);
            $userData['ct'] = hash('sha256', $order['city_name']);
            $userData['zp'] = hash('sha256', $order['zip_code']);
            if (isset($order['country']['iso'])){
                $countryCode = hash('sha256', strtolower($order['country']['iso']));
                $userData['country'] = $countryCode;

            }
            if (isset($order['attributes']['ip']) && !empty($order['attributes']['ip'])){
                $userData['client_ip_address'] = $order['attributes']['ip'];
            }
            if (isset($order['attributes']['user_agent']) && !empty($order['attributes']['user_agent'])){
                $userData['client_user_agent'] = $order['attributes']['user_agent'];
            }
            if (isset($_COOKIE['_fbc'])){
                $userData['fbc'] = $_COOKIE['_fbc'];
            }
            if (isset($_COOKIE['_fbp'])){
                $userData['fbp'] = $_COOKIE['_fbp'];
            }
        }
        return $userData;
    }

    private function pinterestConversion($order){
        $config = optionsByDomain("pinterest_account_config");
//        $config['ad_account_id'] = 549766263511;
//        $config['access_token'] = 'pina_AIA2RFAWADCYEAQAGAAJGDGQCFMADCQBAAAAADUWWWTYIMVMNTCKSGJNTPKJMWF3XVKS6CX4N7NLUY4R5TSLTVC7BKQVIGYA';
        if (isset($config['ad_account_id']) && isset($config['access_token'])){
            $accountId = $config['ad_account_id'];
            $accessToken = $config['access_token'];
            $data['event_name'] = 'checkout';
            $data['action_source'] = 'web';
            $data['partner_name'] = 'direct';
            $data['event_time'] = time();
            $data['event_id'] = $order['code'];
            $userData = $this->getUserData($order);
            $userData['em'] = [$userData['em']];
            $userData['ph'] = [$userData['ph']];
            $userData['ln'] = [$userData['ln']];
            $userData['fn'] = [$userData['fn']];
            $userData['ct'] = [$userData['ct']];
            $userData['zp'] = [$userData['zp']];
            if (isset($userData['country'])){
                $userData['country'] = [$userData['country']];
            }
            if (isset($userData['fbc'])){
                unset($userData['fbc']);
            }
            if (isset($userData['fbp'])){
                unset($userData['fbp']);
            }

            $data['user_data'] = $userData;
            $data['event_source_url'] = url()->full();
            $customData = $this->getCustomDataForFacebook($order);
            $customData['value'] = number_format($customData['value'],0,'.','');
            $data['custom_data'] = $customData;
            $postData['data'] = [$data];
            $url = "https://api.pinterest.com/v5/ad_accounts/$accountId/events";
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, $url);
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 1000);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Accept: text/html",
                "Content-Type: application/json",
                "Authorization: Bearer $accessToken",
            ]);
            $result = curl_exec($channel);
            if (curl_errno($channel)) {
                $error_msg = curl_error($channel);
                \Log::error("Pinterest Conversion - " . $order['id'] . " - data: " . json_encode($error_msg));
            }
            curl_close($channel);
            \Log::info("Pinterest Conversion - " . $order['id'] . " - data: " . json_encode($result));
        }
    }

    private function snapchatConversion($order){
        $config = optionsByDomain("snapchat_account_config");
//        $config['ad_account_id'] = 549766263511;
//        $config['access_token'] = 'pina_AIA2RFAWADCYEAQAGAAJGDGQCFMADCQBAAAAADUWWWTYIMVMNTCKSGJNTPKJMWF3XVKS6CX4N7NLUY4R5TSLTVC7BKQVIGYA';
        if (isset($config['ad_account_id']) && isset($config['access_token'])){
            $accountId = $config['ad_account_id'];
            $accessToken = $config['access_token'];
            $data['event_name'] = 'PURCHASE';
            $data['action_source'] = 'website';
            $data['event_source_url'] = url()->full();;
            $data['event_time'] = time();
            $userData = $this->getUserData($order);
            unset($userData['country']);
            unset($userData['fbc']);
            unset($userData['fbp']);
            if (isset($userData['client_user_agent'])){
                $userData['user_agent'] = $userData['client_user_agent'];
                unset($userData['client_user_agent']);
            }
            if (isset($_COOKIE['ScCid'])){
                $userData['sc_click_id'] = $_COOKIE['ScCid'];
            }
            if (isset($_COOKIE['_scid'])){
                $userData['sc_cookie1'] = $_COOKIE['_scid'];
            }
            $data['user_data'] = $userData;
            $customData = $this->getCustomDataForFacebook($order);
            $cData = [];
            $cData['event_id'] = $order['code'];
            $cData['content_ids'] = $customData['content_ids'];
            $cData['value'] = $customData['value'];
            $cData['currency'] = $customData['currency'];
            $cData['event_id'] = $customData['order_id'];
            $cData['order_id'] = $customData['order_id'];
            $data['custom_data'] = $cData;

            $postData = ['data' => [$data]];
            $url = "https://tr.snapchat.com/v3/$accountId/events/?access_token=$accessToken";
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, $url);
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 10000);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Content-Type: application/json",
            ]);
            $result = curl_exec($channel);
            if (curl_errno($channel)) {
                $error_msg = curl_error($channel);
                \Log::error("Snapchat Conversion - " . $order['id'] . " - data: " . json_encode($error_msg));
            }
            curl_close($channel);
            \Log::info("Snapchat Conversion - " . $order['id'] . " - data: " . json_encode($postData));
            \Log::info("Snapchat Conversion - " . $order['id'] . " - data: " . ($result));
        }
    }

    private function tiktokConversion($order){
        $config = optionsByDomain("tiktok_account_config");
//        $config['ad_account_id'] = 549766263511;
//        $config['access_token'] = 'pina_AIA2RFAWADCYEAQAGAAJGDGQCFMADCQBAAAAADUWWWTYIMVMNTCKSGJNTPKJMWF3XVKS6CX4N7NLUY4R5TSLTVC7BKQVIGYA';
        if (isset($config['ad_account_id']) && isset($config['access_token'])){
            $accountId = $config['ad_account_id'];
            $accessToken = $config['access_token'];
            $eventData['pixel_code'] = $accountId;
            $eventData['event'] = 'CompletePayment';
            $eventData['timestamp'] = date('c', time());
            $eventData['event_id'] = $order['code'];
            $userData = $this->getUserData($order);
            $user['email'] = $userData['em'];
            $user['phone_number'] = $userData['ph'];
            if (isset($userData['client_user_agent'])){
                $user['user_agent'] = $userData['client_user_agent'];
            }
            if (isset($userData['client_ip_address'])){
                $user['ip'] = $userData['client_ip_address'];
            }
            $page['url'] = url()->full();

            $customData = $this->getCustomDataForFacebook($order);

            $properties['value'] = $customData['value'];
            $properties['currency'] = $customData['currency'];
            $properties['content_type'] = 'product';
            $contents = [];
            foreach($order['items'] as $item){
                $contents[] = [
                    "price" => $item['price'],
                    "quantity" => $item['quantity'],
                    "content_id" => $item['sku']
                ];
            }
            $properties['contents'] = $contents;
//            $ad = [];
//            if (isset($_COOKIE['ttclid'])){
//                $ad['callback'] = $_COOKIE['ttclid'];
//            }
            if (isset($_COOKIE['_ttp'])){
                $user['ttp'] = $_COOKIE['_ttp'];
            }
            $data['user'] = $user;
            $data['page'] = $page;
            $eventData['context'] = $data;
            $eventData['properties'] = $properties;

            $postData = $eventData;
            $url = "https://business-api.tiktok.com/open_api/v1.3/pixel/track/";
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, $url);
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 10000);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Accept: text/html",
                "Content-Type: application/json",
                "Access-Token: $accessToken",
            ]);
            $result = curl_exec($channel);
            if (curl_errno($channel)) {
                $error_msg = curl_error($channel);
                \Log::error("Tiktok Conversion - " . $order['id'] . " - data: " . json_encode($error_msg));
            }
            curl_close($channel);
            \Log::info("Tiktok Conversion - " . $order['id'] . " - data: " . json_encode($postData));
            \Log::info("Tiktok Conversion - " . $order['id'] . " - data: " . json_encode($result));
        }
    }

    private function pushNotifyToDiscord($title,$message){
        $url = 'https://discordapp.com/api/webhooks/1214037746893586462/i-RT-IExWOiRRMNhfy690wTwdsc3RFfqbHGLpNf3AzEl23D5cAT3NODufZAHPCqSTAhd';
        $data = [
            'contents' => '',
            'embeds' => [
                [
                    'title' => $title,
                    'description' => $message,
                    'color' => 16741120,
                    'author' => [
                        'name' => env('APP_NAME'),
                        'icon_url' => 'https://play-lh.googleusercontent.com/T1EGTVV0CngCubBeKkBYRfdRstn2mFy_bAH5UQTCP83QYuuGMMC7kvicXlpb6leHKfaF=w240-h480-rw',
                    ]
                ]
            ],
            'attachments' => []
        ];
        $this->triggerAsyncRequest($url,'POST',$data,['Content-Type:application/json']);
    }

    private function isSendFeedback($productIds){
        $retVal = 1;
        if (!empty($productIds)){
            $config = \DB::table('option')->where('key','feedback:ignore_category_ids')->first(['value']);
            if (!empty($config)){
                $categoryIds = json_decode($config->value);
                $count = \DB::table('product_n_category')->whereIn('product_id',$productIds)->whereIn('category_id',$categoryIds)->count();
                if ($count > 0){
                    $retVal = 0;
                }
            }
        }
        return $retVal;
    }

    public function exchange(Request $request) {
        if ($request->has("order_code") && $request->has("email")) {
            $customer = \DB::table(\DB::raw('`' . env('DB_DATABASE_CUSTOMER', 'printerval_customer') . '`.`customer`'))
                ->where('email', $request->input('email'))
                ->orderBy('id', 'desc')
                ->first();
            if ($customer) {
                $query = ApiClient::buildClient("order");
                $filterData = "code=" . $request->input("order_code") . ",customer_id=" . $customer->id . ",payment_status=PAID,status=PROCESSING";
                $query->addField("filters", $filterData);
                $query->addField("service_token", "megaads@123");
                $data = $query->first();
                if (isset($data["result"]) && count($data["result"]) > 0) {
                    $originOrder = $data["result"];
                    if (isset($originOrder["attributes"])) {
                        $attributes = $originOrder["attributes"];
                        if (isset($attributes["origin_order_id"]) || isset($attributes["exchange_order_id"])) {
                            abort(404);
                        }
                    }
                    $exchangeFingerprint = (isset($_COOKIE['exchange_fingerprint']) && !empty($_COOKIE['exchange_fingerprint'])) ? $_COOKIE['exchange_fingerprint'] : Session::getId();
                    if (!isset($_COOKIE['exchange_fingerprint']) || empty($_COOKIE['exchange_fingerprint'])){
                        setcookie('exchange_fingerprint', $exchangeFingerprint, time() + (365 * 24 * 60 * 60), "/");
                    }
                    $cartItems = $this->buildCartExchange($originOrder['id'], $exchangeFingerprint);
                    view()->share('exchangeFingerprint', $exchangeFingerprint);
                    view()->share('originOrder', $originOrder);
                    view()->share('pageType', "purchase");
                    view()->share('metaTitle', __('Exchange'));
                    $this->buildShareData();
                    return Module::view('checkout.exchange');
                }
            }
        }
        abort(404);
    }

    private function buildCartExchange($orderId, $exchangeFingerprint) {
        $url = "/build-cart-exchange";
        $data = [
            "order_id" => $orderId,
            "exchange_fingerprint" => $exchangeFingerprint . "_" . $orderId,
            "service_token" => "megaads@123"
        ];
        $response = ApiClient::buildCustomRequest($url, "POST", $data, []);
        if (isset($response['status']) && $response['status'] == 'successful') {
            return $response['result'];
        }
        return [];

    }

    public function exchangeShipping(Request $request)
    {
        if ($request->has('order_code') && $request->has('email')) {
            $customer = \DB::table(\DB::raw('`' . env('DB_DATABASE_CUSTOMER', 'printerval_customer') . '`.`customer`'))
                ->where('email', $request->input('email'))
                ->orderBy('id', 'desc')
                ->first();
            if (!empty($customer)) {
                $query = ApiClient::buildClient('order');
                $filterData = "code=" . $request->input("order_code") . ",customer_id=" . $customer->id . ",payment_status=PAID,status=PROCESSING";
                $query->addField('filters', $filterData);
                $query->addField('service_token', 'megaads@123');
                $data = $query->first();
                if (isset($data['result']) && count($data['result']) > 0) {
                    $originOrder = $data["result"];
                    $exchangeFingerprint = (!empty($_COOKIE['exchange_fingerprint'])) ? $_COOKIE['exchange_fingerprint'] : Session::getId();
                    if (empty($_COOKIE['exchange_fingerprint'])){
                        setcookie('exchange_fingerprint', $exchangeFingerprint, time() + (365 * 24 * 60 * 60), "/");
                    }
                    $cartItems = $this->buildCartExchange($originOrder['id'], $exchangeFingerprint);
                    view()->share('exchangeFingerprint', $exchangeFingerprint);
                    view()->share('originOrder', $originOrder);
                    view()->share('pageType', "purchase");
                    view()->share('metaTitle', __('Exchange shipping info'));

                    $this->buildShareData();
                    return Module::view('checkout.exchange-shipping');
                }
            }
        }
        abort(404);
    }

    private function redditConversion($order){
        $config = optionsByDomain("reddit_account_config");
//        $config['ad_account_id'] = 't2_dj4ylwdu';
//        $config['access_token'] = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IlNIQTI1NjpzS3dsMnlsV0VtMjVmcXhwTU40cWY4MXE2OWFFdWFyMnpLMUdhVGxjdWNZIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyIiwiZXhwIjo0ODkwNDM5OTczLjMyODcyNCwiaWF0IjoxNzM0Njc5OTczLjMyODcyNCwianRpIjoiWjJLTmo5dEFBN1hiREFJNzJBNDJCamlVNjZ6RUFRIiwiY2lkIjoiMVExRU96VFBXbll2ZXJocHR2Z1dzUSIsImxpZCI6InQyXzFldXg2NWp6YXUiLCJhaWQiOiJ0Ml8xZXV4NjVqemF1IiwibGNhIjoxNzMzOTkyNzgwMjgxLCJzY3AiOiJlSnlLVmtwTUtVN096eXRMTFNyT3pNOHJWb29GQkFBQV9fOUJGZ2J1IiwiZmxvIjoxMCwibGwiOnRydWV9.f8oBIDZoA93KuCJ6eriDBeb7jXYImDFuqKtah50Xy4N5oMgNt94B4HGSHqgGmY1xUVIwW7JFCBbX4I_aAWtpp2brl7Prl7GOXpXG7w6S_uBgiM4yTlNa6DrB3blcgXq9xf42WzpS59ZMHU335OJe8U4lBWwhdUD2CexaE8Xfu6qMisrQ5frw1elNhGq18HpylRQAtVbNxlh4nMpFmAR56J8HK0NTcQlFczHA9lpTqtE4iPUcrFcHrOWi3_dYxUcIoodhnDFxrQvAhHwo8r0c2FxCOAh5bbfeojVNCkMQbs4vPzgSlyLJBptqgaflgXPmgeuJ5ItE4DRe2Tf3sFKwsA';
        if (isset($config['ad_account_id']) && isset($config['access_token'])){
            $accountId = $config['ad_account_id'];
            $accessToken = $config['access_token'];
            $eventData['event_type']['tracking_type'] = 'Purchase';
            $eventData['event_at'] = date('c', time());
            $userData = $this->getUserData($order);
            $user['email'] = $userData['em'];
            if (isset($userData['client_user_agent'])){
                $user['user_agent'] = $userData['client_user_agent'];
            }
            if (isset($userData['client_ip_address'])){
                $user['ip_address'] = $userData['client_ip_address'];
            }
            if (isset($_COOKIE['_rdt_cid'])){
                $eventData['click_id'] = $_COOKIE['_rdt_cid'];
            }
            if (isset($_COOKIE['_rdt_uuid'])){
                $user['uuid'] = $_COOKIE['_rdt_uuid'];
            }
            $customData = $this->getCustomDataForFacebook($order);

            $properties['value_decimal'] = $customData['value'];
            $properties['currency'] = $customData['currency'];
            $contents = [];
            $itemCount = 0;
            foreach($order['items'] as $item){
                $itemCount += $item['quantity'];
                $contents[] = [
                    "name" => $item['name'],
                    "id" => $item['sku']
                ];
            }
            $properties['item_count'] = $itemCount;
            $properties['conversion_id'] = $order['code'];

            $properties['products'] = $contents;
            $eventData['user'] = $user;
            $eventData['event_metadata'] = $properties;

            $postData = ['events' =>[$eventData]];
            $url = "https://ads-api.reddit.com/api/v2.0/conversions/events/$accountId";
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, $url);
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 10000);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Accept: text/html",
                "Content-Type: application/json",
                "Authorization: Bearer $accessToken",
            ]);
            $result = curl_exec($channel);
            if (curl_errno($channel)) {
                $error_msg = curl_error($channel);
                \Log::error("Reddit Conversion - " . $order['id'] . " - data: " . json_encode($error_msg));
            }
            curl_close($channel);
            \Log::info("Reddit Conversion - " . $order['id'] . " - data: " . json_encode($postData));
            \Log::info("Reddit Conversion - " . $order['id'] . " - data: " . json_encode($result));
        }
    }

    private function awinConversion($order){
        $config = optionsByDomain("awin_account_config");
//        $config['ad_account_id'] = 109364;
//        $config['access_token'] = 'c71c19d9-77e0-4fda-b82b-e33e7284e600';
        if (isset($config['ad_account_id']) && isset($config['access_token'])){
            $accountId = $config['ad_account_id'];
            $accessToken = $config['access_token'];
            $orderData['orderReference'] = $order['code'];
            $orderData['amount'] = $order['amount'] -  $order['shipping_fee'] - $order['other_fee'] - $order['tips'];
            $orderData['channel'] = 'aw';
            $orderData['currency'] = env('CURRENCY_UNIT','USD');
            if (isset($_COOKIE['AwinChannelCookie'])){
                $orderData['channel'] = $_COOKIE['AwinChannelCookie'];
            }
            $orderData['voucher'] = $order['promotion_code'];
            if (isset($_COOKIE['awc'])){
                $orderData['awc'] = $_COOKIE['awc'];
            }
            $orderData['voucher'] = $order['promotion_code'];
            $orderData['commissionGroups'] =[['code' => 'DEFAULT', 'amount' => $orderData['amount']]];

            $postData = ['orders' => [$orderData]];
            $url = "https://api.awin.com/s2s/advertiser/$accountId/orders";
            $channel = curl_init();
            curl_setopt($channel, CURLOPT_URL, $url);
            curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($channel, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($channel, CURLOPT_NOSIGNAL, 1);
            curl_setopt($channel, CURLOPT_TIMEOUT_MS, 10000);
            curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($channel, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($channel, CURLOPT_HTTPHEADER, [
                "Accept: text/html",
                "Content-Type: application/json",
                "x-api-key:$accessToken",
            ]);
            $result = curl_exec($channel);
            if (curl_errno($channel)) {
                $error_msg = curl_error($channel);
                \Log::error("awin Conversion - " . $order['id'] . " - data: " . json_encode($error_msg));
            }
            curl_close($channel);
            \Log::info("awin Conversion - " . $order['id'] . " - data: " . json_encode($postData));
            \Log::info("awin Conversion - " . $order['id'] . " - data: " . json_encode($result));
        }
    }

    public function lianPaymentSuccess(Request $request)
    {
        $retVal = [
            'code' => 200,
            'message' => 'success'
        ];
        $signature = $request->header('signature');
        $notifyBody = $request->except(['order_id', 'token']);
        $orderId = $request->input('order_id');
        $token = $request->input('token');
        $apiUrl = config('sa.api_url', 'https://api.printerval.com') . "/lian/payment-success?service_token=megaads@123&signature=$signature&order_id=$orderId&token=$token";
        $response = $this->triggerSyncRequest($apiUrl, 'POST', $notifyBody, ['Content-Type' => 'application/json']);
        Log::info('response api : ' . json_encode($response));
        if ($response['status'] != 'successful') {
            $retVal['message'] = 'fail';
            $retVal['code'] = 500;
        }

        return response()->json($retVal);
    }

    protected function triggerSyncRequest($url, $method = 'GET', $params = [], $headers = []) {
        $ch = curl_init();
        $timeout = 200;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        if ($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if ($method != 'GET') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $data = curl_exec($ch);
        if (curl_errno($ch)) {
            \Log::info('App\Http\Controllers\Controller triggerSyncRequest ERROR', [curl_error($ch), $url]);
        }
        curl_close($ch);
        return json_decode($data, true);
    }
}
