<?php

namespace Extension\TrafficLoadBalancerNew;

use Application\Request;
use Exception;
use Database\Connectors\ConnectionFactory;
use Application\Helper\Provider;
use Application\Config;
use Application\Http;
use Application\Registry;
use Lazer\Classes\Database;
use Application\CrmResponse;
use Application\CrmPayload;

class DelayPost
{
    
    public static function postRemoteData()
    {
        
        $isSplitOrder  = CrmPayload::get('meta.isSplitOrder');
        //$currentStepId = Session::get('steps.current.id');
        $campaignRouterEnable = Config::extensionsConfig('TrafficLoadBalancerNew.default_settings.enable_campaign_router');
        
        if (
            CrmResponse::has('orderId') !== true || 
            $isSplitOrder 
            //|| $currentStepId > 2
            ) {
            return;
        }
        

        $offerUrl   = CrmPayload::get('OFofferUrl');
        $affiliates = self::mapAffiliateKeys(CrmPayload::get('newOFAffiliates'));
        $orderFilerDetails = CrmPayload::get('newOFDetails');
        $orderFilerQueryParams = CrmPayload::get('newOFQueryParams');
        $orderFilerCurrentLb = CrmPayload::get('currentLb');
        
        $enableAffiliateMapping = Config::extensionsConfig('TrafficLoadBalancerNew.enable_affiliate_mapping');
        if ($enableAffiliateMapping)
        {
            $affiliateMappingConfiguration = Config::extensionsConfig('TrafficLoadBalancerNew.affiliates');
            foreach ($affiliateMappingConfiguration as $value)
            {
                if (array_key_exists($value['aff_param'], $affiliates))
                {
                    $requestParams = $orderFilerQueryParams[strtoupper($value['mapped_param'])];
                    if (!empty($requestParams))
                    {
                        $affiliates[$value['aff_param']] = $requestParams . '.' . $affiliates[$value['aff_param']];
                    }
                }
            }
        }
        
        $gateWaySwitcherId = Config::settings('gateway_switcher_id');
        $queryParams       = array(
            'offer_url'        => $offerUrl,
            'conf_scrap_count' => 0,
        );

        if (!empty($affiliates)) {
            $queryParams = array_replace($queryParams, $affiliates);
             $subaffiliatePost = Config::extensionsConfig('TrafficLoadBalancerNew.subaffiliate_post');            
            if(!$subaffiliatePost)
            {
                unset($queryParams['c1']);
                unset($queryParams['c2']);
                unset($queryParams['c3']);
                unset($queryParams['c4']);
                unset($queryParams['c5']);
                unset($queryParams['sId']);
            }
        }
        
        $currentStepId = CrmPayload::get('meta.stepId');        
        $queryParams['orderIds'] = array();
        
        for($i=1; $i<=$currentStepId; $i++) {
            if($currentStepId == $i) {
                $queryParams['orderIds'][$i] = CrmResponse::get('orderId');
            } 
//            else {
//                $queryParams['orderIds'][$i] = session::get(sprintf('steps.%d.orderId',$i));
//            }
        }

        $pixelManagerId = $orderFilerDetails['pixelManagerId'];
        $uniqueIds = $orderFilerDetails['uniqueIds'];
        $queryParams['orderIds'] = array_filter($queryParams['orderIds']);
        $queryParams['uniqueIds'] = array_filter($uniqueIds);
        $queryParams['uniqueIds']['pixelManagerId'] = $pixelManagerId;
        $queryParams['orderFilter'] = 'no';
        
        if((Config::extensionsConfig('TrafficLoadBalancerNew.default_settings.enable_remote'))){
            $scrapperStepId    = $currentStepId > 1 ? 2 : 1;
        }else{
            $scrapperStepId = $currentStepId;
        }
        
        
        $currentLoadBalancer = $orderFilerCurrentLb[$scrapperStepId];
        
        $isDisablePrepaidOrderFiler = Config::extensionsConfig('TrafficLoadBalancerNew.default_settings.disable_prepaid_orderfilter');
        
        if (
                    $currentLoadBalancer['scrapped'] && !$isDisablePrepaidOrderFiler && CrmPayload::get('meta.isPrepaidFlow') ||
                    $currentLoadBalancer['scrapped'] && !CrmPayload::get('meta.isPrepaidFlow')
            )
            {
                $queryParams['orderFilter'] = 'yes';
            }
            
            // Extra code if submit done before session set

            if (
                    ($currentStepId > 1) &&
                    (
                        ($orderFilerCurrentLb[1]['scrapped'] && !$isDisablePrepaidOrderFiler && CrmPayload::get('meta.isPrepaidFlow')) || 
                        ($orderFilerCurrentLb[1]['scrapped'] && !CrmPayload::get('meta.isPrepaidFlow'))
                    )
            )
            {
                $queryParams['orderFilter'] = 'yes';
            }

        $queryString = http_build_query($queryParams);
        
        if(!empty($campaignRouterEnable)) {
            $apiEndpoint = rtrim(Registry::system('systemConstants.UNIFY_CAMPAIGN_ROUTER_URL'), '/api');
            $routerAccessToken = Config::settings('router_access_token');
//            $hostName = Config::settings('host_name');
//            $hostName = str_replace(array("http://","https://","/"), "", $hostName);
//            if(!empty($hostName))
//            {
//                $apiEndpoint = 'https://'. $hostName;
//            }
            
            if($currentStepId == 1) {
                $queryString2 = $queryString.'&convert=yes&sales=yes';
            } else {
                $queryString2 = $queryString.'&convert=yes';
            }

            $url = sprintf(
                '%s/campaign-router/insert-data/%s/?%s', $apiEndpoint, $routerAccessToken, $queryString2
            );
        } else {
            $apiEndpoint = rtrim(Registry::system('systemConstants.NEW_PLATFORM_URL'), '/api');
            $hostName = Config::settings('host_name');
            $hostName = str_replace(array("http://","https://","/"), "", $hostName);
            if(!empty($hostName))
            {
                $apiEndpoint = 'https://'. $hostName;
            }

            if($currentStepId == 1) {
                $queryString2 = $queryString.'&convert=yes&sales=yes';
            } else {
                $queryString2 = $queryString.'&convert=yes';
            }

            $url = sprintf(
                '%s/pixel-router/%s/?%s', $apiEndpoint, $gateWaySwitcherId, $queryString2
            );
        }
        
        $response = Http::get($url, array(), array(CURLOPT_CONNECTTIMEOUT => 10));
    }
    
    private static function mapAffiliateKeys($affiliates)
    {
        $mapping = array(
            'nId' => 'nid', 'afId'    => 'afid', 'affId' => 'affid', 'sId' => 'sid', 'aId' => 'aid',
            'clickId' => 'click_id',
        );
        $newAffiliates = array();
        foreach ($affiliates as $key => $value) {
            if (array_key_exists($key, $mapping)) {
                $newAffiliates[$mapping[$key]] = $value;
                continue;
            }
            $newAffiliates[$key] = $value;
        }
        return $newAffiliates;
    }
	
	
}
