<?php
ini_set('display_errors', 1); // Enable error display
ini_set('display_startup_errors', 1); // Show startup errors
error_reporting(E_ALL); // Report all types of errors
echo 1111;die;
require_once 'config_prod.php';
require_once 'bot_check.php';

//require_once 'Base2n.php';
require 'lib/php/include/device-detector/vendor/autoload.php';
require_once 'lib/php/include/amazon/AmazonRefTag.php';

define('HASH_KEY', 'RzhEBqaw9I1hdT9');
define('IV', 'KzhEBbaw9I1hdTcf'); // Initialzation Vector
define('METHOD', 'aes128');	 // Method to be used to encrypt/decrypt
define('BITS_CHAR', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789');
date_default_timezone_set('America/Los_Angeles');

$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";

//check ua
if (is_bot( $ua) ||  empty($ua) || $ua == '' || is_null($ua)) {
    echo "bot";
    exit();
}

$actualamznPid = 0;
$amznRefTagObj = new AmazonRefTag();
$EdmundsBlacklistIps = array('198.46.218.6','23.94.195.220','172.245.246.250','71.4.184.34','172.245.39.136','71.4.186.186','198.46.206.252','172.245.83.155','75.127.6.227','173.211.16.178','172.245.187.250','107.172.124.113','192.3.167.170','23.244.155.11','192.225.171.113','198.46.206.222','45.57.138.107','172.245.123.202','172.245.246.222','192.198.126.161','172.245.206.149','172.98.186.104','23.229.126.89','23.229.60.8','23.88.195.23','192.225.164.145','23.250.29.162','45.72.26.208','45.57.149.93','192.3.123.191','172.245.83.20','192.241.96.246','192.3.230.35','107.152.217.219','172.102.200.78','198.46.168.219','192.186.176.16','198.46.130.145','23.244.211.20','107.152.217.28','23.94.63.21','198.46.172.178','138.128.108.219','192.225.160.13','23.254.15.89','23.229.66.61','172.245.80.173','192.157.215.148','198.46.171.210','138.128.108.186','209.220.97.26','172.245.80.175','172.245.83.116','192.3.123.169','192.3.123.171','23.250.29.221','23.229.60.88','23.244.106.118','198.46.174.133','23.229.44.106','23.94.157.38','45.72.67.210','107.172.74.156','198.46.174.201','23.94.157.217','71.4.184.235','172.245.75.241','23.229.127.109','23.229.60.12','23.94.60.4','198.46.130.203','198.46.171.162','198.46.184.221','172.245.187.154','198.46.174.196','45.72.26.199','198.46.130.230','23.254.43.61','75.127.6.252','192.241.102.43','172.245.66.221','104.227.167.165','104.227.167.217','192.241.102.17','192.241.102.9','198.46.217.206','209.220.97.118','107.152.217.169','172.245.123.205','23.229.117.27','45.57.138.119','138.128.67.208','23.244.106.71','192.186.176.20','209.220.104.152','45.57.188.77','192.198.113.220','192.225.164.253','192.3.122.182','45.72.67.206','172.245.123.206','172.98.187.146','192.3.234.141','198.46.171.228','23.229.127.91','23.94.140.55','23.244.106.132','23.229.127.96','23.229.60.4','192.225.164.209','172.245.83.239','192.241.96.189','23.244.106.70','23.254.43.27','104.227.167.207','172.245.245.200','172.245.245.144','172.245.66.232','192.198.113.177','45.57.188.165','67.106.134.209','104.227.167.228','107.172.124.175','172.245.80.189','198.46.217.142','23.250.56.88','172.245.206.204','192.186.176.7','45.72.26.187','138.128.45.154','23.236.138.105','107.172.124.122','192.3.123.118','198.144.185.11','172.245.206.137','23.94.195.43','192.3.123.107','45.57.224.57','172.245.123.204','45.57.138.59','45.57.172.51','192.186.176.15','23.236.138.196','172.245.66.224','192.3.123.148','23.244.106.139','45.57.165.61','172.245.246.228','45.57.149.110','23.229.127.87','67.90.47.127','172.245.206.212','192.3.214.134','104.144.9.51','162.248.134.232','184.172.234.202','4.30.27.10','157.130.245.6','62.115.32.251','152.179.226.126','75.149.229.162','52.247.234.251','40.112.170.209','40.83.179.173','40.85.151.71','104.42.76.67','216.218.147.202','64.62.158.114','64.62.158.115','216.218.147.201','64.62.158.118','64.62.158.116','64.62.158.117','65.19.141.115','35.224.187.68','35.238.251.71','104.198.174.148','35.193.78.5','35.238.96.76','104.198.154.186','35.188.87.117','104.197.153.23','35.192.225.202','35.188.51.100','34.66.21.126','35.193.85.226','104.197.162.239','34.66.32.111','35.192.72.1','35.222.82.96','35.226.108.147','18.209.214.208','54.80.203.9','100.27.43.207','34.226.201.232','18.209.223.115','34.230.18.84','35.175.121.191','100.26.172.32','54.198.181.128','54.152.120.197','3.83.18.149','100.25.40.136','3.81.91.212','54.175.137.52','3.92.73.134','35.174.60.26','18.232.35.78','54.81.221.193','54.82.175.206','3.87.207.60','18.207.133.68','3.94.129.25','54.156.83.116','34.236.134.194','34.239.176.189','52.204.15.133','35.175.212.104','54.173.106.108','100.25.214.29','100.26.159.135','18.207.187.7','3.91.81.65','54.92.188.246','54.152.163.3','18.208.232.204','18.215.249.121','34.239.166.224','18.232.115.203','100.24.119.80','18.208.149.48','174.129.184.171','54.89.73.197','54.81.42.120','54.196.148.8','3.84.12.151','34.239.176.227','3.87.55.58','34.204.187.9','18.208.126.158','54.196.81.154','100.25.220.100','54.237.157.247','100.25.12.115','18.207.132.151','35.174.62.136','18.232.54.250','34.229.84.199','18.209.228.120','18.206.13.22','54.165.186.223','18.232.179.171','54.165.21.11','34.239.169.97','54.234.232.208','54.197.35.4','18.206.199.150','34.207.57.240','3.81.27.85','18.232.137.134','3.86.85.55','3.94.99.221','18.213.111.208','3.94.55.206','100.25.151.169','18.232.188.116','54.242.163.16','52.0.98.164','35.172.216.66','34.204.200.23','3.80.7.17','35.153.143.126','100.26.3.143','54.173.142.35','3.91.57.229','107.23.97.37','34.229.63.88','35.175.129.128','18.205.192.228','35.172.203.219','52.90.73.72','52.23.198.181','54.92.161.154','18.204.214.8','3.83.244.163','34.228.44.156','100.27.15.83','18.234.252.5','3.91.24.30','100.24.23.224','3.86.249.118','3.94.207.208','34.227.225.113','3.80.8.93','54.227.45.102','34.201.1.222','34.237.138.143','3.87.109.153','35.173.186.31','35.173.203.30','34.238.167.102','18.204.6.86','52.90.109.83','3.93.59.97','54.86.131.179','3.94.210.244','34.231.147.105','3.95.38.119','100.24.118.84','18.208.195.245','34.226.210.149','34.206.53.154','18.215.125.76','54.211.79.103','18.204.37.132','34.201.12.193','18.232.49.197','35.168.2.13','54.173.63.77','54.173.28.215','3.87.145.121','100.26.225.95','3.81.26.59','18.205.96.192','54.92.253.100','34.231.247.153','3.95.133.116','35.172.223.229','100.25.205.136','52.91.146.92','34.204.186.145','54.227.228.239','54.172.55.102','54.82.76.14','18.212.121.211','3.94.132.125','34.229.233.213','18.206.147.79','54.91.136.2','54.198.158.240','35.175.121.7','18.205.96.8','3.84.184.217','3.93.24.121','18.206.248.131','54.85.104.191','34.201.5.228','3.85.63.173','52.54.109.24','18.213.116.211','3.88.223.186','18.233.200.166','3.90.41.105','54.145.34.222','3.92.76.31','18.232.51.142','34.203.225.36','52.90.68.117','3.80.172.33','100.25.43.179','54.167.173.161','54.152.236.242','3.88.195.228','34.237.139.196','54.159.132.4','3.80.181.160','18.212.242.23','54.90.165.181','3.81.74.132','54.164.131.105','75.101.240.31','54.86.50.19','18.207.237.54','34.207.159.195','3.83.107.205','34.228.247.121','54.152.44.48','54.144.111.11','3.90.114.212','54.80.161.46','18.207.181.212','34.204.188.169','34.228.79.112','18.209.158.218','34.227.78.34','52.91.66.48','54.236.30.188','34.239.169.185','3.91.253.11','34.201.11.130','34.205.135.209','3.93.6.68','3.87.245.105','3.83.107.23','3.83.237.234','3.87.89.251','35.175.141.63','206.180.38.20','3.91.153.167','35.173.198.204','3.80.203.200','216.21.37.141','47.5.43.71','35.12.208.196','3.82.150.124','54.226.249.171','34.234.223.81','3.91.56.57','18.214.87.212','52.70.163.152','54.237.121.158','66.74.180.147','54.215.','50.18.','54.241.','184.169.','204.236.','199.30.24.','199.30.25.','66.249.90.');

$uniqueRequestId = isset($_GET['req_id']) ? $_GET['req_id'] : "";
$req_aff = isset($_GET['req_aff']) ? $_GET['req_aff'] : "";

$ipLimitRedis = new Redis();
$ipLimitRedis->pconnect($config['iplimit_server'], $config['iplimit_port']);

$redisLogwrite = new Redis();
$rw = $redisLogwrite->pconnect($config['redis_ip_for_logging'], $config['redis_port_for_logging']);
//$rw = $redisLogwrite->pconnect('192.168.'.'30.106', 6378);

if(!$rw){
    click_drop_log(__FILE__,__LINE__,"redis Failure",$config['redis_ip_for_logging']."_".$config['redis_port_for_logging']);
}
if(!empty($uniqueRequestId)){
    //capture Cad link
    $link = (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']  === 'https' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    click_drop_log(__FILE__,__LINE__,"step 1 : cad recieve ",$link);
}
if (!isset($_COOKIE['cad'])) {
	$seconds_since_midnight = (date("H")*60*60) + (date("i")*60)  + (date("s"));
	$expire = 60*60*24- $seconds_since_midnight + 60 ; // Seconds until midnight
	preg_match('/[^.]+\.[^.]+$/', $_SERVER['HTTP_HOST'], $match);
	$cookie_value = "cad_".time();
	setcookie('cad', $cookie_value, time()+$expire, '/', ".$match[0]");
	$new_visit = 1;
} else {
	$new_visit = 0;
}

/**
 * Get the first non-empty
 * ion from alternate parameter names.
 */
function getFirstClickValue($source, $keys, $defaultValue)
{
    foreach ($keys as $key) {
        if (
            isset($source[$key]) &&
            trim((string) $source[$key]) !== ''
        ) {
            return trim((string) $source[$key]);
        }
    }

    return $defaultValue;
}

function maxmindIp2location($ip) {
    global  $config;
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $ip =  ip2long_v6($ip);
    }else{
        $ip = ip2long($ip);
    }
    $redis = new Redis();
    try {
        $redis->pconnect($config['maxmind_redis_ip'],$config['maxmind_redis_port']);
        $ip_data = $redis->zRangeByScore('maxmindip', $ip, 340282366920938463463374607431768211456, array('limit' => array(0, 1)));
    } catch (RedisException $e) {
        return array();
    }
    $ip_data = explode(':', $ip_data[0]);
    return array(
        'country2'   => $ip_data[1],
        'country3'   => $ip_data[2],
        'city'       => $ip_data[3],
        'state'      => $ip_data[4],
        'postal'     => $ip_data[5],
        'metro_code' => $ip_data[6]
    );
}

function cleanAmazonLink($url) {
    $url = trim($url);

    // Step 1: If this is an amzn-adsystem redirect, extract the destination Amazon link
    if (preg_match('/[?&]dest=([^&]+)/i', $url, $matches)) {
        $decoded = urldecode($matches[1]);
        // Recursively clean the extracted Amazon URL
        return cleanAmazonLink($decoded);
    }

    // Generic domain pattern for all Amazon regions
    $domainPattern = '(?:www\.)?amazon\.(?:com|co\.uk|ca|de|in|fr|it|es|com\.au|co\.jp)';

    // Case 1: Search URLs → keep only https://.../s?k=...
    if (preg_match('/^(https?:\/\/' . $domainPattern . '\/s\?k=[^&?]*)/i', $url, $matches)) {
        return $matches[1];
    }

    // Case 2: Product URLs (/dp/... or /gp/product/...) → strip ? and trailing /
    if (preg_match('/^(https?:\/\/' . $domainPattern . '\/.*?\/(?:dp|gp\/product)\/[A-Za-z0-9]+)/i', $url, $matches)) {
        $baseUrl = $matches[1];
        // Parse query string
        $parsed = parse_url($url);
        if (!empty($parsed['query'])) {
            parse_str($parsed['query'], $queryParams);
            // Keep only 'psc' if it exists
            if (isset($queryParams['psc'])) {
                return $baseUrl . '?psc=' . $queryParams['psc'];
            }
        }
        return $baseUrl;
    }

    // Case 3: Other Amazon URLs → remove anything after ? and trailing /
    $url = preg_replace('/\?.*/', '', $url);
    $url = rtrim($url, '/');

    return $url;
}


function getRandomShopReftags($amazonPubid,$pickShopRefTag){
    global $config,$actualamznPid,$country;
    if($pickShopRefTag){
        $pid = getShopPid($amazonPubid);
        $key = "amzn_ref_tags_shop";
    } else {
        $pid = getPid($amazonPubid);
        if($country == "GBR"){
            $key = "amzn_ref_tags_uk";
        }else{
            $key = "amzn_ref_tags_us";
        }
    }
    $actualamznPid = $pid; 
    $redis = new Redis();
    $redis->pconnect($config['redis_ip_for_campaign_info'], $config['redis_port_for_campaign_info']);
    $reftags = $redis->get($key);
    $reftags = json_decode($reftags,true);
    if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
        var_dump($reftags);
    }
    if(!empty($reftags)){
        $res = $reftags[array_rand($reftags)];
    }else{
        $actualamznPid = 0; 

        $res['reftag'] = ($country == "GBR") ? "pd_sl_ac250b59845403ed7b80d988ab7ced5d_b" : "pd_sl_7f9289ec360f08e24e5af915799e817f_b";
        $res['cat_id'] = $res['category'] = 0;
    }
    return $res;
}

function extractAsin($url) {
    // Safely parse URL parts
    $parts = parse_url($url);
    $path = isset($parts['path']) ? $parts['path'] : '';
    $query = isset($parts['query']) ? $parts['query'] : '';

    // Common ASIN regex patterns
    $patterns = [
        '/\/dp\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/\/gp\/product\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/\/gp\/aw\/d\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/\/product\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/\/gp\/offer-listing\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/\/exec\/obidos\/tg\/detail\/-\/([A-Z0-9]{10})(?:[\/?]|$)/i',
        '/[?&](?:asin|ASIN)=([A-Z0-9]{10})/i',
        '/[?&]ASIN\.\d+=([A-Z0-9]{10})/i',
    ];

    // Check path for ASIN
    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $path, $matches)) {
            return strtoupper($matches[1]);
        }
    }

    // Check query string (?asin=B07HBQY2Q7)
    parse_str($query, $params);
    if (isset($params['asin']) && preg_match('/^[A-Z0-9]{10}$/i', $params['asin'])) {
        return strtoupper($params['asin']);
    }

    // No ASIN found
    return null;
}
function getXMLAsinReftag($asin,$amazonPubid){
    global $actualamznPid,$amznRefTagObj,$rediswrite;
    if(empty($amazonPubid)){
        $amazonPubid = 1001;
    }
    $actualamznPid = $amazonPubid; 
    $index = "amazon_shop_reftag";
    $response = $amznRefTagObj->getShopReftag($index,$asin);
    $result = empty($response) ? null : json_decode($response, true);
    if(isset($result['status']) && $result['status'] == true  && isset($result['reftag']) && !empty($result['reftag'])){
        return $result;
    }else{
        //error occur captur error need to work
        $outDataObj = new stdClass();
        $outDataObj->date = date("Y-m-d");
        $outDataObj->response = $response;
        $rediswrite->rpush("opensearch_fails", json_encode($outDataObj));
        return false;
    }
}

function getAsinReftag($asin,$affiliateID){
    global $actualamznPid,$amznRefTagObj,$rediswrite;
    $amazonPubid = getShopPid($affiliateID);
    if(empty($amazonPubid)){
        $amazonPubid = 1001;
    }
    $actualamznPid = $amazonPubid; 
    $index = "amazon_shop_reftag";
    $response = $amznRefTagObj->getShopReftag($index,$asin);
    $result = empty($response) ? null : json_decode($response, true);
    if(isset($result['status']) && $result['status'] == true  && isset($result['reftag']) && !empty($result['reftag'])){
        return $result;
    }else{
        //error occur captur error need to work
        $outDataObj = new stdClass();
        $outDataObj->date = date("Y-m-d");
        $outDataObj->response = $response;
        $rediswrite->rpush("opensearch_fails", json_encode($outDataObj));
        return false;
    }
}

function getOpenSearchRandomKeyword($AffiliateID,$device,$legacykeyword){
    global $actualamznPid,$amznRefTagObj,$country,$rediswrite;
    //get keyword and ad copy from openSearch
    //Get pid number
    $pid = getPid($AffiliateID);
    //Get terms
    $actualamznPid = $pid; 

    if($country == "GBR"){
        $index = "amazon_uk_kw";
    }else{
        $index = "amazon_us_kw";
    }
    //$response = $amznRefTagObj->getSearchKeyword($index,$device);
    //Get a random keyword from legacy lists and try to get reftag. The func tries and defaults to random one if none found
    $response = $amznRefTagObj->getLegacySearchKeyword($index,$device,$legacykeyword);
    $decoded = json_decode($response, true);
    if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
        var_dump("Inside getOpenSearchRandomKeyword function");
        var_dump($AffiliateID);
        var_dump($pid,$index);
        var_dump($response);
        var_dump("DONE getOpenSearchRandomKeyword function");
        //exit;
    }
    if(isset($decoded['status']) && $decoded['status'] == true){
        return array($decoded['refTag'], $decoded['catId'], $decoded['category']);
    }else{
        $outDataObj = new stdClass();
        $outDataObj->date = date("Y-m-d");
        $outDataObj->response =$response;
        $rediswrite->rpush("opensearch_fails", json_encode($outDataObj));
        return array(false,false,false);
    }
}

function getShopPid($aid){
    global $config,$country;
    if($country == "GBR"){
        $country_code = "uk";
    }else{
        $country_code = "us";
    }
    $redis = new Redis();
    $redis->pconnect($config['redis_ip_for_campaign_info'], $config['redis_port_for_campaign_info']);

    $placement_ids = $redis->hGet('amzn_shop_'.$country_code, $aid);

    if (!$placement_ids) {
        $placement_ids = $redis->hGet('amzn_shop_'.$country_code, $aid);
    }

    if ($placement_ids) {
        $placement_ids_exploded = explode(",",$placement_ids);
        $placement_id_rand_key =  array_rand($placement_ids_exploded);
        $placement_id = $placement_ids_exploded[$placement_id_rand_key];
    }

    return (!empty($placement_id)) ? $placement_id : 1001;
}

function getPid($aid){
    global $config,$country;
    if($country == "GBR"){
        $country_code = "uk";
    }else{
        $country_code = "us";
    }
    $redis = new Redis();
    $redis->pconnect($config['redis_ip_for_campaign_info'], $config['redis_port_for_campaign_info']);

    // Check for placement_id in Redis
    $placement_ids = $redis->hGet('amzn_text_'.$country_code, $aid);

    if (!$placement_ids) {{}
        $placement_ids = $redis->hGet('amzn_shop_'.$country_code, $aid);
    }
    
    if ($placement_ids) {
        $placement_ids_exploded = explode(",",$placement_ids);
        $placement_id_rand_key =  array_rand($placement_ids_exploded);
        $placement_id = $placement_ids_exploded[$placement_id_rand_key];
    }

    return (!empty($placement_id)) ? $placement_id : 1005;

}

function generateConsistentNumericId($inputString) {
    // Calculate the CRC32 hash of the input string
    $hash = crc32($inputString);

    // Transform the hash into a 9-digit number
    $numericId = abs($hash % 1000000000);

    return $numericId;
}
function encrypt_str($str) 
{
	$compressed = $str;
	$encrypted = crypto($compressed);
	$encoded = base64_encode($encrypted);
	$cleaned = strtr($encoded, '+/=', '-_,');
	return $cleaned;
}

function decrypt_str($cleaned) 
{
	$cleaned = strtr($cleaned, '-_,', '+/=');
	$decoded = base64_decode($cleaned);
	$unencrypted = crypto($decoded);
	$str = $unencrypted;
	return $str;
}

function crypto($str) 
{
	$ky = str_replace(chr(32), '', HASH_KEY);
	if (strlen($ky) < 8) exit('key error');
	$kl = strlen($ky) < 32 ? strlen($ky) : 32;
	$k = array();
	for ($i = 0; $i < $kl; ++$i) 
	{
		$k[$i] = ord($ky[$i]);
	}
	$j = 0;
	for ($i = 0; $i < strlen($str); ++$i) 
	{
		$e = ord($str[$i]);
        $str[$i] = ($e & 0xE0) ? chr($e ^ $k[$j]) : chr($e);
		++$j;
		$j = $j == $kl ? 0 : $j;
	}
	return $str;
}

function log_clicks($status = 0, $reason = '') {
	global $advid, $unique_id,$campaign_id, $affiliate_set_click_id, $aff_clickid, $affiliate_set_ref_id,
           $affiliate_set_sub_id, $sovrn_keyword,$static_link,$given_aff_id,$given_feed_id,$aff_sub_id,$ssid,
           $given_subid,$decrypt_mc,$given_search_ref,$given_xmlfeed,$rediswrite, $subid, $aff_name, $advid,
           $search_ip, $redirect, $clickerua, $search_ua, $clickid, $sub_subid, $cpc,$search,$aff_xml_redis_info,
           $affiliate_name,$testingClick,$oosSerpLink,$searchRef,$errorForClickTable,$sovrn_test;
	if (1) {

        $redishashKey = "affiliate_names";
        $affiliate = $aff_xml_redis_info->hGet($redishashKey,$given_aff_id);
        $affiliate = empty($affiliate) ? $affiliate_name : $affiliate;
        $affiliate = empty($affiliate) ? "NONE0000" : $affiliate;
		$sub_subid = (isset($sub_subid) && $sub_subid != '') ? trim($sub_subid) : '';
		if ( empty($sub_subid) && !empty($ssid) ) {
                    $sub_subid = $ssid;
                }
		$aff_sub_id = empty($aff_sub_id)? $ssid : $aff_sub_id;
		$search = (trim($search) == '') ? '' : urldecode($search);
		$server = (isset($_SERVER['SERVER_ADDR'])) ? sprintf('%u', ip2long($_SERVER['SERVER_ADDR'])) : '';

        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']!="") {
			$click_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$click_ip = 0;
		}

        $click_ips = explode(',',$click_ip);
        if (!empty($click_ips)) {
            $click_ip = trim($click_ips[0]);
        }

        if ($_GET['debug_ip']) {
            var_dump($search_ip);
            var_dump($click_ip);
            if(filter_var($click_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                var_dump("Step 1");
                var_dump(ip2long_v6($search_ip));
                var_dump(ip2long_v6($click_ip));
            } else {
                var_dump("Step 2");
                var_dump(ip2long($search_ip));
                var_dump(ip2long($click_ip));
            }
        }

        if(filter_var($search_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            //$search_ip = sprintf('%u', ip2long_v6($search_ip));
            $search_ip = ip2long_v6($search_ip);
        }else{
            $search_ip = sprintf('%u', ip2long($search_ip));
        }

        $matcher_click_ip = $click_ip;
        $matcher_click_ua = $clickerua;
        
        if(filter_var($click_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            //$click_ip = sprintf('%u', ip2long_v6($click_ip));
            $click_ip = ip2long_v6($click_ip);
        }else{
            $click_ip = sprintf('%u', ip2long($click_ip));
        }

        if ( $static_link ) {
            $search_ip = $click_ip;
        }

		$request_uri = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '';
		$bucket_id = 0;
		$script_time = 0;
	
		$search = addslashes($search);
		$subid = addslashes($subid);
		$request_uri = addslashes($request_uri);
        $redirecturl = addslashes($redirect);
        
		$oldref = '';
        $search_ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']:'';
		$referrer = '';
		$clickerua = addslashes($clickerua);
		$searchua = addslashes($search_ua);
        if ( $static_link ) {
            $searchua = $clickerua;
        }
		$reason = addslashes($reason);
        $aff_rev_share = 0.6;
        if(!empty($affiliate)){
            $mkey = "xml_aff_info_".md5(strtolower($affiliate));
            $value = $aff_xml_redis_info->get($mkey);
            $affInfo = json_decode($value, true);
            if(isset($affInfo['rev_share']) && $affInfo['rev_share'] > 0){
                $aff_rev_share = $affInfo['rev_share'];
            }
        }
		$feed_rev_share = 1;
		$cookie = '';
		$feedName = 'advertisers';
		switch($advid){
            case 15273:
                $feedName= 'Sireesha';
            case 14436:
                $feedName= 'Meredith';
                break;
            case 15421:
                $feedName= 'Kelkoo';
                break;
            case 15127:
                $feedName= 'Steelstraw';
                break;
            case 15361:
                $feedName= 'Keen';
                break;
            case 7831:
                $feedName= 'Openings';
                break;
            case 15390:
                $feedName= 'DiamondCBD';
                break;
        }
		$xmlfeed = $feedName;
		
		if ($status != 0) {
			$reason = trim($reason) == '' ? 'No Reason' : $reason;
		}

		$table = 'click_'.date('Ymd');
		$calculated_searchtime = 1;


		$store_redirecturl = (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? "https" : "http") . "://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$linkid = time();

		$referrer = $redirecturl;

        // if ( $search_ref == '') {
        //     // plug in the incoming request and UA appended
        //     $search_ref = (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? "https" : "http") . "://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].' - UA - '.$_SERVER['HTTP_USER_AGENT'];
        // }
        
        if (!is_null($given_xmlfeed)) {

            $xmlfeed = $given_xmlfeed;
        }
        if (!is_null($given_search_ref)) {

            $search_ref = $given_search_ref;
        }
        if (!is_null($given_subid)) {

            $sub_subid = $given_subid;
        }
        $search_ref = (isset($searchRef) && !empty($searchRef)) ? $searchRef : $search_ref;
        $referrer = (isset($searchRef) && !empty($searchRef)) ? $searchRef : $search_ref;
        
        // Set referrer from given_search_ref if provided
		if (isset($given_search_ref) && !empty($given_search_ref)) {
			$referrer = $given_search_ref;
		}

        $oldref = isset($decrypt_mc[7]) ? $decrypt_mc[7] : '';

        if( $advid == 20378 || $advid == 21610){
            global $categoryName;
            $oldref = $redirect."&cat=".urlencode($categoryName);
        }

        if ( $sovrn_keyword ) {
            $search = $sovrn_keyword;
        }
        if(empty($cpc) || empty($reason)){
            if(in_array($errorForClickTable, ["repeated click", "older click"])){
                $status = 1; //capture all as dropped
            }
            $reason = $errorForClickTable;
        }

		$data = array(  $linkid, $clickid, $status,
                        $script_time, $affiliate, $sub_subid, $xmlfeed,
                        $cpc, $aff_rev_share, $feed_rev_share, $search,
                        $server, $search_ip, $click_ip, '',
                        $store_redirecturl, $oldref, $search_ref, $referrer,
                        $clickerua, $searchua, $cookie, $calculated_searchtime,
                        $reason, 1,
                        $advid,$campaign_id, $affiliate_set_click_id, $aff_clickid, $affiliate_set_ref_id, $affiliate_set_sub_id,
                        $unique_id,$given_aff_id,$sovrn_test);


        if ($_GET['debug_ip']) {
            var_dump("redis searchip ".$search_ip);
            var_dump("redis clickip ".$click_ip);
            die;

        }

        if(isset($_GET['debug']) && $_GET['debug']=="mtsiri" ){
            var_dump($data);
            exit;
        }


        $table1 = 'click_summary_'.date('Ym');
        $data1 = array($given_aff_id, intval($given_feed_id), $status);

        if(REDIS_WRITE)
		{
			/********* Redis Write ********/
            $ret = true;
            if(!$oosSerpLink){
                if(isset($_GET['debug'])) var_dump(json_encode($data));
                $ret = $rediswrite->rpush($table, json_encode($data));
            }
			if(!$ret)
			{
				click_drop_log(__FILE__,__LINE__,"redis Failure","192.168.17.102_6379");
				if(isset($_GET['debug']))
					echo "ERROR: The click was not logged in redis in the log_click function.<br>";
			}else{
				if(isset($_GET['debug']))
					print_r($data);
			}
            $ret = true;
            if(!$oosSerpLink){
                $ret = $rediswrite->rpush($table1, json_encode($data1));
            }

            if(!$ret)
            {
                click_drop_log(__FILE__,__LINE__,"redis Failure","192.168.17.102_6379");
                if(isset($_GET['debug']))
                    echo "ERROR: The click was not logged in redis in the log_click function.<br>";
            }else{
                if(isset($_GET['debug']))
                    print_r($data);
            }
		}
        //make server side curl call to impression match
        //callImpressionMatcher($unique_id,$given_aff_id,$campaign_id,$affiliate_set_click_id,$affiliate_set_sub_id,$search,$matcher_click_ip,urldecode($matcher_click_ua));
	}
}

function callImpressionMatcher($unique_id,$given_aff_id,$campaign_id,$affiliate_set_click_id,$affiliate_set_sub_id,$search,$click_ip,$clickerua){

    $matcherUrl =
        'https://click.validclick.net/validclick-monitor-matcher.php';

    $postData = array(
        'unique_id'  => $unique_id,
        'aff'        => $given_aff_id,
        'cmp'        => $campaign_id,
        'subid'      => $affiliate_set_sub_id,
        'clickid'    => $affiliate_set_click_id,
        'q'          => $search,
        'click_time' => microtime(true),
        'visitor_ip' => $click_ip,
        'visitor_ua' => $clickerua,
        //'debug'      => '1'
    );
    if ( isset($_GET['debug']) && $_GET['debug'] === 'monitor' ) {
        $postData["debug"] = 1;
    }

    $ch = curl_init();

    curl_setopt_array(
        $ch,
        array(
            CURLOPT_URL => $matcherUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2
        )
    );

    /*$response = curl_exec($ch);

    $curlErrno = curl_errno($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo(
        $ch,
        CURLINFO_HTTP_CODE
    );

    $effectiveUrl = curl_getinfo(
        $ch,
        CURLINFO_EFFECTIVE_URL
    );

    curl_close($ch);*/

    if (
        isset($_GET['debug']) &&
        $_GET['debug'] === 'monitor'
    ) {
        echo '<pre>';

        echo "MATCHER URL:\n";
        echo $matcherUrl . "\n\n";

        echo "POST DATA:\n";
        print_r($postData);

        /*echo "\nCURL ERRNO:\n";
        var_dump($curlErrno);

        echo "\nCURL ERROR:\n";
        var_dump($curlError);

        echo "\nHTTP CODE:\n";
        var_dump($httpCode);

        echo "\nEFFECTIVE URL:\n";
        var_dump($effectiveUrl);

        echo "\nRESPONSE:\n";
        var_dump($response);*/

        echo '</pre>';
        exit;
    }
}

function click_drop_log($file,$line,$reason,$redirect_url) {
    global $config, $uniqueRequestId , $redisLogwrite,$req_aff;
    if(empty($uniqueRequestId))
        return true;
    $clickDropObj = new stdClass();
    $clickDropObj->date = date('Y-m-d');
    $clickDropObj->time = time();
    $clickDropObj->req_id = $uniqueRequestId;
    $clickDropObj->aff = $req_aff;
    $clickDropObj->file = $file;
    $clickDropObj->line = $line;
    $clickDropObj->reason = $reason;
    $clickDropObj->redirecturl = $redirect_url;
    $redisLogwrite->rpush('click_drop'. date("Ymd"), json_encode($clickDropObj));
}

function redirect_home($err, $reason, $redirect_url = null) {
	if(!$redirect_url)
		$redirect_url = "http://localpages.com?e=fqp";
	
	log_clicks($err, $reason);
	header("Location: $redirect_url");
    //ob_end_flush();
	exit();
}

function isMobileDevice(){
    $aMobileUA = array(
        '/iphone/i' => 'iPhone',
        '/ipod/i' => 'iPod',
        '/ipad/i' => 'iPad',
        '/android/i' => 'Android',
        '/blackberry/i' => 'BlackBerry',
        '/webos/i' => 'Mobile',
        '/windows phone/i' => 'Windows Phone',
        // Tablets
        '/tablet/i' => 'Tablet',
        '/kindle/i' => 'Kindle',
        '/silk/i' => 'Kindle Fire',
        '/playbook/i' => 'BlackBerry PlayBook'
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
        if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
    }
    //Otherwise return false..
    return false;
}

function get_ias_prebid_token(){
	$client_id = "332187";
	$client_secret = "YvrAqUAibsSpsstuxrNN";
	$url = "https://auth.adsafeprotected.com/uaa/oauth/token";
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout after 30 seconds
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($ch, CURLOPT_USERPWD, "$client_id:$client_secret");
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
	$result = curl_exec($ch);
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	curl_close ($ch);
	
	if(!$result || $status_code != 200){
		return false;
	} else {
		return $result;
	}
}

function get_ias_prebid_segments($access_token, $ip, $referrer){
	$referrer = urlencode($referrer);
	
	$url = "http://api.adsafeprotected.com/db2/client/332187/seg?adsafe_url=".$referrer."&adsafe_ip=".$ip;
	$headers = [
	    "Authorization: bearer ".$access_token
	];
	
	if (!empty($_GET['debug'])){
		echo "URL: ".$url."<br>";
	}
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	
	$result = curl_exec($ch);
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	curl_close ($ch);
	
	if(!$result || $status_code != 200){
		return false;
	} else {
		return $result;
	}
}

function get_cleartrust_score($ip, $referrer,$clickid,$cleartrust_id,$cleartrust_sub_id,$ua) {

    $referrer = urlencode($referrer);

    $url = "https://api.botman.ninja/ic3.php?m=AF&src=s2s&b=20679&s=20679&cid=$clickid".
        "&ip=$ip&s1=$cleartrust_id&s2=$cleartrust_sub_id&s3=$referrer&s6=".urlencode($ua);

    if (!empty($_GET['debug'])){
        echo "URL: ".$url."<br>";

    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
    curl_close ($ch);

    if (!empty($_GET['debug'])){
        echo "status code is: ".$status_code."<br>";
    }

    if(!$result || $status_code != 200){

        return false;
    } else {

        return $result;
    }

}

function ip2long_v6($ip) {
    $ip_n = inet_pton($ip);
    $bin = '';
    for ($bit = strlen($ip_n) - 1; $bit >= 0; $bit--) {
        $bin = sprintf('%08b', ord($ip_n[$bit])) . $bin;
    }

    if (function_exists('gmp_init')) {
        return gmp_strval(gmp_init($bin, 2), 10);
    } elseif (function_exists('bcadd')) {
        $dec = '0';
        for ($i = 0; $i < strlen($bin); $i++) {
            $dec = bcmul($dec, '2', 0);
            $dec = bcadd($dec, $bin[$i], 0);
        }
        return $dec;
    } else {
        trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
    }
}

function long2ip_v6($dec) {
    if (function_exists('gmp_init')) {
        $bin = gmp_strval(gmp_init($dec, 10), 2);
    } elseif (function_exists('bcadd')) {
        $bin = '';
        do {
            $bin = bcmod($dec, '2') . $bin;
            $dec = bcdiv($dec, '2', 0);
        } while (bccomp($dec, '0'));
    } else {
        trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
    }

    $bin = str_pad($bin, 128, '0', STR_PAD_LEFT);
    $ip = array();
    for ($bit = 0; $bit <= 7; $bit++) {
        $bin_part = substr($bin, $bit * 16, 16);
        $ip[] = dechex(bindec($bin_part));
    }
    $ip = implode(':', $ip);
    return inet_ntop(inet_pton($ip));
}

function validateSerpLink($redirectUrl) {
    $flag = false;
    $urlParts = parse_url($redirectUrl);
    if(isset($urlParts['query']))
        parse_str($urlParts['query'],$queryStr);
    
    if(isset($urlParts['host']) &&  strpos($urlParts['host'],"socialsearch") !== false && isset($queryStr['subid']) && !empty($queryStr['subid'])){
        $flag = true;
    }
    return $flag;
}

$clicktraceid = isset($_GET['clicktraceid']) ? $_GET['clicktraceid'] : false;
if(!empty($clicktraceid)){
    $redisTraceWrite = new Redis();
    $redisTraceWrite->pconnect($config['r2_redis_ip_read'], $config['r2_redis_ip_read_port']);
    $obj = new stdClass();
    $obj->requestId = $clicktraceid;
    $obj->date = date('Y-m-d');
    $obj->cad_in = (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? "https" : "http") . "://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $redisTraceWrite->rpush('click_request_trace', json_encode($obj));
}

$clickIP = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : false;
$testingClick = false;
$testAff = isset($_GET['affiliate']) ? trim($_GET['affiliate']) : '';
$testAffCouponCabin = ( $testAff == strtolower('couponcabin')) ? true : false;
if($testAffCouponCabin && !empty($clickIP) && in_array($clickIP,$config['testing_ips'])){
    $testingClick = true;
}

$cakeid = isset($_GET['cakeid']) ? trim($_GET['cakeid']) : '';
$caketraffic = isset($_GET['caketraffic']) ? trim($_GET['caketraffic']) : null;
$oos_serp_aff = isset($_GET['oos_serp_aff']) ? trim($_GET['oos_serp_aff']) : 0;
$searchRef = isset($_GET['searchRef']) ? trim($_GET['searchRef']) : "";


/************* Connect to redis for writing *****************/
$redis_array = $config['redis_ip_for_ias'];
shuffle($redis_array);
$rediswrite = new Redis();
$rw = $rediswrite->pconnect($redis_array[0], $config['redis_port_for_ias']);
//$rw = $rediswrite->pconnect('192.168.'.'30.106', 6378);

if(!$rw)
{
	// Try backup server
	$backup_redis_array = $config['redis_proxy_ip_for_ias'];
	shuffle($backup_redis_array);
	$rediswrite = new Redis();
	$rw = $rediswrite->pconnect($backup_redis_array[0], $config['redis_proxy_port_for_ias']);
    if(!$rw)
	{
		click_drop_log(__FILE__,__LINE__,"redis Failure",$backup_redis_array[0]."_6379");
		define('REDIS_WRITE', false);
	}
	else
	{
		define('REDIS_WRITE', true);
	}

}
else
{
	define('REDIS_WRITE', true);
}
/************************************************************/

$mc = isset($_GET['mc']) ? $_GET['mc'] : "";

//get campaign id and other info first
if(isset($_GET['srt_hash'])){
    $creativeRedis = new Redis();
    $creativeRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $decrypt_mc = array();
    $encrpt_array = explode("::",decrypt_str($_GET['srt_hash']));//$encrpt_array = [adv_id,cmp_id,creative_id]
    $advKeyword = $advKeywordRedirectUrl = false;
    if(in_array($encrpt_array[0],array(16115,16652,21582,21616))){
        //get redirect url 
        $redisKeywordDestUrlHashKey = "cmp_keywords_dest_urls_".$encrpt_array[1];
        if($creativeRedis->exists($redisKeywordDestUrlHashKey)){
            $urls = $creativeRedis->hgetAll($redisKeywordDestUrlHashKey);
            $advKeyword = array_rand($urls);
            $advKeywordRedirectUrl = $urls[$advKeyword];
        }
    }
    $decrypt_mc[0] = time() . rand(1000000, 9999999) . $encrpt_array[1];//click id
    $decrypt_mc[1] = ( isset($_GET['keyword']) && !empty($_GET['keyword']) ) ? trim($_GET['keyword']) : (($advKeyword) ? $advKeyword : "dynamic" );//keyword of static link
    $decrypt_mc[2] = "dynamic";//affiliate for static link
    $decrypt_mc[3] = $encrpt_array[0]; //adv_id
    $decrypt_mc[4] = $encrpt_array[1];//cmp id
    $decrypt_mc[5] = $encrpt_array[2];//creative id
    $decrypt_mc[6] = 0;//bid
    $decrypt_mc[7] = ($advKeywordRedirectUrl) ? $advKeywordRedirectUrl : $creativeRedis->hGet('all_creatives',$encrpt_array[2]);//creative url
    $decrypt_mc[8] = time()+ 3600;//timestamp
    $decrypt_mc[9] = "";//host
    $decrypt_mc[10] = "";//IP
    $decrypt_mc[11] = "";//UA
    $decrypt_mc[12] = 0;
    $decrypt_mc[13] = "CPC";//type
    $decrypt_mc[14] = 0;
    $decrypt_mc[15] = 1;
    $decrypt_mc[16] = "";//sub id
    $decrypt_mc[17] = 1;//static link
}
else{
    $decrypt_mc = explode("::",decrypt_str($mc));
}
//Validate with name
$campaign_info_redis = new Redis();
$campaign_info_redis->pconnect($config['redis_ip_for_campaign_info'], $config['redis_port_for_campaign_info']);
$incomingCampaignid = isset($decrypt_mc[4]) ? $decrypt_mc[4] : false;

$setAid = true;
foreach (['given_aff_id', 'given_affiliate_id', 'aid'] as $key) {
    if (isset($_GET[$key]) && !empty(trim($_GET[$key]))) {
        $setAid = false;
        break;
    }
}

if(!empty($incomingCampaignid) && $setAid){
    $campaignName =$campaign_info_redis->hGet('t_campaign_'.$incomingCampaignid, 'name');
    $decidedAffid = false;
    // Ensure more-specific names are checked first.
    $namewiseAffiliates = $config['namewise_affiliates'];
    uksort($namewiseAffiliates, function ($a, $b) {
        return strlen($b) - strlen($a);
    });

    $matchedPrefix = null;

    foreach ($namewiseAffiliates as $prefix => $typeWiseAid) {
        if (strpos(strtolower($campaignName),strtolower($prefix)) !== false) {
            $_GET['aid'] = $typeWiseAid;
            $matchedPrefix = $prefix;
            break;
        }
    }

    if (isset($_GET['debug'])) {
        if ($matchedPrefix !== null) {
            var_dump('Affiliate aid changed to ' . $_GET['aid'] . ' using campaign-name rule: ' . $matchedPrefix);
        } else {
            var_dump('No affiliate rule matched campaign: ' . $campaignName);
        }
    }
}


$country = isset($_GET['country']) ? trim($_GET['country']) : "USA";
$errorForClickTable = "";
$category_id = isset($_GET['cat']) ? trim($_GET['cat']) : -1;
$sovrn_keyword = isset($_GET['sovrn_keyword']) ? trim($_GET['sovrn_keyword']) : null;
$affiliate_name = isset($_GET['affiliate']) ? trim($_GET['affiliate']) : '';
$affiliate_set_ref_id = isset($_GET['affiliate_set_ref_id']) ? trim($_GET['affiliate_set_ref_id']) : '';
$affiliate_set_click_id = isset($_GET['affiliate_set_click_id']) ? trim($_GET['affiliate_set_click_id']) : '';
$affiliate_set_sub_id = isset($_GET['affiliate_set_sub_id']) ? trim($_GET['affiliate_set_sub_id']) : (isset($_GET['subid']) ? trim($_GET['subid']) : '');
$given_xmlfeed  = isset($_GET['given_xmlfeed']) ? trim($_GET['given_xmlfeed']) : null;
$given_search_ref  = isset($_GET['given_search_ref']) ? trim($_GET['given_search_ref']) : null;
if(empty($affiliate_set_ref_id)){
    $affiliate_set_ref_id = $given_search_ref;
}
$given_subid  = isset($_GET['given_subid']) ? trim($_GET['given_subid']) : null;
if(isset($_GET['aid'])){
    if (trim($_GET['aid']) == 13421) {
        $_GET['aid'] = 118037;
    }
    $given_aff_id  =  trim($_GET['aid']);
}elseif(isset($_GET['given_aff_id']) ) {
    $given_aff_id  =  trim($_GET['given_aff_id']);
}elseif(isset($_GET['given_affiliate_id']) ) {
    $given_aff_id  =  trim($_GET['given_affiliate_id']);
}else{
    $given_aff_id  =  null;
}
$given_feed_id  = isset($_GET['given_feed_id']) ? trim($_GET['given_feed_id']) : null;
$aff_sub_id = isset($_GET['subid']) ? trim($_GET['subid']) : '';
$search_keyword = isset($_GET['search']) ? trim($_GET['search']) : '';
$aff_keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : $search_keyword;
$quicklaunch = isset($_GET['quicklaunch']) ? trim($_GET['quicklaunch']) : 0;
$oos = isset($_GET['oos']) ? trim($_GET['oos']) : '';
$product_type = isset($_GET['product_type']) ? trim($_GET['product_type']) : '';
$product_sub_id = isset($_GET['product_sub_id']) ? trim($_GET['product_sub_id']) : '';
$aff_clickid = (isset($_GET['aff_clickid']) && trim($_GET['aff_clickid']) !== '')
    ? trim($_GET['aff_clickid'])
    : $affiliate_set_click_id;
$rokt_accountid = isset($_GET['accountid']) ? trim($_GET['accountid']) : '';
$custom = isset($_GET['custom']) ? trim($_GET['custom']) : ''; // Custom parameter to be passed to pixel
$rtbRedirect = isset($_GET['r']) ? trim(urldecode($_GET['r'])) : null;
$connexityBing = isset($_GET['connexityBing']) ? $_GET['connexityBing'] : 0;
$trillion_sid = isset($_GET['sid']) ? trim($_GET['sid']) : ''; // Trillion Sid parameter to be passed to pixel
$fallbackUrl = isset($_GET['fallback']) ? trim($_GET['fallback']) : null;
$sovrn_test = isset($_GET['sovrn_test']) ? trim($_GET['sovrn_test']) : 0;

if(!empty($oos_serp_aff)){
    $given_aff_id = $oos_serp_aff;
}

//if it's a testing aff  click then don't capture in CPC and click table
$testingAff = array(126216); // fr amazon testing rateit,acconna and main affiliate for search n agency
if(in_array($given_aff_id,$testingAff)){
    $testingClick = true;
}

require_once('includes/mobile_device_detect.php');
if(mobile_device_detect(true,true,true,true,true,true,true,false,false)){
    $is_mobile_browser=1;
    $device = 'mobile';
    $ifmobile = true;
    $ifnotmobile = false;
} else{
    $is_mobile_browser=0;
    $device = 'desktop';
    $ifmobile = false;
    $ifnotmobile = true;
}

$couponsite = isset($_GET['couponsite']) ? 1 : 0;

$EdmundsCampaignIdforMotorTrend = array(73185,42840,42922,41470,41367,44055,44056,45662,45656,45427,46419,79689,79692,79693,79694,79695,79696,79698,79700,79705,79706,79707,79708,79709,79710,79711,79712,49477,72422,79690,79691,80900,80901,80902,80903,80904,80905,80906,80907,80908,80909,80910,80911,80912,80913,80914,80915,80916,79701,79702,79703,46917,47008);
//Specific to Edmunds to MotorTrend - https://admedia-jira.atlassian.net/browse/AD-1196
$mt_ed_mapping_Redis = new Redis();
$mt_ed_mapping_Redis->pconnect($config['redis_ip_for_1800contacts'],$config['redis_port_for_1800contacts']);
$decrypt_mc[4] = isset($decrypt_mc[4]) ? $decrypt_mc[4] : "";

$motorTrendLink = $mt_ed_mapping_Redis->hGet("motortrend_edmund_mapping",$decrypt_mc[4]);

if (!empty($motorTrendLink)) {
    
    $MTcreativeRedis = new Redis();
    $MTcreativeRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $decrypt_mc = array();
    $encrpt_array = explode("::",decrypt_str($motorTrendLink));//$encrpt_array = [adv_id,cmp_id,creative_id]
    $decrypt_mc[0] = time() . rand(1000000, 9999999) . $encrpt_array[1];//click id
    $decrypt_mc[1] = "dynamic";//keyword of static link
    $decrypt_mc[2] = "dynamic";//affiliate for static link
    $decrypt_mc[3] = $encrpt_array[0]; //adv_id
    $decrypt_mc[4] = $encrpt_array[1];//cmp id
    $decrypt_mc[5] = str_replace("'","",$encrpt_array[2]);//creative id
    $decrypt_mc[6] = 0;//bid
    $decrypt_mc[7] = $MTcreativeRedis->hGet('all_creatives',$decrypt_mc[5]);//creative url
    $decrypt_mc[8] = time()+ 3600;//timestamp
    $decrypt_mc[9] = "";//host
    $decrypt_mc[10] = "";//IP
    $decrypt_mc[11] = "";//UA
    $decrypt_mc[12] = 0;
    $decrypt_mc[13] = "CPC";//type
    $decrypt_mc[14] = 0;
    $decrypt_mc[15] = 1;
    $decrypt_mc[16] = "";//sub id
    $decrypt_mc[17] = 1;//static link

}

//check input query rules
$dropClick = 0;
$error = array();
$rules = $config['query_param_rules'];
foreach ($rules as $queryParam => $regex) {
    if(!isset($_GET[$queryParam]) || empty($_GET[$queryParam]))
        continue; //Check if query param is set and not empty
    
    if($queryParam=="srt_hash"){
        if(empty($encrpt_array) || preg_match('~[^\x20-\x7E\t\r\n]~',$encrpt_array[count($encrpt_array)-1]) > 0){
            $dropClick = 1;$error[$queryParam]=$encrpt_array;
        }
    }elseif($queryParam=="mc") {
        if(preg_match('~[^\x20-\x7E\t\r\n]~',$decrypt_mc[count($decrypt_mc)-1]) > 0){
            $dropClick = 1;$error[$queryParam]=$decrypt_mc;
        }
    }else{
        if(preg_match($regex,$_GET[$queryParam]) == 0){
            $dropClick = 1;$error[$queryParam]=$_GET[$queryParam];
        }
    }
}
//If any rules fails then capture that 
if($dropClick == 1){
    $uniqueRequestId = "RULE_FAIL_DROPCLICK";
    click_drop_log(__FILE__,__LINE__,"Rule fails:-". json_encode(array_keys($error)),json_encode($error));
    //echo "bot click";
    //exit();
}


if(isset($_GET['debug']) && $_GET['debug'] == "ms3rfcv")
{
	var_dump($decrypt_mc);
	var_dump('given_xmlfeed = '.$given_xmlfeed);
    var_dump('given_search_ref = '.$given_search_ref);
    var_dump('given_subid = '.$given_subid);
    var_dump($_SERVER['HTTP_X_FORWARDED_FOR']);
    die;
}
// Check values 


//Get bid value from campaign wise bid, If not exist then use xml feed set bid value as previous
//xml info redis
$aff_xml_redis_info = new Redis();
$aff_xml_redis_info->pconnect($config['redis_ip_for_xml_data'], $config['redis_port_for_xml_data']);
//$aff_xml_redis_info->pconnect('205.134.226.146', 8102);
$mkey = "affiliate_names";
$affiliate_name = $aff_xml_redis_info->hget($mkey,$given_aff_id);
$mkey = "xml_aff_info_".strtolower(md5(strtolower($affiliate_name)));
$value = $aff_xml_redis_info->get($mkey);
$aff_settings = json_decode($value, true);
$premium = false;
if ( $aff_settings['marquee_status'] ){
    $premium = true;
}

if(!empty($oos_serp_aff)){
    $redishashKey = "affiliate_names";
    $affiliate = $aff_xml_redis_info->hGet($redishashKey,$oos_serp_aff);
    $affiliate_name = empty($affiliate) ? $oos_serp_aff : $affiliate;
}

$redisCampaignBidHashKey = "campaignwise_bid_value";

$clickid = isset($decrypt_mc[0]) ? $decrypt_mc[0] : "";
$search = isset($decrypt_mc[1]) ? $decrypt_mc[1] : "";
$subid = isset($decrypt_mc[2]) ? $decrypt_mc[2] : "";
if(!empty($oos_serp_aff)){
    $subid = $oos_serp_aff;
}
$advid = isset($decrypt_mc[3]) ? $decrypt_mc[3] : "";
$campaign_id = isset($decrypt_mc[4]) ? $decrypt_mc[4] : "";

// If a campaign is paused, check if we can drop the traffic to a specific link
$redisForChannelWiseKeywords = new Redis();
$redisForChannelWiseKeywords->pconnect($config['short_url_creative_redis'], $config['short_url_creative_redis_port']);
$isPaused = $redisForChannelWiseKeywords->hExists("paused_campaigns", $campaign_id)
                && $redisForChannelWiseKeywords->hGet("paused_campaigns", $campaign_id);

if ($isPaused && $advid != 13421) {
    //check campaign level pub drop URL
    $redisKeyField = strtolower($affiliate_name) . "_" . $campaign_id;
    $url = $redisForChannelWiseKeywords->hGet('publisher_traffic', $redisKeyField);
    if (empty($url)) {
        //check advertiser level drop URL
        $advDropUrl = $campaign_info_redis->hExists('t_campaign_'.$campaign_id, 'adv_drop_url')
            ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'adv_drop_url')
            : false;
        $url = empty($advDropUrl) ? "https://socialsearch.com/" : $advDropUrl;
    }
    if (!empty($url)) {
        header("Location: " . $url);
        ob_end_flush();
        exit();
    }
}

$creative_id = isset($decrypt_mc[5]) ? $decrypt_mc[5] : "";

/** 
 * affiliate id 126717 = affiliate "adx_rtb"
 */
if ($given_aff_id == 126717 && $advid == 20378 && $creative_id == 0) {
    $adx_crid = $redisForChannelWiseKeywords->hExists('adx_campaign_crids', $campaign_id) 
            ? (int)$redisForChannelWiseKeywords->hGet('adx_campaign_crids', $campaign_id) 
            : 0;
    if($adx_crid > 0) {
        $creative_id = $adx_crid;
    }
}

if (isset($_GET['overwrite_bid'] ) && $_GET['overwrite_bid'] == 1 ) {
    $bid = isset($decrypt_mc[6]) ? $decrypt_mc[6] : 0;
} else {
    $bid = ($aff_xml_redis_info->hExists($redisCampaignBidHashKey,$campaign_id)) ? $aff_xml_redis_info->hGet($redisCampaignBidHashKey,$campaign_id) : false;
}
$bidVal = isset($decrypt_mc[6]) ? $decrypt_mc[6] : 0.02;
$cpc = ($bid === false) ? $bidVal : $bid;


if (isset($_GET['debug']) && $_GET['debug'] == "mt") {
    var_dump("override = ".$_GET['overwrite_bid']);
    var_dump("decrypt_mc[6] = ".$decrypt_mc[6]);
    var_dump("bidVal ".$bidVal);
    var_dump("cpc ".$cpc);
}

$redirect = isset($decrypt_mc[7]) ? $decrypt_mc[7] : "";

//Check Campaign status and drop click if it cappepd, deleted
$campaignStatus = $campaign_info_redis->hExists('t_campaign_'.$campaign_id, 'status') ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'status') : false;
$campaignTargetting = $campaign_info_redis->hGet('t_campaign_'.$campaign_id,'targeting');
$campaignTargetting = (empty($campaignTargetting)) ? array() : json_decode($campaignTargetting,true);

$search_2_traffic = true;
$search_13_traffic = true;
$campaignName =$campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name');
$campaignName =!empty($campaignName) ? $campaignName : "";

if (strpos(strtolower($campaignName), 'search_2_') === false) {
    $search_2_traffic = false;
}
if (strpos(strtolower($campaignName), 'search_13_') === false) {
    $search_13_traffic = false;
}

if (isset($_GET['debug']) && $_GET['debug'] == "mt1") {
    var_dump($campaignName);
    var_dump($search_2_traffic);
    var_dump($search_13_traffic);
    die;
}

//check targetting
//get IP Info
$end_user_ip =  $_SERVER['HTTP_X_FORWARDED_FOR'];
$location = maxmindIp2location($end_user_ip);
if(!empty($_GET['debug'])) {
    var_dump($location);
}
$usercountry = $location['country3'];
$city = $location['city'];
$state = $location['state'];
$city_state = strtolower($city . ':' . $state);
$zip = $location['postal'];
$metro_code = $location['metro_code'];
$geo_target_unmatch = False;
$reason_geo_unmatch = "";
// Country
if (!empty($campaignTargetting['countries'])) {
    if (!$usercountry || !in_array($usercountry, $campaignTargetting['countries'])) {
        $geo_target_unmatch = True;
        $reason_geo_unmatch = "country code is $usercountry";
    }
}
// Metro Code
if (!$geo_target_unmatch  && !empty($campaignTargetting['metro']) && !in_array($metro_code, $campaignTargetting['metro'])) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "metro is $metro_code";
}
// State
if (!$geo_target_unmatch && !empty($campaignTargetting['states']) && !in_array($state, $campaignTargetting['states'])) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "state is $state";
}
// City
if (!$geo_target_unmatch && !empty($campaignTargetting['cities']) && !in_array($city_state, $campaignTargetting['cities'])) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "City is $city_state";
}
// Zip
if (!$geo_target_unmatch && !empty($campaignTargetting['zip']) && !in_array($zip,$campaignTargetting['zip'])) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Zip is $zip";

}
// Exclude Geo's
//Exclude Country
if(!$geo_target_unmatch && !empty($campaignTargetting['exclude']['countries']) && in_array($usercountry,$campaignTargetting['exclude']['countries']) ){
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Excluded Country is $usercountry";
}
//Exclude Metro
 if(!$geo_target_unmatch && !empty($campaignTargetting['exclude']['metro']) && in_array($metro_code,$campaignTargetting['exclude']['metro']) ){
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Excluded Metro is $metro_code";
}
//Exclude States
if (!$geo_target_unmatch && !empty($campaignTargetting['exclude']['states']) && in_array($state, $campaignTargetting['exclude']['states']) ){
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Excluded State is $state";
}
// Exclude City
if (!$geo_target_unmatch && !empty($campaignTargetting['exclude']['cities']) && in_array($city_state, $campaignTargetting['exclude']['cities']) ) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Excluded City is $city_state";
}
// Exclude Zip
if (!$geo_target_unmatch && !empty($campaignTargetting['exclude']['zip']) && in_array($zip, $campaignTargetting['exclude']['zip']) ) {
    $geo_target_unmatch = True;
    $reason_geo_unmatch = "Excluded Zip is $zip";
}

if( !$search_2_traffic && !$search_13_traffic) {
    if ($geo_target_unmatch || (!empty($campaignStatus) && in_array($campaignStatus,array("X")))) {//if archived, we drop it.
        //check campaign level pub drop URL
        $redisKeyField = strtolower($affiliate_name) . "_" . $campaign_id;
        $url = $redisForChannelWiseKeywords->hGet('publisher_traffic', $redisKeyField);
        if (empty($url)) {
            //check advertiser level drop URL
            $advDropUrl = $campaign_info_redis->hExists('t_campaign_'.$campaign_id, 'adv_drop_url')
                ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'adv_drop_url')
                : false;
            $url = empty($advDropUrl) ? "https://socialsearch.com/?dc=ic" : $advDropUrl;//ic = inactive campaign
        }
        $reason = ($geo_target_unmatch) ? "Out of Geo | $reason_geo_unmatch" : ( ($campaignStatus == 'C') ? "Capped Campaign" : "Deleted Campaign" );
        log_clicks(1,$reason);
        if(!empty($_GET['debug'])) {
            var_dump("Reason=>$reason ,Drop Url=> $url ,Campaign_targetting=>",$campaignTargetting);
            exit();
        }
        if (!empty($url)) {
            header("Location: " . $url);
            ob_end_flush();
            exit();
        }
    }
}


//check publisher traffic with respect to campaign specific
if(!empty($campaign_id)){
    if(isset($_GET['debug_pub']) && $_GET['debug_pub']==1){
        var_dump("checking the drop url");
    }
    $campaign_name = !empty($campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name'))
        ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name') : "Search_100";//default Search_100

    // Extract all numbers from the string
    preg_match_all('/\d+/', $campaign_name, $matches);

    // Get the third number (0-indexed), which is the ID
    $affiliate_extracted_id = isset($matches[0][1]) ? $matches[0][1] : null;
    if(isset($_GET['debug_pub']) && $_GET['debug_pub']==1){
        var_dump($campaign_name);
        var_dump($matches);
        var_dump($affiliate_extracted_id);
    }

    if ($affiliate_extracted_id !== null && ctype_digit($affiliate_extracted_id)) {
        //Get name of this affiliate
        $affiliate_name = $aff_xml_redis_info->hget("affiliate_names",$affiliate_extracted_id);
        //check publisher traffic with respect to specific campaign
        $redisKeyField = strtolower($affiliate_name)."_".$campaign_id;
        $drop_traffic_url = $mt_ed_mapping_Redis->hGet('publisher_traffic', $redisKeyField);
        if(isset($_GET['debug_pub']) && $_GET['debug_pub']==1){
            var_dump("Step 1 $redisKeyField ".$drop_traffic_url);
        }
        if(empty($drop_traffic_url)) {
            $redisKeyField = strtolower($affiliate_name);
            //check publisher traffic with respect to all campaign
            $drop_traffic_url = $mt_ed_mapping_Redis->hGet('publisher_traffic', $redisKeyField) ;
            if( isset($_GET['debug_pub']) && $_GET['debug_pub']==1){
                var_dump("Step 2 $redisKeyField ".$drop_traffic_url);
            }
        }
        if(!empty($drop_traffic_url) ) {
            if(isset($_GET['debug_pub']) && $_GET['debug_pub']==1){
                var_dump("Step final redirection for key $redisKeyField: ".$drop_traffic_url);
                exit;
            }
            //drop this traffic
            header('Location: ' . $drop_traffic_url);
            ob_end_flush();
            exit();
        }
    }
}


if (isset($_GET['debug']) && $_GET['debug'] == "mt") {
    var_dump($encrpt_array);
    var_dump($encrpt_array[2]);
    var_dump($decrypt_mc);
    var_dump("CPC IS ".$cpc);
    var_dump("testingClick = ".$testingClick);
    die;
}

//Switch the redirect if hourly rotation is set
$cridRotationRedis = new Redis();
$cridRotationRedis->pconnect($config['redis_ip_for_campaigns'],$config['redis_port_for_campaigns']);
$currentHour = (int) date('H');
$cridRotationKey =  $campaign_id."_crid_".date("Ymd")."_hour_$currentHour";
if ( $cridRotationRedis->exists($cridRotationKey) ) {
    $crids = explode(',',$cridRotationRedis->get($cridRotationKey));
    $creative_id = $crids[array_rand($crids)];
    //get creative url
    $allcreativeData = new Redis();
    $allcreativeData->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $redirect = $allcreativeData->hGet('all_creatives',$creative_id);
}

//check if amazon advertiser, add tag if  missing on the $redirect link
if ( $advid == 20378  || $advid == 21610) {
    require_once 'validateUrl.php';
    $categoryName = "";
    if( $creative_id == 0 ) {
        $creative_ids = $campaign_info_redis->hGet('t_campaign_' . $campaign_id, 'creatives');
        $crids = json_decode($creative_ids, true);
        $creative_id = $crids[0];
    }

    $allcreativeData = new Redis();
    $allcreativeData->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);

    $creativeDestUrl = $allcreativeData->hGet('all_creatives', $creative_id);//creative url
    $parsed_url = parse_url($creativeDestUrl);

    if(isset($_GET['amzn_debug']) && $_GET['amzn_debug'] ) {
        var_dump($creative_id);
        var_dump($creativeDestUrl);
        var_dump($parsed_url);
    }

    parse_str($parsed_url['query'], $query_params);

    $amzn_tag = urlencode($query_params['tag']);

    if( empty($_GET["shopfeed"]) && empty($_GET["skip_reftag"])) {

        $redirect_url = $creativeDestUrl;
        $amzn_pid = $given_aff_id;

        //get ref tag for this publisher ID
        //Get a Random listing first
        if (isset($_GET['dest'])) {
            $_GET['dest'] = cleanAmazonLink($_GET['dest'] );
            if(!empty($_GET['dest'])) {
                $redirect_url = $_GET['dest'];
            }
        }
        if(!empty($sovrn_keyword)){
            $redirect_url = urldecode($sovrn_keyword);
            $redirect_url = cleanAmazonLink($redirect_url);
            $amzn_pid = 122450;
        }

        $redirect_url = preg_replace('/\/ref=.*$/', '', $redirect_url);//remove existing ref= if any present

        //validate URL check html/blanl domain
        $amznUrlStatus = validateUrl($redirect_url);
        if(!$amznUrlStatus){
            $redirect_url = $creativeDestUrl;//send traffic on creative url if its invalid url
        }
        //check if redirect url has ASIN
        $asin = extractAsin($redirect_url);

        $pickShopRefTag = 0;

        $catId = null;
        //if ( in_array($amzn_pid,[118593,119356,123716,124650,126691]) ){
        if (preg_match('/^txtadnwplace([1-9]|10)-20$/', $amzn_tag)) {
            //shop associate tag matches, for these pubs, we must only use shop ref tags.
            $pickShopRefTag = 1;
        }
        //}
        /**
         * if ASIN value exist then get asin refcode otherwise go with normal flow
         */
        if(!empty($asin) && $pickShopRefTag){
            if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
                var_dump("ASIN PRESENT");
            }
            $asinData = getAsinReftag($asin,$amzn_pid);
            $reftag_value = $asinData['reftag'];
            $catId = $asinData['cat_id'];
            $categoryName = $asinData['category'];
        }else{
            if($pickShopRefTag) {
                $asinData = getAsinReftag("GARBAGE",$amzn_pid);//no sku, use any garbage sku to fetch randon reftag for shop feed
                $reftag_value = $asinData['reftag'];
                $catId = $asinData['cat_id'];
                $categoryName = $asinData['category'];
            } else {
                //Get a legacy term and send it to best match
                $legacyKeyword = null;//default empty
                $rand_number = rand(1, 100);
                $target = 95;//95% is default.
                //AO-17398 - gradual 2% decrease
                $TestTagsToAllocate75Percent = [
                        "usdeplacement-20",
                        "ussmtplacemen-20"];

                if ( in_array($amzn_tag,$TestTagsToAllocate75Percent) ) {
                    $target = 90;//90% target for now.
                }

                if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
                    var_dump("RANDOM NUMBER = " .$rand_number);
                }
                if (isset($decrypt_mc[17]) && is_string($decrypt_mc[17]) && $decrypt_mc[17] !== "1") {
                    $legacyKeyword = $decrypt_mc[17];
                    $rand_number = 96;
                }

                if( $given_aff_id == 120926 ) {//fatcoupon only.
                    $itemlevelbidTag = ["us2025tag16-20"];
                    $itemlevelbidCIDs = [107066,107067,107068,107069,107070,107071,107072,107073,107074,107075,107076,107407,107408,107409,107410,107411,107412,107413,107414,107415,107416,107417];
                    if ( in_array($amzn_tag,$itemlevelbidTag)
                        &&
                        in_array($campaign_id,$itemlevelbidCIDs) ) {
                        $rand_number = 100;//100% target for expanded keyword reftags
                    }
                }

                if($rand_number < $target) { //we want a high probablity to pick a legacy term
                    $LegacyKeywordsRedis = new Redis();
                    $LegacyKeywordsRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
                    $LegacyKeywordsRedisHashKey =  "chanelKeywordsFor_".$advid;

                    $fields = $LegacyKeywordsRedis->hKeys($LegacyKeywordsRedisHashKey);

                    if (!empty($fields)) {
                        $randField = $fields[array_rand($fields)];
                        $raw = $LegacyKeywordsRedis->hGet($LegacyKeywordsRedisHashKey, $randField);
                        $raw_values = json_decode($raw);
                        $legacyKeyword = $raw_values[array_rand($raw_values)];

                        if (isset($decrypt_mc[17]) && is_string($decrypt_mc[17]) && $decrypt_mc[17] !== "1") {
                            $legacyKeyword = $decrypt_mc[17];
                        }

                        if (isset($_GET['amzn_debug']) && $_GET['amzn_debug']) {
                            var_dump("legacy term = " . $legacyKeyword);
                        }
                    }
                }
                list($randomKeywordDestUrl, $catId,$categoryName) = getOpenSearchRandomKeyword($amzn_pid,$device,$legacyKeyword);
                if(empty($redirect_url) && !empty($randomKeywordDestUrl)){
                    $redirect_url = $randomKeywordDestUrl;
                }
                if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
                    var_dump("UPDATED TO ".$redirect_url);
                    //exit;
                }
                //extract Search term.
                // Parse query string
                parse_str(parse_url($randomKeywordDestUrl, PHP_URL_QUERY), $random_dest_params);
                // Get the 'k' value
                $keyword = isset($random_dest_params['k']) ? $random_dest_params['k'] : null;
                if(!is_null($keyword)){
                    $search = $keyword;
                }
                $reftag_value = isset($random_dest_params['ref']) ? urldecode($random_dest_params['ref']) : null;
            }
        }

        if(empty($reftag_value)) {
            if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
                var_dump("Step 2 shop reftag");
            }
            $asinData = getRandomShopReftags($amzn_pid,$pickShopRefTag);
            $reftag_value = $asinData['reftag'];
            $catId = $asinData['cat_id'];
            $categoryName = $asinData['category'];
            $reftag_value = empty($reftag_value) ? "default" : $reftag_value;
        }


        if(isset($_GET['amzn_debug']) && $_GET['amzn_debug']){
            var_dump(" REF TAG START ");
            var_dump($reftag_value);
            var_dump(" REF TAG END ");
            //exit;
        }
        if (strpos($redirect_url, '?') !== false) {
            $redirect_url = $redirect_url . "&ref=".$reftag_value;
        } else {
            $redirect_url = $redirect_url . "?ref=".$reftag_value;
        }

        if (!empty($catId)) {
            $redirect_url = $redirect_url . "&cat_id=".$catId;
        }
        // if (!empty($categoryName)) {
        //     $redirect_url = $redirect_url . "&cat=".urlencode($categoryName);
        // }

        $adtypeid = (empty($pickShopRefTag)) ?  1 : 2;// 1 is textads, 2 is shopads
        $legacy = 0;
        if ( !is_null($legacyKeyword) ) {
            $legacy = 1;
        }

        $redirect_url = $redirect_url  . 
                        "&hvcampaign=$campaign_id".
                        "&hvadtype=$adtypeid".
                        "&hvdev=$device".
                        "&hvpub=$actualamznPid".
                        "&appid=$actualamznPid".
                        "&l=$legacy";

        //Add tag param if it not exist
        $parts = parse_url($redirect_url);
        parse_str($parts['query'], $params);

        if(!isset($params['tag'])){
            $redirect_url = $redirect_url . '&tag='.$amzn_tag;
        }

    } else {
        //XML Data Fixes
        if(isset($_GET["xmlReftag"]) && !empty($_GET["xmlReftag"]) && isset($_GET["xmlReftagsku"]) && !empty($_GET["xmlReftagsku"])){
            $redirect_url = $redirect;
            $sku = $_GET["xmlReftagsku"];
            $amazonPubid = $_GET["xmlReftag"];
            $asinData = getXMLAsinReftag($sku,$amazonPubid);
            $reftag_value = isset($asinData['reftag']) ? $asinData['reftag'] : false;
            $catId = isset($asinData['cat_id']) ? $asinData['cat_id'] : 0;
            $categoryName = isset($asinData['category']) ? $asinData['category'] : 0;
            $reftag_value = empty($reftag_value) ? 'pd_sl_ec71f018a3d04562bc6adc604b1db52a_e' : $reftag_value;
            $redirect_url = str_ireplace('{reftag}',$reftag_value, $redirect_url);
            $redirect_url = $redirect_url  . "&appid=$amazonPubid&hvpub=$amazonPubid&cat_id=$catId";
        }else{
            //shopping web
            $redirect_url = $redirect;
            $amzn_pid = $given_aff_id;
            $asin = extractAsin($redirect_url);
            $asinData = getAsinReftag($asin,$amzn_pid);
            $reftag_value = $asinData['reftag'];
            $catId = isset($asinData['cat_id']) ? $asinData['cat_id'] : 0;
            $categoryName = isset($asinData['category']) ? $asinData['category'] : 0;
            //replace reftag w.r.t 
            if(!empty($reftag_value))
                $redirect_url = preg_replace('/ref=[^?&]+/', "ref=$reftag_value", $redirect_url);

            //replace other query param
            $parts = parse_url($redirect_url);
            parse_str($parts['query'], $query);
            $query['hvpub'] = $query['appid'] = $actualamznPid;
            $query['cat_id'] = $catId;
            $query['hvcampaign'] = $campaign_id;
            $query['hvadtype'] = 2;//for shop
            $query['hvdev'] = $device;
            $parts['query'] = urldecode(http_build_query($query));
            $redirect_url = $parts['scheme'] . "://" . $parts['host'] . $parts['path'] . "?" . $parts['query'];
        }
    }
    //replace marcro if tag is present
    $replace_array = array (
        '[tag]' => $amzn_tag,
        '{tag}' => $amzn_tag
    );
    $redirect_url = str_ireplace(array_keys($replace_array), $replace_array, $redirect_url);

    $redirect = $redirect_url;

    if(isMobileDevice()){
        $redirect = str_replace(
            "https://www.amazon.com/s?k=",
            "https://www.amazon.com/dp/s?k=",
            $redirect
        );
     }

}

if( isset($_GET['amzn_debug']) && $_GET['amzn_debug'] ) {
    var_dump($redirect);
    exit;
}

$oosSerpLink = validateSerpLink($redirect);
$tstamp = isset($decrypt_mc[8]) ? $decrypt_mc[8] : "";
$host = isset($decrypt_mc[9]) ? $decrypt_mc[9] : "";
$search_ip = isset($decrypt_mc[10]) ? $decrypt_mc[10] : "";
$search_ips = explode(',',$search_ip);
if (!empty($search_ips)) {
    $search_ip = trim($search_ips[0]);
}
$search_ua = isset($decrypt_mc[11]) ? $decrypt_mc[11] : "";
$freq_cap = isset($decrypt_mc[12]) ? $decrypt_mc[12] : "";
$type = isset($decrypt_mc[13]) ? $decrypt_mc[13] : "";

if ( !empty($given_aff_id) && is_numeric($given_aff_id)) {
    $final_aff_id = $given_aff_id;
} else {
    $final_aff_id = !empty($subid)? $subid : $given_aff_id;
}

if(isset($decrypt_mc[15])){
	$adgroup = isset($decrypt_mc[14]) ? $decrypt_mc[14] : "";
	$position = isset($decrypt_mc[15]) ? $decrypt_mc[15] : "";
} else {
	$position = isset($decrypt_mc[14]) ? $decrypt_mc[14] : "";
	$adgroup = 0;
}
//If connexity bing url hitted then
if ($connexityBing){
    $rediswrite2 = new Redis();
    $rediswrite2->pconnect($config['r2_redis_ip_read'], $config['r2_redis_ip_read_port']);
    $af_placement_id = '';
    $subidforconnexity = empty($affiliate_set_sub_id) ? 1 : $affiliate_set_sub_id;
    $incomingValue = "shopping".$campaign_id.$subidforconnexity;
    $af_placement_id = generateConsistentNumericId($incomingValue);
    $redirect .= '&af_placement_id='.$af_placement_id;//change redirect url
    $conexityObj = new stdClass();
    $conexityObj->af_placement_id = $af_placement_id;
    $conexityObj->keyword = "shopping";
    $conexityObj->subid = $subidforconnexity;
    $conexityObj->cid = $campaign_id;
    $rediswrite2->rpush('connexity_placementid_info', json_encode($conexityObj));
}

//capture traffic with server ip into redis and campaign id and some meta data
$capturetraffic = new stdClass();
$capturetraffic->date = date("Y-m-d");
$capturetraffic->time = time();
$capturetraffic->camp_id = $campaign_id;
$capturetraffic->adv_id = $advid;
$capturetraffic->host_ip = $_SERVER['REMOTE_ADDR'];
$rediswrite->rpush('host_traffic_'. date("Ymd"), json_encode($capturetraffic));

//get browser 
$browserParser = new DeviceDetector\Parser\Client\Browser();
$search_ua = !empty($search_ua) ? $search_ua : $_SERVER['HTTP_USER_AGENT'];
$browserParser->setUserAgent($search_ua);
$browser = $browserParser->parse();
$browser_name = (isset($browser['name']) && !empty($browser['name'])) ? $browser['name'] : "";

if( $campaign_id == 91977 ) {
    $nissanRdr = "https://www.lookfantastic.com/?search=lookfantastic&subid=119356";
    header('Location: '.$nissanRdr);
    ob_end_flush();
    exit();
}


if( $advid == 15992 ) { // per Emma CLIC-49
    $nissanRdr = "https://www.pizzahut.com/";
    header('Location: '.$nissanRdr);
    ob_end_flush();
    exit();
}

if($campaign_id == 80137 ) { // per danny CLIC-48 and AO-13666
    $nissanRdr = "https://www.socialsearch.com/";
    header('Location: '.$nissanRdr);
    ob_end_flush();
    exit();
}

if($campaign_id == 66505) { // per danny and nathan April 5 2024
    header('Location: https://www.google.com');
    ob_end_flush();
    exit();
}

if ( $advid == 13425) { // XML-240, redirect all Edmunds to Nissan

    $nissanRdr = "https://63014.click.validclick.net/cad.php?mc=Iyw5MjAjMSAqPSQ5PS0qIS8-NjIgNS0jbWhmZXlwcSAyYXt_YHpwaisyNSEhIyoyPzQiMSYtMys6NSMtIioyPzIrO39tfWEyKzt6fnNrbnF0c2F8J3VpdmBqd3t6Zmo_b3JtJn1han82cXZhZmkubX59NCU7MyQpIi8-PTQhNyEqMSQ-InBqTWlXbnV2aHMkPCk_NCQpIiw6PDMjNCQvPCMuYGdGZ2hkWnQsMzF9ek5sYWdtTW96aT95dWNpeisnK2NuZTRmbHFiYHlsenAmZ3t0PTV7bW1hcX53bjx8a3t1YTVqcGt9ZTppe3hrYTpxZndkOmZycSppenwmX1V9dWhncHJYRUo_fGVlW3l8dnN9aD9iZHo_fGVlW2d2Z2hrYD9wZXp8bXhpImFtf0VpZmF-dHltNHBsaXF9e3sucHZ8XnR4ZGFpbXN3L2ltZHByaUgrVmNtcHF3ZnNna11jbnkjMyA-NSMrIC47NjYrOy0jMysyPiQjKFlYRjgrMS0jOCsyPi4o&adv=15810&utm_source=63014&search=&aid=&b=";
    header('Location: '.$nissanRdr);
    ob_end_flush();
    exit();
}

/*if (  $advid == 15842 ) { // 1800contact advertiser IP block

    $redis1800Contacts = new Redis();
    $redis1800Contacts->pconnect($config['redis_ip_for_1800contacts'],$config['redis_port_for_1800contacts']);
    $clickip1800contacts = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
    if (isset($_GET['1800contactstest'])) {
        $clickip1800contacts = $_GET['1800contactstest'];
    }

    if(filter_var($clickip1800contacts, FILTER_VALIDATE_IP)) {
        if(filter_var($clickip1800contacts, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $ipInt = ip2long_v6($clickip1800contacts);
        }else{
            $ipInt = ip2long($clickip1800contacts);
        }
        if (isset($_GET['debug'])){
            var_dump($clickip1800contacts. ' = '. $ipInt);
            var_dump($redis1800Contacts->hGet('Blocklist1800Contacts', $ipInt) );
            die();
        }

        //Is IP blocked ?
        if ( $redis1800Contacts->hGet('Blocklist1800Contacts', $ipInt) ) {
                $dropUrl = "https://socialsearch.com/Search?search=".$search."&subid=$subid";
                $reason = '1800 contacts IP block';
		click_drop_log(__FILE__,__LINE__,$reason,"redirect to default");
		redirect_home(1, "1800 contacts IP block",$dropUrl);
        }
    }
}*/

//$campaign_info_redis->pconnect('192.168.'.'30.106',6378);
$isKeywordReportDisabled = intval($campaign_info_redis->hGet('t_campaign_'.$campaign_id,'is_kw_report_disable'));

$search = $original_keyword = ($search != '' && $search != 'dynamic') ? $search : $search_keyword ;
if(isset($decrypt_mc[18])) {
    $original_keyword = isset($decrypt_mc[18]) ? trim($decrypt_mc[18]) : null;
}

if ( $aff_keyword == '' && !empty($search) && $search != 'dynamic') {
    $aff_keyword = $search;
}

if ( isset($_GET['keyword']) ) {
   $original_keyword = $_GET['keyword'];
}

if (isset($_GET['sphinx_debug'])){
    var_dump("search = ".$search);
    var_dump("decrypt_mc[17] = ".$decrypt_mc[17]);
    var_dump("Before sphinx search");
    exit;
}

if ( $campaign_id == 72665) {
    //Wayfair shop campaign
    $redirect .= '&clickid=72665_6l1449hed11_'.mt_rand();
}

//create Unique Hash Id
$keywordId = 0;
$match_keyword = isset($decrypt_mc[1]) ? $decrypt_mc[1] : "";
$matchType = "broad";
//change unique id to base 32 instead base 64 as base 64 is case senstive
/*$base32 = new Base2n(5,BITS_CHAR, FALSE, TRUE, TRUE);
$unique_id = $base32->encode(openssl_encrypt($campaign_id."_".date("Ymd")."_".mt_rand(0,100000), METHOD , HASH_KEY , 0, IV));
$unique_id = str_replace('=','',$unique_id);*/

$unique_id = date("YmdHis")
            .str_pad(mt_rand(0,999999), 6, '0', STR_PAD_LEFT)
            .$campaign_id;


if ( in_array($advid,[19337,19334,19335,19336]) ) {

    $keywordDestUrlRedis = new Redis();
    $keywordDestUrlRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);

    $redisKeywordDestUrlHashKey = "keywords_dest_urls_{$advid}";
    if($keywordDestUrlRedis->exists($redisKeywordDestUrlHashKey)){
            if (isset($decrypt_mc[17])) {
                $search_keyword = $decrypt_mc[17];

                if ( $decrypt_mc[17] == '1' ) {
                    $redis_keyword_read = new Redis();
                    $redis_keyword_read->pconnect($config['redis_ip_keyword_data'], $config['redis_port_keyword_data']);
                    $jsonData = $redis_keyword_read->get("keywordIds_$campaign_id");
                    $hash = json_decode($jsonData,true);
                    $search = $search_keyword = array_rand($hash);
                }
            }

            $adv_search_keyword = $search_keyword;
            $adv_search_keyword = str_replace(' ','',$adv_search_keyword);
            $hashField = preg_replace("/[^A-Za-z0-9]/",'',$adv_search_keyword);
            $keywordDestUrl = $keywordDestUrlRedis->hGet($redisKeywordDestUrlHashKey,$hashField);
            if(!empty($keywordDestUrl)){

                $adv_cmp_name = "Search_100_Trelegy";
                switch($advid) {
                    case 19334:
                        $adv_cmp_name = "search_100_dovato";
                        break;
                    case 19335:
                        $adv_cmp_name = "Search_100_Nucala";
                        break;
                    case 19336:
                        $adv_cmp_name = "Search_100_Cabenuva";
                        break;

                }
            $redirect = $keywordDestUrl.'&utm_source=admedia&utm_medium=cpc&utm_term={Keyword}&utm_campaign='.$adv_cmp_name;

            if (isset($_GET['sphinx_debug'])){
                var_dump('found dest URL for keyword '.$search_keyword);
                var_dump($redisKeywordDestUrlHashKey);
                var_dump($hashField);
                var_dump($redirect);
            }
            } else {
            $redirect = 'https://cured.com/search?s='.$search_keyword;

            if (isset($_GET['sphinx_debug'])){
                var_dump('step 1 found NO dest URL for keyword '.$search_keyword);
                var_dump($redirect);
            }
        }
    } else {
        $redirect = 'https://cured.com/search?s='.$search_keyword;

        if (isset($_GET['sphinx_debug'])){
            var_dump('step 2 found NO dest URL for keyword '.$search_keyword);
            var_dump($redirect);
        }
    }
}
if ( in_array($advid,[18769,17258,16115,16652,21582,21616]) ) {

    $keywordDestUrlRedis = new Redis();
    $keywordDestUrlRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $redisKeywordDestUrlHashKey = "keywords_dest_urls_{$advid}";
    if($keywordDestUrlRedis->exists($redisKeywordDestUrlHashKey)){
        $adv_search_keyword = str_replace(' ','',$search_keyword);
        $hashField = preg_replace("/[^A-Za-z0-9]/",'',$adv_search_keyword);
        $keywordDestUrl = $keywordDestUrlRedis->hGet($redisKeywordDestUrlHashKey,$hashField);
        if(!empty($keywordDestUrl)){
            $redirect = $keywordDestUrl;
        }
        if (isset($_GET['keyword_dest_url_debug'])){
            var_dump('found dest URL for keyword '.$search_keyword);
            var_dump($redisKeywordDestUrlHashKey);
            var_dump($hashField);
            var_dump($keywordDestUrl);
            var_dump($redirect);
            die;
        }
    }
}

if(isset($_GET['gclid'])) {
    $redirect .= '&gclid='.$_GET['gclid'];
}
/**
 * Code start to capture target ID info
 */

//$device,$browser_name calculated above,
$pubId = !empty($given_aff_id) ? $given_aff_id : $affiliate_name;//if aff id not found then add aff name
$subId = !empty($aff_sub_id) ? $aff_sub_id : (!empty($given_subid) ? $given_subid : $affiliate_set_sub_id);
$pubClickId = !empty($aff_clickid) ? $aff_clickid : (!empty($affiliate_set_click_id) ? $affiliate_set_click_id : 0);

$unique_string_array = array("campaign_id"=>$campaign_id,
                            "original_keyword"=>$original_keyword,
                            "match_keyword"=>$match_keyword,
                            "campaign_name"=>$campaignName,
                            "match_type"=>$matchType,
                            "browser"=>$browser_name,
                            "device_type"=>$device,
                            "account_id"=>$advid,
                            "adgroup"=>$adgroup,
                            "publisher_id"=>$pubId,
                            "sub_id"=>$subId,
                            "keyword_id"=>$keywordId,
                            "pub_click_id"=>$pubClickId,
                            "ip"=> $clickIP
                            );

$encryptedObj = new stdClass();
$encryptedObj->clickid = $unique_id;
$encryptedObj->value = json_encode($unique_string_array);
$encryptedObj->date = date("Y-m-d");
$rediswrite->rPush("encrypted_key_data", json_encode($encryptedObj));


if(empty(trim($search_keyword)) || $isKeywordReportDisabled){
	$redis_keyword_read = new Redis();
	$redis_keyword_read->pconnect($config['redis_ip_keyword_data'], $config['redis_port_keyword_data']);
    //$redis_keyword_read->pconnect('192.168.'.'30.106',6378);
    $jsonData = $redis_keyword_read->get("keywordIds_$campaign_id");
    $hash = json_decode($jsonData,true);
    if ( !empty($hash) ) {
        $_GET['search'] = $search_keyword = array_rand($hash);
    }
}

if ( $isKeywordReportDisabled) {
    preg_match_all('!\d+!', md5($campaign_id . '_' . str_replace(' ', '', $search_keyword)), $matches);
    $aff_keyword = $original_keyword."||".$search_keyword;

} else {
    preg_match_all('!\d+!', md5($campaign_id . '_' . str_replace(' ', '', $original_keyword)), $matches);
}
if ( $advid == 17099 || $advid == 17258 ){
	$targetId = $unique_id;
} else{
	$targetId = (int)(substr(implode('', $matches[0]), 0, 9));
}

$feedId = isset($decrypt_mc[17]) ? (int)trim($decrypt_mc[17]) : 0;

if(isset($decrypt_mc[18])) {
    $receivedMerchant = isset($decrypt_mc[18]) ? trim($decrypt_mc[18]) : null;
}

if(isset($decrypt_mc[19])) {
    $clickMerchant = isset($decrypt_mc[19]) ? trim($decrypt_mc[19]) : false;
}
if(isset($_GET['fm'])){
    $feedId = ($feedId != $_GET['fm']) ? $_GET['fm']: $feedId;
}

if (  $advid == 15357 ) { // HP advertiser IP block

    $hpRedis = new Redis();
    $hpRedis->pconnect($config['redis_ip_for_hp'],$config['redis_port_for_hp']);

    $hp_clickerip = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';

    if (isset($_GET['hptest'])) {
        $hp_clickerip = $_GET['hptest'];
    }

    if(filter_var($hp_clickerip, FILTER_VALIDATE_IP)) {
        if(filter_var($hp_clickerip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $ipInt = ip2long_v6($hp_clickerip);
        }else{
            $ipInt = ip2long($hp_clickerip);
        }
        if (isset($_GET['debug'])){
            var_dump($hp_clickerip. ' = '. $ipInt);
            var_dump($hpRedis->hGet('HPBlockedIPList', $ipInt) );
            die();
        }

        //Is IP blocked ?
        if ( $hpRedis->hGet('HPBlockedIPList', $ipInt) ) {
            echo "IP blocked for this advertiser";
            die();
            //block traffic from this
        }
    }
}

//For HP Bing traffic , add UTMs:
if ( $advid == 15357 && $campaign_id == 59154 && $subid == 117972 ) {

    $redirect .= "&jumpid=cs_con_nc_ns&utm_medium=cs&utm_source=admedia&utm_content=spaddisttype=ampla&utm_campaign=ad_media_shopping_campaign_search_8_hp_shopping_feed";
}

$feedCheck = ($advid == 2175 && $couponsite) ? false : true;

//check feed cap , status related to advertiser id
if (isset($feedId) && !empty($feedId) && $feedCheck ) {
   //validate feedId to belong to the advertiser id.
   $validFeedId = false;
   switch($advid) {
       case '14436'://meredith and meredith synd
           $validFeedId = in_array($feedId,[3720,3721]);

           break;
       case '15127'://stillstraw and stillstraw synd
           $validFeedId =  in_array($feedId,[3722,3725]);
           break;
       case '15421'://kelkoo and kelkoo synd
           $validFeedId =  in_array($feedId,
                            [3727,3733,3667,3731,3732,3730,3734,3735,3736,3737]);
           break;
       case '15410'://dealpilot and dealpilot synd
           $validFeedId = in_array($feedId,[3741,3742]);
           break;
       case '15948'://IntentX
           $validFeedId = in_array($feedId,[3755]);
           break;
       default:
   }

   if ($validFeedId) {

        //check for feed's cap count and status.
        $redisFeedIP = $config['redis_ip_for_feed_cap'];//use dev IP for testing
        $redisFeedPort = $config['redis_port_for_feed_cap'];//use 6378 for dev

       $redisFeedCheck = new Redis();
       $redisFeedConnection = $redisFeedCheck->pconnect($redisFeedIP,$redisFeedPort);

       if($redisFeedConnection) {
           //get status of the feed first
           $date = date('Y-m-d');
           $feed_current_count_key = 'xml_feed_'.$feedId.'_'.$date.'_current_click_count';
           $feed_status_key = 'xml_feed_'.$feedId.'_feed_status';
           $feed_cap_status_key = 'xml_feed_'.$feedId.'_'.$date.'_cap_status';
           $feed_cap_count_key = 'xml_feed_'.$feedId.'_cap_count';
           $feed_cap_reached_key = 'xml_feed_'.$feedId.'_cap_reached';

           $current_click_count = $redisFeedCheck->exists($feed_current_count_key) ?
                                    $redisFeedCheck->get($feed_current_count_key) : 0; // initialize to 0 if key does not exist for the date

           $cap_count = $redisFeedCheck->get($feed_cap_count_key);
           $cap_count = (int)((int)$cap_count * 0.98);//allow 98% of traffic to handle possible for concurrency issues
	       $getCapStatus = $redisFeedCheck->exists($feed_cap_status_key)? $redisFeedCheck->get($feed_cap_status_key) : 1;//default to active
           $getFeedStatus = $redisFeedCheck->exists($feed_status_key) ? $redisFeedCheck->get($feed_status_key) : 1;// default to active

           if (isset($_GET['debug'])){
               var_dump("current_click_count = ".$current_click_count. ' for redis key '.$feed_current_count_key);
               var_dump('cap_count  ='.$cap_count);
               var_dump('getFeedStatus ='.$getFeedStatus);
           }

           if ($current_click_count <= $cap_count && $getFeedStatus) {

                $redisFeedCheck->incr($feed_current_count_key);
                $redisFeedCheck->expire($feed_current_count_key, 86400);

               if ($redisFeedCheck->exists($feed_cap_reached_key) ) $redisFeedCheck->del($feed_cap_reached_key);

	        } else {
               if (isset($_GET['debug'])){
                   var_dump("feed_current_count_key = ".$feed_current_count_key);
                   var_dump('fm  ='.$_GET['fm']);
                   var_dump('feedId decoded ='.$feedId);
                   var_dump('feed_cap_status_key = '.$feed_cap_status_key);
                   var_dump($current_click_count. " <= ".$cap_count.', capStatus = '.$getCapStatus.' , feedStatus = '. $getFeedStatus);
                   die();
               }

                $redisFeedCheck->set($feed_cap_status_key,0);//set cap status to inactive i.e, 0
                $redisFeedCheck->set($feed_cap_reached_key,time());
                $reason = "Feed cap reached for feedId - ".$feedId;
                click_drop_log(__FILE__,__LINE__,$reason,"redirect to default");
                $dropbhgSERPUrl ="https://find.vplay-fuel.com/results.aspx?q=".$search."&gd=SY1003522&searchsource=69".'&hello=1';
                header('Location: '.$dropbhgSERPUrl);
                ob_end_flush();
                exit();
	        }

	    }else{
           if (isset($_GET['debug'])){
               var_dump('Redis connection to 192.168.17.103 / 6379 failed ');
               die();
           }
           //Since redis is not available, drop to bhg
           click_drop_log(__FILE__,__LINE__,"redis Failure click drop","192.168.17.103_6379");
           $dropbhgSERPUrl ="https://find.vplay-fuel.com/results.aspx?q=".$search."&gd=SY1003522&searchsource=69".'&hello=2';
           header('Location: '.$dropbhgSERPUrl);
           ob_end_flush();
           exit();
        }
    }/*else{
       if (isset($_GET['debug'])){
           var_dump('Invalid feedId');
           die();
       }
   }*/
}

if($advid == 19880){

    $usBankRedis = new Redis();
    $usBankRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $hash = $usBankRedis->hgetall("19880_keywords");
    $random_key = array_rand($hash);
    $usBankkeywordID = $hash[$random_key];
    $search = $search_keyword = $random_key;//keyword is set as a key
    //Set macros
    $redirect = str_ireplace('{_dskeywordid}', $usBankkeywordID, $redirect);
    $redirect = str_ireplace('{_dssearchterm}', $search, $redirect);

}

if ( ($advid == 20638 || $advid == 21734 )&& !empty($category_id)) {
    if($_GET["debug"]){
        var_dump("ADVID IS ".$advid);
        var_dump("CAT ID".$category_id);
    }
    //pick a keyword
    $redisForChannelWiseKeywords = new Redis();
    $redisForChannelWiseKeywords->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
    $rediskeyForChannelWise =  "chanelKeywordsFor_".$advid;
    $getKeywords = $redisForChannelWiseKeywords->hGet($rediskeyForChannelWise,$category_id);
    if(empty($getKeywords)) {
        $search = $search_keyword =  "kindle+store";
        //var_dump("SEARCH IS ".$search);
    } else {
        $getKeywords = json_decode($getKeywords);
        $search = $search_keyword = empty($getKeywords) ? "kindle+store" : $getKeywords[array_rand($getKeywords)];
        //var_dump("SEARCH IS ".$search);
    }

}

if ($advid == 13425 ) { // Edmunds account check only for blacklist Ip
    // get utm from redis
    $redisEdmund = new Redis();
    $redis_edmund = $redisEdmund->pconnect($config['redis_ip_for_edmund'],$config['redis_port_for_edmund']);
	if(!$redis_edmund){
		click_drop_log(__FILE__,__LINE__,"redis Failure","192.168.17.103_6380");
	}
    //get utm source value
    $parts = parse_url($redirect);
    parse_str($parts['query'], $query);
    if( isset( $query['utm_source']) ) {

        switch ($query['utm_source']){

            case 'adyield':
                $redirect = $redirect."&utm_adgroup=".$redisEdmund->sRandMember('edmunds_ad_yield_domains');
                break;
            default:
                $redirect = $redirect."&utm_adgroup=".$redisEdmund->sRandMember('edmunds_admedia_domains');
        }
    }

    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']!="") {
        $click_ip_address = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
    } else {
        $click_ip_address = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ?  $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
    }

    if ($click_ip_address && $click_ip_address != '') {
        if (in_array($click_ip_address, $EdmundsBlacklistIps)) {
            click_drop_log(__FILE__,__LINE__,"Edmunds Blacklist IP","http://www.items.com");
            header("Location: http://www.items.com");
            ob_end_flush();
            die;
        }
    }
}

if($campaign_id == 60427){
    die();
}
if (  $campaign_id == "42973" || $campaign_id == 42973 ) {
    click_drop_log(__FILE__,__LINE__,"Click Drop Due to campaign id $campaign_id","");
    ob_end_flush();
    die;
}


if (!$redirect) {
    click_drop_log(__FILE__,__LINE__,"Empty Redirect Link","https://www.leisure.com");
    header('Location: https://www.leisure.com');
    ob_end_flush();
    die;
}

$ssid = isset($decrypt_mc[16]) ? $decrypt_mc[16] : "";
if($ssid=="[SUBID]"){
	$ssid = "";
}
/*if(isset($decrypt_mc[17])){
    if ( $decrypt_mc[17] == 1 ) {
        $static_link = $decrypt_mc[17]; // Static link used for adcenters
    }
} else {
	$static_link = 0;
}*/

$static_link = (isset($decrypt_mc[17]) && $decrypt_mc[17] == 1) ? $decrypt_mc[17] : 0;


if(isset($decrypt_mc[18])){
	$aff_name = $decrypt_mc[18]; // Affiliate name
} else {
	$aff_name = '';
}

$domain = '';
$rtb_native = false;

$clickerip = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? ( (filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) ? ip2long_v6($_SERVER['HTTP_X_FORWARDED_FOR']) : sprintf('%u', ip2long($_SERVER['HTTP_X_FORWARDED_FOR'])) ) : '';

$clickerua = isset($_SERVER['HTTP_USER_AGENT']) ? urlencode($_SERVER['HTTP_USER_AGENT']) : '';
if($_SERVER['HTTP_X_FORWARDED_FOR'] =="192.168.100.125"){
	$clickerip = sprintf('%u', ip2long("199.27.174.35"));
}

$redis_db = new Redis();
$redis_connect = $redis_db->pconnect($config['redis_ip_for_campaigns'],$config['redis_port_for_campaigns']);
//$redis_connect = $redis_db->pconnect('192.168.'.'30.106',6378);

if(!$redis_connect){
	click_drop_log(__FILE__,__LINE__,"redis Failure","127.0.0.1_22122");
}
if($static_link){
    if ( empty($search) ) {
        $search = isset($_GET['search']) ? $_GET['search'] : $search;
    }
	$subid = isset($_GET['aid']) ? $_GET['aid']: $subid;
        if(!empty($oos_serp_aff)){
            $subid = $oos_serp_aff;
        }
	$sub_subid = isset($_GET['subid']) ? $_GET['subid']: "";
	$domain = isset($_GET['domain']) ? $_GET['domain']: "";

	if($sub_subid == '[SUBID]')
		$sub_subid = '';
	if($domain == '[DOMAIN]')
		$domain = '';

	// Is the click from rtb_native?
	if(isset($_GET['rtb_native']) && $_GET['rtb_native'] == 1)
		$rtb_native = true;
}

if($static_link){
	if($cpc==0){
	    if (empty($_GET['b'])) {
            $cpm = round($redis_db->hGet('t_campaign_'.$campaign_id, 'bid'), 3) ;
        } else {
            $cpm = $_GET['b']/1000;
        }
        if($cpm >=0.001){
            $cpc = $cpm;
        }
	}

	//if (!$unique_clickid) {
        $padded_cid = $campaign_id;
        if(strlen($padded_cid)<5){
            for($i=strlen($padded_cid); $i<6; $i++){
                $padded_cid = "0".$padded_cid;
            }
        }
        $unique_clickid = time().rand(1000000,9999999).$padded_cid;
    //}

	$redirect = str_ireplace('[query]', urlencode($search), $redirect);
	$redirect = str_ireplace('{query}', urlencode($search), $redirect);
	$redirect = str_ireplace('[keyword]', urlencode($search), $redirect);
	$redirect = str_ireplace('{keyword}', urlencode($search), $redirect);
	$redirect = str_ireplace('[PLACEMENT]', 1, $redirect);
	$redirect = str_ireplace('{PLACEMENT}', 1, $redirect);
	$redirect = str_ireplace('[AID]', $subid, $redirect);
	$redirect = str_ireplace('{AID}', $subid, $redirect);
	$redirect = str_ireplace('[SUBID]', $sub_subid, $redirect);
	$redirect = str_ireplace('{SUBID}', $sub_subid, $redirect);
	/*$redirect = str_ireplace('[UID]', $unique_clickid, $redirect);
	$redirect = str_ireplace('{UID}', $unique_clickid, $redirect);*/
	// data for conversions s2s tracking
    //$redirect .= "&pbd=$campaign_id-$creative_id-$subid";
    $amzn_clickid = "";
    if( in_array($advid,[20378,21610]) ) {
        $amzn_clickid = $clickid;
    }
    $clickid = $unique_clickid;
}

if($advid == 18769) {

    /*$overstock_cid_map = array(90686 => 335985,90687 => 335986,90688 => 335987,90689 => 335991,90691 => 335992,90692 => 335988,90693 => 335993,90694 => 335994,90695 => 335989,90696 => 335995,90697 => 335996,90698 => 336000,90699 => 336001,90700 => 336002,90701 => 336003,91390 => 336004,90886 => 336005);
    $map_id = isset($overstock_cid_map[$campaign_id]) ? $overstock_cid_map[$campaign_id] : $overstock_cid_map[90686];*/
    //get CID from the campaign name,
    $campaign_name = !empty($campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name'))
        ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name') : "Search_100_BedBathBeyond_PKW_336003";//default Search_100

    $explode_campaign_name = explode('_',$campaign_name);
    $map_id = end($explode_campaign_name);
    $redirect = str_ireplace('{cid}', $map_id, $redirect);

}
//Overstock CId changes
if($advid == 20805) {
    //get CID from the campaign name,
    $campaign_name = !empty($campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name'))
        ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name') : 12345;//default cid value of this campaign Search_100_41_Overstock_PKW_Nonbrand
    if(!empty($campaign_name)){
        $explode_campaign_name = explode('_',$campaign_name);
        $map_id = end($explode_campaign_name);
        if (filter_var($map_id, FILTER_VALIDATE_INT) === false) {// if last element of campaign name is not a valid int value then change mapid with default  id
            $map_id = 12345;//default map id
        }
        $redirect = str_ireplace('{cid}', $map_id, $redirect);
    }
}
/////////// Forensiq pre-bid check ////////////////
$fqp = isset($_GET['fqp']) ? $_GET['fqp'] : false;  // if fqp parameter is present forensiq pre bid has been checked
$fqScore = 0;

$adv_fornsiq_setting = $rediswrite->get("fornsiq_prebid_{$advid}");
if(!empty($adv_fornsiq_setting) && $adv_fornsiq_setting == 1  && $advid == 13425){//Edmunds only
    $cfp = $redis_db->hMGet('t_campaign_'.$campaign_id, ['cfp_active', 'adv_drop_url']);

    if ($cfp['cfp_active']) {
        include 'lib/php/api/Forensiq/ForensiqAPI.php';
        $forensiqAPI = new ForensiqAPI();

        $params = array(
            'ip' => $_SERVER['HTTP_X_FORWARDED_FOR'],
            'rt' => 'click',
            'seller' => $subid,
            'ua' => $_SERVER['HTTP_USER_AGENT'],
            'cmp' => $campaign_id
        );

        $fqvalue['a'] = $subid;
        $fqvalue['c'] = $campaign_id;
        $fqvalue['x'] = '';

        try {
            $fqScore = $forensiqAPI->preBid($params);
            $fqvalue['s'] = $fqScore;
        } catch (Exception $e) {
            $fqvalue['s'] = -1;
            $fqvalue['e'] = $e->getMessage();
        }

        if (!empty($_GET['debug']) && $_GET['debug'] == 'fq') {
            $forensiqAPI->printDebug();
            die;
        }

        $fqvalue = json_encode($fqvalue);
        $rediswrite->rPush('pop_log_fq_' . date('Ymd'), $fqvalue);

        // Forensiq Pre-Bid score: 0-64 - safe
        if ($fqScore > 64 ||( isset($_GET['debug']) &&  $_GET['debug'] == "fqp_failed") ) {
			$reason = 'Failed Foreniq Prebid Score';
			click_drop_log(__FILE__,__LINE__,$reason,"redirect to default");
            redirect_home(1, "Failed Foreniq Prebid Score: " . $fqScore, $cfp['adv_drop_url']);
        }
    }
}
////////////////////////////////////////////////////

///////////////////////////////////////////////////
///////////// IAS Prebid check ////////////////////
///Edmund = 13425/////Meredith = 14436////Glam =14951////////Mutually =15135////360daily =15191///motortrend=15196///
$adv_ias_setting = $rediswrite->get("ias_prebid_{$advid}");
//if(!empty($adv_ias_setting) && $adv_ias_setting==1 ){
if(0){
	$drop_click = true;
	$ias_drop_click_url = "";
	$ias_access_token = $rediswrite->get("ias_prebid_token_ede2df3r3f");

	if(!$ias_access_token){
		if (!empty($_GET['debug'])){
			echo "Get token from IAS<br>";
		}

		$access_token_json = get_ias_prebid_token();
		if($access_token_json){
			$access_token_arr = json_decode($access_token_json, true);
			$ias_access_token = $access_token_arr['access_token'];
			$token_expires_in = (int) $access_token_arr['expires_in'];

			try{
				$rediswrite->setEx("ias_prebid_token_ede2df3r3f", $token_expires_in-30, $ias_access_token);
			}
			catch(Exception $e){
				if (!empty($_GET['debug'])){
					echo "Error: ".$e->getMessage()."<br>";
				}
			}
		}
	}

	if($ias_access_token){
		if (!empty($_GET['debug'])){
			echo "call prebid now<br>";
		}

		$ias_prebid_resp = get_ias_prebid_segments($ias_access_token, $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_REFERER']);

		if (!empty($_GET['debug'])){
			print_r($ias_prebid_resp);
		}
		$aff_id = !empty( $subid ) ? $subid : 0 ;
		$ssid = !empty( $ssid ) ? $ssid : '' ;
		$ias_data = json_encode( array('adv_id'=>$advid, 'aff_id'=>$aff_id,'sub_id'=>$ssid, 'campaign_id'=>$campaign_id,'ip'=>$_SERVER['HTTP_X_FORWARDED_FOR'], 'ua'=>$_SERVER['HTTP_REFERER']) );
		if($ias_prebid_resp){
			$ias_prebid_arr = json_decode($ias_prebid_resp, true);
			if(isset($ias_prebid_arr['segment_codes']) && !empty($ias_prebid_arr['segment_codes']) && in_array("ESAIPH", $ias_prebid_arr['segment_codes'])){
				$drop_click = false;
				$rediswrite->rpush("ias_prebid_success_".date('Ymd'), $ias_data);
			} else {
				$rediswrite->rpush("ias_prebid_failed_".date('Ymd'), $ias_data);
			}
		}
	}

	if($drop_click){
		if (!empty($_GET['debug'])){
			echo "IAS says drop click<br>";
		}

		$cfp = $redis_db->hMGet('t_campaign_'.$campaign_id, ['cfp_active', 'adv_drop_url']);

		if($cfp && isset($cfp['adv_drop_url']) && !empty($cfp['adv_drop_url'])){
			$ias_drop_click_url = $cfp['adv_drop_url'];
		}
		else{
			$ias_drop_click_url = "https://socialsearch.com?dc=ias";
		}
		$reason = 'Failed IAS Prebid Check';
		click_drop_log(__FILE__,__LINE__,$reason,"redirect to default");
		redirect_home(1, "Failed IAS Prebid Check", $ias_drop_click_url);
		//header("Location: $ias_drop_click_url");
		//exit(0);
	}else{
		if (!empty($_GET['debug'])){
			echo "Click passed IAS check<br>";
		}
	}
}

///////////////////////////////////////////////////

$cookie = isset($_COOKIE['cad']) ? trim($_COOKIE['cad']) : '';
if(isset($_GET['rurl']) && $_GET['rurl']!=""){
	$redirect = $_GET['rurl'];
}

if( in_array($advid,[20378,21610]) ) {//to check original clickid time
    $clickid = $amzn_clickid;
}

$search_timestamp = substr($clickid, 0, 10);

if($clickid && $campaign_id != 57034 && !$quicklaunch && $product_type != 24 && !in_array($given_aff_id,[117562,122450])){//exclude a few pubs.
	if( $search_timestamp< (time() - 900) ){ // Click older than 15 minutes..drop it
		$cpc = 0;
        $errorForClickTable = "older click";
        if ( isset($_GET['debug'])) {
            var_dump('Found that the click is older than 15 mins as time is '.date("Y-m-d H:i:s", $search_timestamp));
        }
	} else {
        if ( isset($_GET['debug'])) {
            var_dump('Found that the click is NOT older than 15 mins as time is '.date("Y-m-d H:i:s", $search_timestamp));
        }
    }
}

if ( isset($_GET['debug'])) {
    var_dump('Found that the clickid = '.$clickid);
}

$date = date("Y-m-d");
$adv_table = "advtrack_".date("Ymd");


$frckey = "adv_frc_".date("Ymd").$clickerip;
$cache_expire = strtotime('tomorrow');
$ipLimitForCampaign = $ipLimitRedis->hget($frckey,$campaign_id);
if(empty($ipLimitForCampaign)){
    $ipLimitRedis->hset($frckey,$campaign_id,1);
    $ipLimitRedis->expireAt($frckey,$cache_expire);
}else{
    $ipLimitRedis->hIncrBy($frckey,$campaign_id,1);
}

$searchTimestamp = substr($clickid, 0, 10);
$clickCacheExpire =  $searchTimestamp +1800;//in 30 min from search
$cid_key = "clicked_".date("Ymd").$clickid."_".$clickCacheExpire;
$repeat_click = 0;
$keys = $ipLimitRedis->get($cid_key);
$repeat_click = empty($keys) ? 0 : 1;
if(!$repeat_click){
    $ipLimitRedis->set($cid_key,1);
    $ipLimitRedis->expireAt($cid_key,$clickCacheExpire);
}
if(!empty($repeat_click) && $campaign_id != 57034 && !$quicklaunch && $product_type != 24 && !in_array($given_aff_id,[117562,122450])){ // This clickid has already been clicked on
	$cpc = 0;
    $errorForClickTable = "repeated click";
    if ( isset($_GET['debug'])) {
        var_dump('Found a repeat_click');
        var_dump($repeat_click);
        var_dump($campaign_id);
        var_dump($quicklaunch);
        var_dump($product_type);
    }
}

$userClickIP = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
//for testing BLACKLIST ip replace user IP via manual input
if (isset($_GET['test_blacklist_ip'])) {
    $userClickIP = $_GET['test_blacklist_ip'];
}

if(filter_var($userClickIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
    $ipInt = ip2long_v6($userClickIP);
}else{
    $ipInt = ip2long($userClickIP);
}
///
$blacklistRedis = new Redis();
$connected = false;
$whitelist = $blacklisted = 0;

try {
    $connected = $blacklistRedis->connect($config['blacklist_ip_server'], $config['blacklist_ip_port']);
    // verify redis is actually alive
    if ($connected) {
        $connected = in_array($blacklistRedis->ping(), ['PONG', '+PONG', true], true);
    }

} catch (Exception $e) {
    if (isset($_GET['debug'])) {
        var_dump('Blacklist redis connection fail '.$e->getMessage());
    }
    $connected = false;
}
// check IP for whitelist
if ($connected) {
    try {
        $whitelist = $blacklistRedis->sIsMember('ivt_ip_whitelist', $ipInt);
    } catch (Exception $e) {
        if (isset($_GET['debug'])) {
            var_dump('Blacklist redis get data fail '.$e->getMessage());
        }
        $whitelist = 1; // fail open
    }
} else {
    if (isset($_GET['debug'])) {
        var_dump('Blacklist redis connection fail, So IVT is getting skip');
    }
    $whitelist = 1; // fail open
}
if (isset($_GET['debug'])) {
    var_dump('Conection is '.$connected.' whitelist is'.$whitelist);
}
if(!$whitelist){ //Skip for whitelist IP
    if($blacklistRedis->sIsMember('blacklist_ips', $ipInt)){
        $cpc = 0;
        $errorForClickTable = "Blacklist IP";
        $blacklisted = 1;
    }
}

//Statefarm blacklist Fixes not check whitelist here
if($advid == 17237) {
    if($blacklistRedis->sIsMember('statefarm_blacklist_ips', $ipInt)){
        $cpc = 0;
        $errorForClickTable = "Statefarm Blacklist IP";
        $blacklisted = 1;
    }
    if (isset($_GET['debug'])) {
        var_dump('Statefarm blacklist check: '.($blacklistRedis->sIsMember('statefarm_blacklist_ips', $ipInt) ? 'blacklisted' : 'not blacklisted'));
    }
}

//check advertiser level  click ip cap

/*$advClickCapRedis = new Redis();
$advClickCapRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
$advClickCapLimit = $advClickCapRedis->hget('adv_ip_click_cap',$advid);
//if cap has positive number then that is cap value, In no limit it will be -1 
if($advClickCapLimit >=0){
    $advClickCapKey = "clickcap_".date("Ymd").$clickerip;
    $cache_expire = strtotime('tomorrow');
    //check clickserved with advertiser for an IP
    $advertiserClickCounter = $ipLimitRedis->hget($advClickCapKey,$advid);
    $advertiserClickCounter = empty($advertiserClickCounter) ? 0 : $advertiserClickCounter;
    if($advertiserClickCounter >= $advClickCapLimit){
        //drop traffic
        $cpc = 0;
        $errorForClickTable = "advcap reached";
    }else{
        if(empty($advertiserClickCounter)){
            $ipLimitRedis->hset($advClickCapKey,$advid,1);
            $ipLimitRedis->expireAt($advClickCapKey,$cache_expire);
        }else{
            $ipLimitRedis->hIncrBy($advClickCapKey,$advid,1);
        }
    }
    
}*/

/*if ($advid == 15618 ) { // Discover Advertiser

    $redirect = str_replace('{ignore}','',$redirect);

    if($is_mobile_browser){

        //replace desktop with mobile
        $redirect = str_ireplace('AdMedia__Brand__Desktop', 'AdMedia__Brand__Mobile', $redirect);
        $redirect = str_ireplace('AdMedia__NB__Desktop', 'AdMedia__NB__Mobile', $redirect);

        $redirectExplode = explode('acmpgn=',$redirect);
        $redirectFirstPart = $redirectExplode[0].'&acmpgn=';
        $redirectExplodePart2 = explode('&sgm=',$redirectExplode[1]);
        $redirectSecondPart = '&sgm='.$redirectExplodePart2[1];
        $middlePart = $redirectExplodePart2[0];

        $getArr = explode("}{",$middlePart);
        $toReplace = array("ifnotmobile:","ifmobile:","{","}");
        $arrAcpgn = array();
        foreach ($getArr as $val ) {
            if ( strpos($val,"ifnotmobile") !== false ) {
                $arrAcpgn['desktop'] = str_replace($toReplace,"", $val);
            }
            if ( strpos($val,"ifmobile") !== false ) {
                $arrAcpgn['mobile'] = str_replace($toReplace,"", $val);
            }
        }


        $redirect = $redirectFirstPart . $arrAcpgn['mobile'].$redirectSecondPart;

    }else {
        //replace mobile with desktop
        $redirect = str_ireplace( 'AdMedia__Brand__Mobile','AdMedia__Brand__Desktop', $redirect);
        $redirect = str_ireplace('AdMedia__NB__Mobile','AdMedia__NB__Desktop',  $redirect);

        $redirectExplode = explode('acmpgn=',$redirect);
        $redirectFirstPart = $redirectExplode[0].'&acmpgn=';
        $redirectExplodePart2 = explode('&sgm=',$redirectExplode[1]);
        $redirectSecondPart = '&sgm='.$redirectExplodePart2[1];
        $middlePart = $redirectExplodePart2[0];

        $getArr = explode("}{",$middlePart);
        $toReplace = array("ifnotmobile:","ifmobile:","{","}");
        $arrAcpgn = array();
        foreach ($getArr as $val ) {
            if ( strpos($val,"ifnotmobile") !== false ) {
                $arrAcpgn['desktop'] = str_replace($toReplace,"", $val);
            }
            if ( strpos($val,"ifmobile") !== false ) {
                $arrAcpgn['mobile'] = str_replace($toReplace,"", $val);
            }
        }


        $redirect = $redirectFirstPart . $arrAcpgn['desktop'].$redirectSecondPart;

    }
}*/

if ($advid){

    //$targetId = (!empty($affiliate_set_click_id)) ? $affiliate_set_click_id : ((!empty($aff_clickid) ) ? $aff_clickid : $targetId);

    $targetId = $unique_id;

    /********** Log Advertiser detailed log *******************/
	$osParser = new DeviceDetector\Parser\OperatingSystem();
	$osParser->setUserAgent($search_ua);
	$os = $osParser->parse();
    $os_name = (isset($os['name']) && !empty($os['name'])) ? $os['name'] : "";
    $campaign_name = !empty($campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name'))
        ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name') : "Search_100";//default Search_100
	$httpRef = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']:'';
	$reftopass = (!empty($given_search_ref)) ? $given_search_ref : $httpRef;
    //if($static_link){
		$replace_array = array (
			'[OS]' => urlencode($os_name),
			'{OS}' => urlencode($os_name),
			'[Browser]' => urlencode($browser_name),
			'{Browser}' => urlencode($browser_name),
			'[device]' =>  $device,
			'{device}' =>  $device,
			'[matchtype]' => 'Broad',
			'{matchtype}' => 'Broad',
			'[campaign_id]' => $campaign_id,
			'{campaign_id}' => $campaign_id,
            '[campaign_name]' => $campaign_name,
            '{campaign_name}' => $campaign_name,
            '{creativeid}'   => $creative_id,
            '[creativeid]'   => $creative_id,
			'[geo]' => $country,
			'{geo}' => $country,
			'[loc_physical_ms]' => $country,
			'{loc_physical_ms}' => $country,
			'[targetid]' => $targetId,
			'{targetid}' => $targetId,
            '[uid]' => $targetId,
            '{uid}' => $targetId,
            '[UID]' => $targetId,
            '{UID}' => $targetId,
            '[keyword]' => urlencode($search),
            '{keyword}' => urlencode($search),
            '[KEYWORD]' => urlencode($search),
            '{KEYWORD}' => urlencode($search),
            '{ref}' => urlencode($reftopass),
            '[ref]' => urlencode($reftopass),
			'{REF}' => urlencode($reftopass),
            '[REF]' => urlencode($reftopass)
		);
		$redirect = str_ireplace(array_keys($replace_array), $replace_array, $redirect);
	//}
	preg_match('/{ifmobile:(.*?)}/i', $redirect, $match);
	if(isset($match[1])){
		if($ifmobile){
			$redirect = str_ireplace('{ifmobile:'.$match[1].'}',$match[1],$redirect);
		}
		else{
			$redirect = str_ireplace('{ifmobile:'.$match[1].'}','',$redirect);
		}
	}
	preg_match('/\[ifmobile:(.*?)\]/i', $redirect, $match);
	if(isset($match[1])){
		if($ifmobile){
			$redirect = str_ireplace('[ifmobile:'.$match[1].']',$match[1],$redirect);
		}
		else{
			$redirect = str_ireplace('[ifmobile:'.$match[1].']','',$redirect);
		}
	}
	preg_match('/{ifnotmobile:(.*?)}/i', $redirect, $match);
	if(isset($match[1])){
		if($ifnotmobile){
			$redirect = str_ireplace('{ifnotmobile:'.$match[1].'}',$match[1],$redirect);
		}
		else{
			$redirect = str_ireplace('{ifnotmobile:'.$match[1].'}','',$redirect);
		}
	}
	preg_match('/\[ifnotmobile:(.*?)\]/i', $redirect, $match);
	if(isset($match[1])){
		if($ifnotmobile){
			$redirect = str_ireplace('[ifnotmobile:'.$match[1].']',$match[1],$redirect);
		}
		else{
			$redirect = str_ireplace('[ifnotmobile:'.$match[1].']','',$redirect);
		}
	}

	$data1 = array(time(), $clickid, $search, $subid, $ssid, $advid, $campaign_id, $adgroup, $creative_id, $cpc, $redirect, urlencode($httpRef), $clickerip, $type, $cookie, $position, $clickerua, date("Y-m-d H:i:s"), $_SERVER['SERVER_NAME'], 0, '');
	if($cpc && REDIS_WRITE)
	{
            if(!$oosSerpLink){
                $rediswrite->rpush($adv_table, json_encode($data1));
            }
            
	}
    if($type != "CPM"){
        $data2 = array($date, $advid, $campaign_id, $adgroup, $creative_id, $subid, 1, $cpc, '');
        if($cpc && REDIS_WRITE)
        {
            if(!$oosSerpLink){
                $rediswrite->rpush("adv_summary_".date("Ymd"), json_encode($data2));
            }
            if($rtb_native)
            {
                // Data for inserting into rtb_native_detail
                $native_list = "rtb_native_detail_".date("Ymd");
                $rtb_native_data = array($campaign_id, $adgroup, $creative_id, $subid, $sub_subid, $domain, $cpc);
                $rediswrite->rpush($native_list, json_encode($rtb_native_data));
            }
            $osParser->setCache(new \DeviceDetector\Cache\RedisCache($rediswrite));
            $browserParser->setCache(new \DeviceDetector\Cache\RedisCache($rediswrite));
        }

        // Create object for data to be posted //
        $dataObj = new stdClass();
        $dataObj->cid = $campaign_id;
        $dataObj->crid = $creative_id;
        if($rtbRedirect){
            parse_str(parse_url($rtbRedirect, PHP_URL_QUERY), $rtbParams);
            $dataObj->pid = 'RTB_'.$rtbParams['ssp_id'];
        } else {
            if ($given_subid) {
                $dataObj->pid = $subid . '_' . $given_subid;
            } else {
                $dataObj->pid = $subid;
            }
        }
        $dataObj->country = $country;
        $dataObj->os = isset($os['name']) ? $os['name'] : '';
        $dataObj->browser = $browser['name'];
        $dataObj->bid_price  = $cpc;
        $dataObj->keyword = ($isKeywordReportDisabled) ? $aff_keyword : $search;
        $dataObj->aff_clickid = $aff_clickid;


        /////////// Reduce click counter ////////////////
        if ($cpc) {
            $redis_counter = new Redis();
            $redis_counter->pconnect($config['redis_ip_for_click_counter'],$config['redis_port_for_click_counter']);
            try {
                $redis_counter->hIncrBy('campaign_CPC_allowable_clicks', $campaign_id, -1);
            } catch (RedisException $e) {
            }
            /////////////////////////////////////////////////
        }
        $affMetaObj = new stdClass();
        $affMetaObj->affiliate = $affiliate_name;
        $affMetaObj->subid = $affiliate_set_sub_id;
        $affMetaObj->ref = $affiliate_set_ref_id;
        $affMetaObj->clickid = $affiliate_set_click_id;

        if (REDIS_WRITE) {

            //check if paused campaign, and store the info for reco later on.
            $pausedCmpRedis = new Redis();
            $pausedCmpRedis->pconnect($config['short_url_creative_redis'],$config['short_url_creative_redis_port']);
            $isPaused = $pausedCmpRedis->hExists("paused_campaigns", $campaign_id) && $pausedCmpRedis->hGet("paused_campaigns", $campaign_id);

            if ( $isPaused ) {
                $pausedObj = new stdClass();
                $pausedObj->cid = $campaign_id;
                $pausedObj->aid = $advid;
                if ( $given_subid ) {
                     $pausedObj->pid = $subid.'_'.$given_subid;
                } else {
                     $pausedObj->pid = $subid;
                }
                $pausedObj->affiliate = $affiliate_name;
                $pausedObj->time = time();

                $rediswrite->rpush("paused_campaigns_" . date("Ymd"), json_encode($pausedObj));

            }

            if ($cpc) {
                if(!$testingClick && !$oosSerpLink){
                    if($rtbRedirect){
                        // Log RTB Contextual clicks here
                        // Processed at admediacrons.com/html/rtb/contextual_ads/placement_clicks.php
                        $rediswrite->rpush("placement_clicks_" . date("Ymd"), json_encode([
                            'placement_id'  => $rtbParams['placement_domain_id'],
                            'imp_id'        => $rtbParams['iid'],
                            'cca'           => $rtbParams['cca'],
                            'matrix'        => !empty($rtbParams['matrix']) ? $rtbParams['matrix'] : '[]',
                            'timestamp'     => time(),
                            'ssp'           => $rtbParams['ssp_id'],
                            'country'       => $dataObj->country,
                            'os'            => $dataObj->os,
                            'browser'       => $dataObj->browser,
                            'ip'            => $search_ip
                        ]));
                    } else {
                        // Log All other clicks here
                        $rediswrite->rpush("advDetailLog_xml_" . date("Ymd"), json_encode($dataObj));
                    }
                }
            }
            if(isset($product_type) && !empty($product_type)){
                $dataObj->product_type = $product_type;
                $dataObj->product_sub_id = $product_sub_id;
                if(!$testingClick  && !$oosSerpLink){
                    $rediswrite->rpush("affDetailLog_xml_" . date("Ymd"), json_encode($dataObj));
                }
            }
            //store affiliate set variables like  sub id, ref id and click id
            if(!$testingClick  && !$oosSerpLink){
                $rediswrite->rpush('affiliate_meta_'. date("Ymd"), json_encode($affMetaObj));
            }

            ///////////////////////////////////////////////
            //if ($given_subid || $affiliate_set_sub_id ) {
                $clickCpcSummaryObj = new stdClass();
                $clickCpcSummaryObj->date = date("Y-m-d");
                $clickCpcSummaryObj->time = time();
                $clickCpcSummaryObj->camp_id = $campaign_id;
                $clickCpcSummaryObj->adv_id = $advid;
                $clickCpcSummaryObj->affiliate_id = $given_aff_id;
                $clickCpcSummaryObj->cpc = $cpc;
                $clickCpcSummaryObj->affiliate_set_click_id = (!empty($affiliate_set_click_id)) ? $affiliate_set_click_id : $aff_clickid;
                $clickCpcSummaryObj->affiliate_set_ref_id = $affiliate_set_ref_id;
                if ( $affiliate_set_sub_id ) {
                    $clickCpcSummaryObj->affiliate_set_sub_id = $affiliate_set_sub_id;
                } else if ( $given_subid ) {
                    $clickCpcSummaryObj->affiliate_set_sub_id = $given_subid;
                }
                $clickCpcSummaryObj->status = ($cpc) ? 1 : 0;
                $clickCpcSummaryObj->device = (isMobileDevice()) ? 1 : 0;
                //store affiliate cpc data
                if(!$testingClick  && !$oosSerpLink){
                    //Not needed as we are calculate same from raw click table
                    //$rediswrite->rpush('aff_cpc_summary_'. date("Ymd"), json_encode($clickCpcSummaryObj));
                }
            //}

            if ( $cpc ) {
                // Record IP to click count
                $redisIPWriteCheck = new Redis();
                $redisIPWriteCheckConn = $redisIPWriteCheck->pconnect($config['redis_ip_for_feed_validation'],$config['redis_port_for_feed_validation']);

                if ($redisIPWriteCheckConn) {
                    $feedId = (isset($feedId) && !empty($feedId)) ? $feedId : '';
                    $searchStr = preg_replace("/[^a-zA-Z0-9]/", "", $search);
                    $redisIPWriteCheck->incr($feedId . '_' . date('Y-m-d') . '_' . $search_ip . '_' . $searchStr);
                    $redisIPWriteCheck->expire($feedId . '_' . date('Y-m-d') . '_' . $search_ip . '_' . $searchStr, 86400);
                } else {
                    click_drop_log(__FILE__, __LINE__, "redis Failure", "127.0.0.1_22123");
                }
            }
        }

    }

}

if (isset($_GET['debug']) && $_GET['debug']=="checkSearch2Info") {
    var_dump("premium is ");
    var_dump($premium);
    var_dump("search_2_traffic is ");
    var_dump($search_2_traffic);
    var_dump("cpc is ");
    var_dump($cpc);
    die;
}

if( $advid == 20378 || $advid == 21610) {
    //For amazon set of advertisers, check error and null route
    $amazonRedirects = [
        20378 => "https://amazon.com",
        21610 => "https://amazon.co.uk"
    ];

    //added for sovrn not to drop click, capture as dropped click but go through properly
    if (isset($amazonRedirects[$advid])
                && in_array($errorForClickTable, ["Blacklist IP","repeated click", "older click"], true)
                && !in_array($given_aff_id,[117562,122450]) ) {

        //header("Location: " . $amazonRedirects[$advid]);
        if (isset($_GET['debug']) && $_GET['debug']=="dropInfo") {
            var_dump('error For drop = '.$errorForClickTable);
            die;
        }
        redirect_home(0, $errorForClickTable, $amazonRedirects[$advid]);//mark fruad for amazon not drop
        exit;
    }
}

//added for sovrn not to drop click, capture as dropped click but go through properly
if ( $blacklisted && !$search_2_traffic && !$cpc && !in_array($given_aff_id,[117562,122450,120347])) {
    // click needs to be dropped and not sent to the advertiser
    // since cpc = 0 for time out on click or multiple click ip reason or blacklisted IP

    $cfp = $redis_db->hMGet('t_campaign_'.$campaign_id, ['cfp_active', 'adv_drop_url']);

    if($cfp && isset($cfp['adv_drop_url']) && !empty($cfp['adv_drop_url'])){
        $click_drop_url = $cfp['adv_drop_url'];
    }
    else{
        $click_drop_url = "https://socialsearch.com?dc=mip";
    }
    $reason = 'Click Dropped Due to Timeout or Multiple IP';
    if (isset($_GET['debug']) && $_GET['debug']=="dropInfo") {
         var_dump('Dropping the Click because cpc = 0');
         var_dump('blacklisted = '.$blacklisted);
         var_dump('search_2_traffic = '.$search_2_traffic);
         var_dump('cpc = '.$cpc);
         var_dump('given_aff_id = '.$given_aff_id);
         var_dump("premium is ");
         var_dump($premium);
         die;
    }
    click_drop_log(__FILE__,__LINE__,$reason,"redirect to default");
    if ( $blacklisted ) {
        if( !empty($fallbackUrl) ) {
            $click_drop_url = $fallbackUrl;
        }
        redirect_home(0, "Click Dropped Due to Timeout or Multiple IP", $click_drop_url);//status = 0 for fraud
    } else {
        redirect_home(1, "Click Dropped Due to Timeout or Multiple IP", $click_drop_url);//status = 1 for drop
    }
}

log_clicks(0);//capture valid click

if (REDIS_WRITE) {

	//log all the redirects here
	$outDataObj = new stdClass();
	$outDataObj->cid = $campaign_id;
	$outDataObj->advertiser_id = $advid;
	$outDataObj->redirect = $redirect;
	$outDataObj->static_link = $static_link;
	$outDataObj->affiliate_id = $subid;
	$outDataObj->incoming = (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	$outDataObj->time = time();
	$rediswrite->rpush("outgoing_cad_redirects_" . date("Ymd"), json_encode($outDataObj));

    //capture IP wise click Data for sovrn campaign wise
    $userClickIP = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
    if ($given_aff_id == 117562 && !empty($campaign_id) && !empty($userClickIP)){
        if(filter_var($userClickIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $ipInt = ip2long_v6($userClickIP);
        }else{
            $ipInt = ip2long($userClickIP);
        }
        $sovrnRediskeyForCampaignIpCounter = "sovrn_camp_".date("Ymd")."_".$campaign_id;
        $rediswrite->hincrby($sovrnRediskeyForCampaignIpCounter,$ipInt,1);
    }
}
//capture social sep link when redirecting to social search
if($oosSerpLink){
    $seprObj = new stdClass();
    $seprObj->date = date("Y-m-d");
    $seprObj->time = time();
    $seprObj->affiliate_id = $given_aff_id;
    $seprObj->affiliate_sub_id = $subid;
    $seprObj->redirect = $redirect;
    $rediswrite->rpush("oos_serplink_" . date("Ymd"), json_encode($seprObj));
}


if(isset($_GET['rtb_cad']) && !empty($_GET['rtb_cad']) && isset($_GET['rtb_cad_bid']) && !empty($_GET['rtb_cad_bid'])){
    $mkey = "rtb_spent_counter_".$affiliate_name."_".$_GET['rtb_cad'];
    $creative_redis = new Redis();
    $rediswrite->incrByFloat($mkey,(float)$_GET['rtb_cad_bid']);
}

//get merchant click counter for given valid advertiser id
$validAdvId = array(14436,15127,15410);
if(in_array($advid,$validAdvId) && !empty($clickMerchant)){
    $date = date('Ymd');
    $mkey = $advid.'_clickcounter_'.$date.'_'.$clickMerchant;
    $setExpire = false;
    if(!$rediswrite->exists($mkey)){
        $setExpire = true;
    }
    $rediswrite->incr($mkey);
    if($setExpire){
        $rediswrite->expire($mkey,86400);
    }
    $counter = $rediswrite->exists($mkey) ? $rediswrite->get($mkey) : 0;
    if( ($advid == 14436 || $advid == 15127)  && $counter > 20000){
        $dropbhgSERPUrl ="https://find.vplay-fuel.com/results.aspx?q=".$search."&gd=SY1003522&searchsource=69".'&hello=3';
        $reason = "Click Drop Due to counter Reach for meredith";
        click_drop_log(__FILE__,__LINE__,$reason,$dropbhgSERPUrl);
        header("Location: $dropbhgSERPUrl");
        ob_end_flush();
        exit(0);
    }
}

if ( $advid == 2175 && $given_aff_id == 117562){ // connexity advertiser and sovrn affiliate from RTB

    $redisIPWrite = new Redis();
    $redisIPWriteConn = $redisIPWrite->pconnect($config['redis_ip_for_feed_validation'],$config['redis_port_for_feed_validation']);

    $connexity_click_ip = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ?
                            ( (filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) ? ip2long_v6($_SERVER['HTTP_X_FORWARDED_FOR']) : sprintf('%u', ip2long($_SERVER['HTTP_X_FORWARDED_FOR'])) )
                            : '';

    $redisIPWrite->sadd('connexity_ip_'. date("Ymd"),$connexity_click_ip);
}

if ( $advid != 2175 && $given_aff_id == 117562){ // Non connexity advertisers and sovrn affiliate from RTB

    $redisIPWrite = new Redis();
    $redisIPWriteConn = $redisIPWrite->pconnect($config['redis_ip_for_feed_validation'],$config['redis_port_for_feed_validation']);

    $connexity_click_ip = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ?
        ( (filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) ? ip2long_v6($_SERVER['HTTP_X_FORWARDED_FOR']) : sprintf('%u', ip2long($_SERVER['HTTP_X_FORWARDED_FOR'])) )
        : '';

    $redisIPWrite->sadd('sovrn_clickip_'. date("Ymd").'_'.$campaign_id,$connexity_click_ip);
}

if ( $advid == 15810 || $advid == 15483 || $advid == 16184) { // Nissan, Nike, Geico
    // Have this go to cad2.php to set the DV tag and redirect to landing page of the advertiser.
    $redirect = 'https://click.validclick.net/cad2.php?adv='.$advid.'&cmp='.$campaign_id.'&oos='.$oos.'&rdr='.urlencode($redirect);

}

/*if ( in_array($advid,[13421,20934]) )  { // hearst and hearstCPA accounts
    // Have this go to cad2.php to set the DV tag and redirect to landing page of the advertiser.
    $redirect = 'https://ssuserverification.com/rdr.php?r='.urlencode($redirect);

}*/

if (($subid == 118659 || $subid == 118687 ) && $advid == 10112 && $affiliate_set_click_id) { // items.com track the affiliate pch_items
    $redirect .= '?subid='.$subid.'&clickid='.$affiliate_set_click_id;
}

if ( $caketraffic ) {
    $redirect = 'https://'.$caketraffic.'/d?url='.$redirect;
}

//Atkins  - check for the Android or iOS and redirect it to respective playstores.
/*if ( $advid == 16958 ) {
    $atkins_campaign_name = !empty($campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name'))
        ? $campaign_info_redis->hGet('t_campaign_'.$campaign_id, 'name') : "Search_100_Atkins_Google";//default Search_100_Atkins_Google
    if($ifmobile) {
        $ua = strtolower($ua);
        if(stripos($ua,'android') !== false) {
            $redirect = "https://play.google.com/store/apps/details?id=com.atkins.android.carbcounter&hl=en&utm_source=admedia&utm_campaign=".$atkins_campaign_name;
        } elseif(stripos($ua,'iphone') !== false || stripos($ua,'mac os') !== false || stripos($ua,'macintosh') !== false) {
            $redirect = "https://itunes.apple.com/us/app/atkins-carb-tracker/id583475512?ls=1&mt=8&utm_source=admedia&utm_campaign=".$atkins_campaign_name;
        }
    }
}

//wayfair ad rank MNGT-396
if ( $advid == 17099 ) {
    //getCampaign Name
    $campaignName = $campaign_info_redis->hGet('t_campaign_'.$campaign_id,'name');
    $adRankArray = $config['campaign_adranks'];
    list($rankId,$any) = sscanf(strtolower($campaignName),"search_%d_%s");
    $adRankValue = (isset($adRankArray[$rankId]) && !empty($adRankArray[$rankId])) ? $adRankArray[$rankId] : $config['default_campaign_adranks'];
    $redirect .= "&adrank=$adRankValue";
}*/

//replace custom variables
$replace_array = array (
    '{custom1}' => isset($_GET['custom1']) ? urlencode($_GET['custom1']) : '',
    '{custom2}' => isset($_GET['custom2']) ? urlencode($_GET['custom2']) : '',
    '{custom3}' => isset($_GET['custom3']) ? urlencode($_GET['custom3']) : '',
    '{custom4}' => isset($_GET['custom4']) ? urlencode($_GET['custom4']) : '',
    '{custom5}' => isset($_GET['custom5']) ? urlencode($_GET['custom5']) : '',
);
$redirect = str_ireplace(array_keys($replace_array), $replace_array, $redirect);

if(isset($_GET['debug']) && $_GET['debug'] == "ms3rfcv1")
{
    var_dump($redirect);
    var_dump($premium);
    die;
}

if ( $advid == 20638 || $advid == 21734 ) {
    $redirect .= '&overwrite_bid=1';
}

$cleartrust_id =  $campaign_id;
$cleartrust_sub_id =  isset($subid) && !empty($subid) && ($subid !=0) ? $subid : '0';
$cleartrust_ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'click.validclick.net';

if ( !empty($pubClickId) ) {
    $clickid = $pubClickId;
}

$test_pub = false;
$test_pub = in_array($given_aff_id,[119491,120407,119657]);

///Make Cleartrust call for non search 2 and $test_pub accounts only for test phase.
if(!$search_2_traffic && $test_pub) {

    $ct_resp = get_cleartrust_score($_SERVER['HTTP_X_FORWARDED_FOR'],
        $cleartrust_ref,
        $clickid,
        $cleartrust_id,
        $cleartrust_sub_id,
        $ua);

    if (!empty($_GET['debug'])) {
        var_dump($ct_resp);
    }

}
?>
<!DOCTYPE html>
<html>
<head>

    <meta name="user-agent" content="<?= htmlspecialchars($ua, ENT_QUOTES, 'UTF-8') ?>">
    <meta name="data-useragent" content="<?= htmlspecialchars($ua, ENT_QUOTES, 'UTF-8') ?>">

    <?php if(!$search_2_traffic): ?>

        <?php if($advid == 19280): ?>
            <script id="myAdmediaTag" data-admedia-tagid="<?=$campaign_id?>" src="https://humanaadverification.com/tag.js" type="text/javascript"></script>
        <?php endif; ?>

        <?php     // Hearst specific discovery image tags.
         if($advid == 13421 && $campaign_id == 69762): ?>
                <script src="https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B27429874.331415001;dc_trk_aid=523359663;dc_trk_cid=168523014;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php
        if($advid == 13421 && $campaign_id == 90753): ?>
            <script src="https://ad.doubleclick.net/ddm/trackimpj/N46002.147676WMTWABCPORTLAND0/B30522481.382194861;dc_trk_aid=572998642;dc_trk_cid=205238554;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 69763): ?>
            <script src="https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B27429874.331415001;dc_trk_aid=523689313;dc_trk_cid=168117898;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 69764): ?>
            <script src="https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B27429874.331415001;dc_trk_aid=523326284;dc_trk_cid=168117901;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 71847): ?>
                <script src="https://ad.doubleclick.net/ddm/trackclk/N3727.1687342MATADORNETWORK.COM/B27419864.342888852;dc_trk_aid=534547943;dc_trk_cid=169106288;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 71939): ?>
            <script src="https://ad.doubleclick.net/ddm/trackclk/N3727.1687342MATADORNETWORK.COM/B27419864.342888855;dc_trk_aid=534662883;dc_trk_cid=169106288;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 72148): ?>
            <script src="https://ad.doubleclick.net/ddm/trackclk/N3727.1687342MATADORNETWORK.COM/B27419864.342888858;dc_trk_aid=534913627;dc_trk_cid=169106288;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && in_array($campaign_id,[79218,79219]) ): ?>
            <script src="https://ad.doubleclick.net/ddm/trackimp/N9329.3864123MATADORNETWORK/B28420575.345679282;dc_trk_aid=545490981;dc_trk_cid=183918831;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && $campaign_id == 81769): ?>
            <script src="https:/pixel.adsafeprotected.com/rjss/st/1357105/69894135/skeleton.js__;!!Ivohdkk!jhhf8BWJCf8u22YwfOC5l4KXnWoJtmWPrsb_POY9jT6ajeaGOJMnSxyUwrKwbvMyYwO0mplbj2e4pgHyFM3w4ZY$" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && in_array($campaign_id,[81768,81769]) ): ?>
            <script src="https://pixel.adsafeprotected.com/rjss/st/1357105/69894135/skeleton.js" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && in_array($campaign_id,[116426,116427,116428,116429]) ): ?>
            <script src="https://ad.doubleclick.net/ddm/trackimp/N228601.4532644HEARST-UNIBALL/B34323919.431575034;dc_trk_aid=625472204;dc_trk_cid=243244315;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?" type="text/javascript"></script>
        <?php endif; ?>
        <?php if($advid == 13421 && in_array($campaign_id,[125120,125121]) ): ?>
            <script src="https://pixel.adsafeprotected.com/rjss/st/2858979/93495058/skeleton.js?bidurl=%%PATTERN:url%%"></script> <noscript><img src="https://pixel.adsafeprotected.com/rfw/st/2858979/93495057/skeleton.gif?gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_278}&gdpr_pd=${GDPR_PD}&bidurl=%%PATTERN:url%%" BORDER=0 WIDTH=1 HEIGHT=1 ALT=""></noscript>
        <?php endif; ?>
    <?php endif; ?>
    <?php
    // Bonnier
    if($advid == 6721): ?>
        <script type="text/javascript">
            window.history.forward(1);
            function clicklink() {
                var l = document.getElementById('url');
                l.click();
            }
        </script>
    <?php else: ?>
        <script type="text/javascript">
            window.history.forward(1);
            function clicklink() {
                window.location.href = "<?=$redirect?>";
            }
        </script>
    <?php endif; ?>

    <?php
    if(stristr($_SERVER['HTTP_HOST'], "accoona.com")){
        $ga_domain = "accoona.com";
    } elseif(stristr($_SERVER['HTTP_HOST'], "leisure.com")){
        $ga_domain = "leisure.com";
    } else {
        $ga_domain = "goclicker.com";
    }

    ?>

    <?php
    if($type!="CPC_D"){
        ?>
        <script type="text/javascript" >
            if (window.top !== window.self) {
                document.write = "";
                window.top.location = window.self.location; setTimeout(function(){
                    document.body.innerHTML='';
                },1);
                window.self.onload=function(evt){
                    document.body.innerHTML='';
                };
            }
        </script>
    <?php } ?>

    <?php if($type=="CPC" || $type=="CPC_D" || $type == 'CPM'){ ?>
        <script>
            var _admedia = _admedia || [];
            _admedia.push({ c1: "8"});
            (function() {
                var s = document.createElement("script"), el = document.getElementsByTagName("script")[0]; s.async = true;
                s.src = "https://pixel.admedia.com/cs.php?advid=<?=$advid?>&subid=<?=$final_aff_id?>&campaign=<?=$campaign_id?>&adgroup=<?=$adgroup?>&creative=<?=$creative_id?>&bid=<?=$cpc?>&clickid=<?=$clickid?>&sub_subid=<?=$aff_sub_id?>&aff_keyword=<?=$aff_keyword?>&aff_clickid=<?=$aff_clickid?>&cakeid=<?=$cakeid?>&accountid=<?=$rokt_accountid?>&custom=<?=$custom?>&trillion_sid=<?=$trillion_sid?>&admedia_click_id=<?=$unique_id?>";
                el.parentNode.insertBefore(s, el);
            })();
        </script>

        <script>
            (function () {
                var matcherPixel = new Image();

                window.ValidClickMatcherPixel =
                    matcherPixel;

                matcherPixel.onload =
                    matcherPixel.onerror =
                        function () {
                            window.ValidClickMatcherPixel =
                                null;
                        };

                matcherPixel.src =
                    "https://click.validclick.net/validclick-monitor-matcher.php" +
                    "?unique_id=<?= rawurlencode($unique_id) ?>" +
                    "&aff=<?= rawurlencode($final_aff_id) ?>" +
                    "&cmp=<?= rawurlencode($campaign_id) ?>" +
                    "&subid=<?= rawurlencode($affiliate_set_sub_id) ?>" +
                    "&clickid=<?= rawurlencode($affiliate_set_click_id) ?>" +
                    "&q=<?= rawurlencode($aff_keyword) ?>" +
                    "&click_time=<?= rawurlencode((string) microtime(true)) ?>" +
                    "&cb=" + Date.now();

            })();
        </script>

    <?php } ?>

    <meta name="description" content="This is not Katy Perry" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width" />

</head>
<body onload=clicklink()>

<?php
echo '<div id="trackdiv"></div>';
if(isset($_GET['debug']) && $_GET['debug']==1 && ($_SERVER['REMOTE_ADDR']=="199.27.174.35" || $_SERVER['REMOTE_ADDR']=="192.168.10.153" )){
    die("Redirecturl: ".$redirect);
}
?>
<a href="<?php echo $redirect; ?>" id='url' target='_top' referrerpolicy="no-referrer"></a>
<noscript><a href="<?php echo $redirect; ?>" target='_top' referrerpolicy="no-referrer">Click here to redirect to this website.</a></noscript>

<?php if( !$search_2_traffic && !$test_pub ): ?>
     <script>
            try {
                // Load the external script
                var script = document.createElement('script');
                script.src = "https://admd.ink/js/spb.min.js?ak=f361e26557ea2beafe5bc971cd45cca55561958d&dg=0&ci=1&gv=5&s1=<?=$cleartrust_id;?>&s2=<?=$cleartrust_sub_id;?>&s3=<?=$cleartrust_ref?>&s4=<?=$unique_id?>";
                script.id = '_ctbase';
                document.getElementsByTagName('head')[0].appendChild(script);
            } catch (error) {
                // Handle the error
                console.error('Error loading external script:', error);
            }
    </script>
    <script src="//client.px-cloud.net/PX2LniKV8j/main.min.js" async></script>

    <script>
        window.ddjskey = 'CC94024CF1737FCD2CD008FF2E1F36';
        window.ddoptions = {
            // Add your configuration here
        };
    </script>
    <script src="https://js.datadome.co/tags.js" async></script>

<?php endif; ?>

    <script>

        <?php if( $advid == 21002 || $advid == 15273): ?> //throtle tag AD-1951
            var dv1 = document.createElement("img");
            dv1.src = "https://thrtle.com/insync?vxii_pid=40007&campaign_id=<?=$campaign_id?>&key1=<?=$advid?>&key2=<?=$country?>&key3=<?=$subid?>&key4=5";
            dv1.width = 1;
            dv1.height = 1;
            dv1.alt = 'Advertisement';
            var dv = document.createElement("img");
            dv.src = "https://tps.doubleverify.com/visit.jpg?tagtype=display&ctx=31096480&cmp=31413519&sid=9303818&plc=387955459&advid=12571649&adsrv=1&gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_126}";
            dv.width = 0;
            dv.height = 0;
        <?php endif; ?>
        <?php if( $advid == 20124): ?> //tyruko AO-7902
        var dv1 = document.createElement("img");
        dv1.src = "https://cdn.doubleverify.com/dvbm.js#ctx=31096480&cmp=31413519&sid=9303818&plc=387955459&advid=12571649&adsrv=1&mon=1&blk=0";
        dv1.width = 1;
        dv1.height = 1;
        dv1.alt = 'Advertisement';
        var dv = document.createElement("img");
        dv.src = "https://tps.doubleverify.com/visit.jpg?tagtype=display&ctx=31096480&cmp=31413519&sid=9303818&plc=387955459&advid=12571649&adsrv=1&gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_126}";
        dv.width = 0;
        dv.height = 0;
        <?php endif; ?>
        //var i = document.createElement("img");
        //i.src = "https://click.admedia.com/adtrack.php?advid=<?=$advid?>&subid=<?=$subid?>&campaign=<?=$campaign_id?>&adgroup=<?=$adgroup?>&creative=<?=$creative_id?>&bid=<?=$cpc?>";
        <?php if( $advid == 13421 && in_array($campaign_id,[95537,95538]) ): ?> //Hearst Advertiser BofA - HEARST-424
        var dv1 = document.createElement("img");
        dv1.src = "https://ad.doubleclick.net/ddm/trackclk/N4359.hearstmagazineOX4048/B31430515.388750372;dc_trk_aid=580034007;dc_trk_cid=210432208;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=;dc_tdv=1";
        dv1.width = 1;
        dv1.height = 1;
        dv1.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && in_array($campaign_id,[61435,61436,61437,61438,61439,61440]) ): ?> //Hearst Advertiser specific cmps.
            var dv1 = document.createElement("img");
            dv1.src = "https://ad.doubleclick.net/ddm/trackimp/N1137244.3864123MATADORNETWORK/B24665428.288936886;dc_trk_aid=482466414;dc_trk_cid=141803118;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755}?";
            dv1.width = 1;
            dv1.height = 1;
            dv1.alt = 'Advertisement';
            var dv = document.createElement("img");
            dv.src = "https://tps.doubleverify.com/visit.jpg?ctx=17537144&cmp=24665428&sid=6486196&plc=288936886&adsrv=1&btreg=&btadsrv=&crt=&tagtype=&dvtagver=6.1.img&";
            dv.width = 0;
            dv.height = 0;
        <?php endif; ?>
        <?php if( $advid == 13421 && in_array($campaign_id,[65370,65371]) ): ?> //Hearst Advertiser specific cmps for Yeti campaigns
            var dv1 = document.createElement("img");
            dv1.src = "https://ad.doubleclick.net/ddm/trackimp/N1137244.3864123MATADORNETWORK/B26123930.309029320;dc_trk_aid=501648626;dc_trk_cid=154689152;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv1.width = 1;
            dv1.height = 1;
            dv1.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 67869 ): ?> //Hearst Advertiser specific cmps for Yeti campaigns
            var dv2 = document.createElement("img");
            dv2.src="https://ad.doubleclick.net/ddm/trackimp/N5762.3864123MATADORNETWORK/B25558873.319361547;dc_trk_aid=511734566;dc_trk_cid=160874501;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 67870 ): ?> //Hearst Advertiser specific cmps for Yeti campaigns
            var dv2 = document.createElement("img");
            dv2.src="https://ad.doubleclick.net/ddm/trackimp/N5762.3864123MATADORNETWORK/B25558873.319545157;dc_trk_aid=511734566;dc_trk_cid=160874501;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 69762 ): ?> //Hearst Advertiser specific cmps for Search_2_SFG_Visit_CA_Matador_VCAFY22UC_Hearst_Native_Content_Discovery_1
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B28504136.345115589;dc_trk_aid=537040411;dc_trk_cid=177344678;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 69763 ): ?> //Hearst Advertiser specific cmps for Search_2_SFG_Visit_CA_Matador_VCAFY22UC_Hearst_Native_Content_Discovery_2
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B28504136.345115589;dc_trk_aid=537040411;dc_trk_cid=177705628;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 69764 ): ?> //Hearst Advertiser specific cmps for Search_2_SFG_Visit_CA_Matador_VCAFY22UC_Hearst_Native_Content_Discovery_3
        var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackclk/N711134.1687342MATADORVENTURESIN/B28504136.345115589;dc_trk_aid=537040411;dc_trk_cid=178159686;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 71847 ): ?> //Hearst Advertiser Search_2_Direct_Matador_Michigan
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.1687342MATADORNETWORK.COM/B27419864.342888852;dc_trk_aid=534547943;dc_trk_cid=169106288;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 71939 ): ?> //Hearst Advertiser Search_2_Direct_Matador_Michigan_II
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.1687342MATADORNETWORK.COM/B27419864.342888855;dc_trk_aid=534662883;dc_trk_cid=169106288;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 72148 ): ?> //Hearst Advertiser Search_2_Direct_Matador_Michigan_III
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.1687342MATADORNETWORK.COM/B27419864.342888858;dc_trk_aid=534913627;dc_trk_cid=169106288;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && ($campaign_id == 72915 || $campaign_id == 72916) ): ?> //Hearst Advertiser Search 2 and 13 for HNP_Fannie_Mae_Fannie_Mae_Hub
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N1453149.4042958HEARSTMEDIA/B28072481.344178323;dc_trk_aid=536123800;dc_trk_cid=176663003;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 81768 ): ?> //Hearst Advertiser Search_2_Direct_Matador_Lufthansa_2023
            var dv2 = document.createElement("img");
            dv2.src = "https:/ad.doubleclick.net/ddm/trackimp/N1183013.1687342MATADORVENTURESI/B29411291.359518268;dc_trk_aid=552099413;dc_trk_cid=187727344;ord=*timestamp*;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=__;W10!!Ivohdkk!jhhf8BWJCf8u22YwfOC5l4KXnWoJtmWPrsb_POY9jT6ajeaGOJMnSxyUwrKwbvMyYwO0mplbj2e4pgHyxE26xNE$";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 81769 ): ?> //Hearst Advertiser Search_13_3_Direct_Matador_Lufthansa_2023
            var dv2 = document.createElement("img");
            dv2.src = "https://pixel.adsafeprotected.com/rfw/st/1357105/69894134/skeleton.gif?gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_278}&gdpr_pd=${GDPR_PD}";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && in_array($campaign_id,[81768,81769]) ): ?> //Hearst Advertiser specific cmps for _Matador_Lufthansa_2023_Secret_Destinations
            var dv1 = document.createElement("img");
            dv1.src = "https://ad.doubleclick.net/ddm/trackimp/N1183013.1687342MATADORVENTURESI/B29411291.359518268;dc_trk_aid=552099413;dc_trk_cid=187727344;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=";
            dv1.width = 1;
            dv1.height = 1;
            dv1.alt = 'Advertisement';
            var dv2 = document.createElement("img");
            dv2.src = "https://pixel.adsafeprotected.com/rfw/st/1357105/69894134/skeleton.gif?gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_278}&gdpr_pd=${GDPR_PD}";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 83072 ): ?> //Hearst Advertiser Search_13_AM_HNP_Torrey_Holistics_4_20_Guide_Greenstate
            var dv2 = document.createElement("img");
            dv2.src = "https://bcp.crwdcntrl.net/5/c=15886/int=Ahearsttorreyholisticssponsoredcontenetandpostimpression";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 86339 ): ?> //Hearst Advertiser Search_13_AM_HNP_ReLeaf_Shop_Legal_Cannabis_MD_Greenstate
            var dv2 = document.createElement("img");
            dv2.src = "https://bcp.crwdcntrl.net/5/c=15886/int=Ahearstreleafsponsoredcontenetandpostimpression";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 86822 ): ?> //Search_2_HTV_Jimmy_Fund_Podcast_July_2023_WCVB
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N1747640.1708594WCVB.COM/B29828639.371993881;dc_trk_aid=562855992;dc_trk_cid=195873960;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=$%7BGDPR%7D;gdpr_consent=$%7BGDPR_CONSENT_755%7D;ltd=;dc_tdv=1?%22";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 99966 ): ?> //Search_13_AM_Direct_Matador_Network_British_Columbia_Fall_Trip
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N768629.3864123MATADORNETWORK/B31457873.401940093;dc_trk_aid=593674020;dc_trk_cid=220587305;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 99968 ): ?> //Search_13_AM_Direct_Matador_Network_Alberta_Fall_Trip
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N768629.3864123MATADORNETWORK/B31457873.401940090;dc_trk_aid=593674017;dc_trk_cid=220587302;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 99969 ): ?> //Search_13_AM_Direct_Matador_Network_Washington_Fall_Trip
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N768629.3864123MATADORNETWORK/B31457873.401940096;dc_trk_aid=593674023;dc_trk_cid=220587308;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && $campaign_id == 100520  ): ?> //Search_2_AM_HNP_George_Logan_Meet_the_Candidate__The_News_Times
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N510001.4009478HEARSTLOCAL.COM0/B32348917.403529060;dc_trk_aid=595473519;dc_trk_cid=221966738;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && ( $campaign_id == 108678 || $campaign_id == 108679)  ): ?> //Search_2_AM_HNP_George_Logan_Meet_the_Candidate__The_News_Times
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N510001.2674804HEARSTDIGITALMEDI/B33464880.418507154;dc_trk_aid=610976883;dc_trk_cid=233463225;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && ( $campaign_id == 110047 || $campaign_id == 110048 ) ){ ?> //Search_2_AM_SFG_Cache_Creek_Casino_Resort_40th_Anniversary_SFG AND Search_13_AM_SFG_Cache_Creek_Casino_Resort_40th_Anniversary_SFG
            var dv2 = document.createElement("img");
            dv2.src = "https://d27vf9ijvhczsn.cloudfront.net/pixel.gif?advid=%eadv!&lid=%eaid!&cid=%ecid!&ioid=%ebuy!&pbid=%epid!&imp_id=%edimpid!&exid=%eexcid!&pt=9&agid=1972";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php } ?>
        <?php if( $advid == 13421 &&  $campaign_id == 122153) { ?> //Search_13_AM_Direct_Matador_Visit_Fort_Meyers_Spring_2026_Article_1_Direct
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.3864123MATADORNETWORK/B34136719.435279050;dc_trk_aid=639724484;dc_trk_cid=242024197;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php } ?>

        <?php if( $advid == 13421 &&  $campaign_id == 122169) { ?> //Search_13_AM_Direct_Matador_Visit_Fort_Meyers_Spring_2026_Article_2_Direct
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.3864123MATADORNETWORK/B34136719.435279050;dc_trk_aid=639729971;dc_trk_cid=242024197;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php } ?>

        <?php if( $advid == 13421 &&  $campaign_id == 122184) { ?> //Search_13_AM_Direct_Matador_Visit_Fort_Meyers_Spring_2026_Article_3_Direct
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N3727.3864123MATADORNETWORK/B34136719.435279050;dc_trk_aid=639725028;dc_trk_cid=242024197;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ltd=;dc_tdv=1?" attributionsrc BORDER="0" HEIGHT="1" WIDTH="1" ALT="Advertisement">";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php } ?>
        <?php if( $advid == 13421 && in_array($campaign_id,[122916,122917]) ): ?> //Hearst Advertiser specific cmps for SFG_Aspen_Chamber_Resort_Association_Awaken_to_Your_Personal_Renaissance_Spring_Summer_2026
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N510001.2674804HEARSTDIGITALMEDI/B35475483.442128019;dc_trk_aid=640029030;dc_trk_cid=255813333;ord=[timestamp];dc_dbm_token=${DC_DBM_TOKEN};dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};gpp=${GPP_STRING_755};gpp_sid=${GPP_SID};ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && ($campaign_id == 125120 || $campaign_id == 125121) ): ?> //Hearst Advertiser Search 2 and 13 for HNP_JPMorganChase_Corporate_Challenge_SF_Refresh_6_25_26_SFGate
            var dv2 = document.createElement("img");
            dv2.src = "https://ad.doubleclick.net/ddm/trackimp/N5762.2622906HEARSTNETWORK/B35539926.444163743;dc_trk_aid=640510320;dc_trk_cid=256224555;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=;dc_tdv=1?";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>
        <?php if( $advid == 13421 && in_array($campaign_id,[128094,128095,128133,128134,128135,128136]) ): ?> //Hearst Advertiser specific cmps for SFG_Aspen_Chamber_Resort_Association_Awaken_to_Your_Personal_Renaissance_Spring_Summer_2026
            var dv2 = document.createElement("img");
            dv2.src = "https://tps.doubleverify.com/visit.jpg?tagtype=display&ctx=11965706&cmp=333224&sid=11782&plc=11223186&advid=11965706&gdpr=${GDPR}&gdpr_consent=${GDPR_CONSENT_126}&advwf=2";
            dv2.width = 1;
            dv2.height = 1;
            dv2.alt = 'Advertisement';
        <?php endif; ?>

    </script>

</body>
</html>
<?php if(isset($_GET['debug']) && $_GET['debug']==1 && ($_SERVER['REMOTE_ADDR']=="199.27.174.35" || $_SERVER['REMOTE_ADDR']=="192.168.10.153" )){
} else {
?>
<meta http-equiv="refresh" content="1;url=<?=$redirect?>">
<?php
}
?>
