<?php

	session_start();
	error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
	
	$configs = include(__DIR__ . '/../configs/config.php');
	
	include('functions.php');
	include('konnektive.php');
	include('Mobile_Detect.php');
	include('data_pipe.php');
	include('fraud.php');
	
	// Conditions to inject Meta / Google pixels

	if ( ! empty($_GET['meta']) ) {
		$_SESSION['meta_pixel_id'] = strip_tags($_GET['meta']);
	} elseif ( ! empty($_GET['google']) ) {
		$_SESSION['google_pixel_id'] = strip_tags($_GET['google']);
	}

	// Add subaff_cid to session

	if ( ! empty($_GET['subaff_cid']) ) {
		$_SESSION['subaff_cid'] = strip_tags($_GET['subaff_cid']);
	}
	
	/*
	 * Comment this out when you're not testing
	 */ 
	$_SESSION["anonymous_ip"] = false;
	
	$mobile_detect = new Mobile_Detect;
	
	$konnektive = new KonnektiveApi($configs->crm->username, $configs->crm->password);
	
	if (!isset($_SESSION["show_afflink"])) {
		$_SESSION["show_afflink"] = false;
	}
	
	if (!isset($_SESSION["ip_info"])) {

		$_SESSION["ip_info"] = ip_info($_SERVER["HTTP_CF_CONNECTING_IP"]);
		
		$ip_data = json_decode($_SESSION["ip_info"]);
		
		if ($_SERVER["HTTP_CF_IPCOUNTRY"] !== "CA") {
			if (!in_array($ip_data->region_code, ["FL", "PR", "CA"])) {
				$_SESSION["show_afflink"] = true;
			}
		}
	}
	
	if (session_status() == PHP_SESSION_ACTIVE) {
		// The first page load for the click/client
		
		if (isset($_GET["AFFID"])) {
			$_SESSION["affid"] = $_GET["AFFID"];
			// Overwrite the affid if it's not in the config
			if ( ! isset ($configs->affiliates[$_SESSION["affid"]]) ) {
				$_SESSION["affid"] = 'default';
			}
			$_SESSION['kk_affid'] = $_GET["AFFID"];
		}
		
		if (isset($_GET["c1"])) {
			$_SESSION["c1"] = $_GET["c1"];
		}
		
		if (isset($_GET["c2"])) {
			$_SESSION["c2"] = $_GET["c2"];
		}
		
		if (isset($_GET["c3"])) {
			$_SESSION["c3"] = $_GET["c3"];
		}

		if (isset($_GET["c6"])) {
			$_SESSION["c6"] = $_GET["c6"];
		}
		
		if (empty($_SESSION["log_click"])) {
			
			$resp = $konnektive->import_click(array(
				"affId" 				=> $_SESSION["kk_affid"],
				"sourceValue1" 	=> $_SESSION["c1"],
				"sourceValue2" 	=> $_SESSION["c2"],
				"sourceValue3" 	=> $_SESSION["c3"],
				"pageType"			=> "leadPage",
				"ipAddress" 		=> $_SERVER['HTTP_CF_CONNECTING_IP'],
				"campaignId" 		=> $configs->default_campaign_id,
				"httpReferer" 	=> "",
				"userAgent" 		=> isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "",
				"requestUri" 		=> (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"
			));
			
			$_SESSION["log_click"] = "logged";
		}
	}	
		