<?php
/*
linkshare api key = 0f8c3949be10ad57f2a59abbe56e083e
integrate api key = 5d36d02e96307accf11b52d9908a1f5b
*/
ini_set("display_errors",0);
include_once 'lib/php/include/dbConstants.php';
$api_key = isset($_GET["api_key"]) ? $_GET["api_key"] :  false;
if (isset($_POST["api_key"])){
	$api_key = trim($_POST["api_key"]);
	if ($api_key!="0f8c3949be10ad57f2a59abbe56e083e" && $api_key!="5d36d02e96307accf11b52d9908a1f5b"){
		print "Authentication failed";
		exit();
	}	
	$remote_ip = $_SERVER['REMOTE_ADDR'];
	$white_array = array("1");	
	$white_array[] = "192.168.30.184";
	$white_array[] = "65.245.193.4";
	$white_array[] = "65.245.193.18";
	$white_array[] = "216.150.85.18";
	if (!in_array($remote_ip, $white_array)){
		print "Authentication failed.";
		exit();		
	}	
}

if ($api_key=="0f8c3949be10ad57f2a59abbe56e083e"){
	$admin_type = "LKSA";
	$partner_rev_share = 0.7;
} elseif ($api_key=="5d36d02e96307accf11b52d9908a1f5b") {
	$admin_type = "INTG";
	$partner_rev_share = 0.75;
}

if (isset($_POST["cmd"]) && trim($_POST["cmd"])=="add_user") {
    $aff = trim(strip_tags($_POST["aff"] ));
	$aff = $admin_type."_".$aff; // Append unique 
	$production = trim(strip_tags(urldecode($_POST["production"])));
    $email = trim(strip_tags(urldecode($_POST["email"]) ) );
    $status = 1;
    $meta = 1;
    $cutofftime = 1.5;
    $firstname = trim(strip_tags(urldecode($_POST["firstname"]) ) );
    $lastname = trim(strip_tags(urldecode($_POST["lastname"]) ) );
    $company = trim(strip_tags(urldecode($_POST["company"]) ) );
    $address1 = trim(strip_tags(urldecode($_POST["address1"]) ) );
    $address2 = trim(strip_tags(urldecode($_POST["address2"]) ) );
    $city = trim(strip_tags(urldecode($_POST["city"]) ) );
    $state = trim(strip_tags($_POST["state"] ) );
	$rev_share = trim(strip_tags($_POST["rev_share"] ) );
    $country = trim(strip_tags(urldecode($_POST["country"]) ) );
    $zip = trim(strip_tags($_POST["zip"] ) );
    $telephone = trim(strip_tags(urldecode($_POST["telephone"]) ) );
    $SSN = trim(strip_tags(urldecode($_POST["SSN"]) ) );
    $Tax_ID = trim(strip_tags(urldecode($_POST["Tax_ID"]) ) );
    $fax = trim(strip_tags(urldecode($_POST["fax"]) ) );
    $url = trim(strip_tags(urldecode($_POST["url"]) ) );
    $public_IP = trim(strip_tags(urldecode($_POST["public_IP"]) ) );
	$wire = trim(strip_tags(urldecode($_POST["wire"]) ) );
	$payment_type = trim(strip_tags(urldecode($_POST["payment_type"]) ) );
	switch($payment_type){	
		case "paypal":
		 $paypal_status = trim(strip_tags($_POST["paypal_status"] ) );
		 $paypal_email = trim(strip_tags(urldecode($_POST["paypal_email"]) ) );
		 $flag = 1;
		 $new_add = "";
		  break;
		case "check":
		  $baddress1 = trim(strip_tags(urldecode($_POST["baddress1"]) ) );
		  $baddress2 = trim(strip_tags(urldecode($_POST["baddress2"]) ) );
		  $bapt = trim(strip_tags(urldecode($_POST["bapt"]) ) );
		  $bcity = trim(strip_tags(urldecode($_POST["bcity"]) ) );
		  $bstate = trim(strip_tags(urldecode($_POST["bstate"]) ) );
		  $bzip = trim(strip_tags(urldecode($_POST["bzip"]) ) );
		  $bcountry = trim(strip_tags(urldecode($_POST["bcountry"]) ) );
		  $check_payable = trim(strip_tags(urldecode($_POST["check_payable"]) ) );
			 $flag = 1;
		if($baddress1 && $bcity  && $bzip && $bcountry )
			$new_add = $baddress1.",".$bcity." ".$bzip . ",".$bcountry;
		if($baddress1 && $baddress2  && $bcity && $bzip &&  $bcountry )
	       $new_add = $baddress1 .  "," . $baddress2 . "," . $bcity .   " " . $bzip . "," .$bcountry;	
		if($baddress1 && $bcity && $bstate && $bzip &&  $bcountry )
	       $new_add = $baddress1 .  "," . $bcity .  "," . $bstate . " " . $bzip . "," .$bcountry;	
		if($baddress1  && $bapt && $bcity  && $bzip &&  $bcountry )
	       $new_add = $baddress1 .  ",Apt/Suite " . $bapt . "," . $bcity . " " . $bzip . "," .$bcountry;	
		if($baddress1 && $baddress2 && $bcity && $bstate && $bzip && $bcountry )
		    $new_add = $baddress1.",".$baddress2.",".$bcity.",".$bstate." ".$bzip.",".$bcountry;
		if($baddress1 && $bapt && $bcity && $bstate && $bzip && $bcountry )
	       $new_add = $baddress1.","."Apt/Suite ".$bapt.",".$bcity.",".$bstate . " " . $bzip . "," .$bcountry;
		  if($baddress1 && $baddress2 && $bapt && $bcity  && $bzip &&  $bcountry )
	       $new_add = $baddress1 .  ",Apt/Suite " . $bapt . "," . $baddress2 . "," . $bcity . " " . $bzip . "," .$bcountry;
		if($baddress1 && $baddress2 && $bapt && $bcity && $bstate && $bzip &&  $bcountry )
	       $new_add = $baddress1 .  ",Apt/Suite " . $bapt . "," . $baddress2 . "," . $bcity .  "," . $bstate . " " . $bzip . "," .$bcountry;	
		  break;
	}   

	$db = connectWriteDB($production);
	$chk_user = check_user_exists($aff,$db);
	if ($chk_user){
		$return_array = array("response"=>0, "error"=>"Error: User $aff exists", "errorcode"=>"01");
		print_r($return_array);
	} elseif ($aff && $email && $firstname && $lastname && $company && $address1 && $city && $state && $country  && $telephone) { 
		$insert_sql1 = "INSERT INTO Affiliate 
		SET name = :name,
		XMLfeeds = 'B4KInhouse,BusinessBing,7searchNC,BrkW-Auto-300,BrkW-Health-200,BrkW-Home-400,BrkW-Life-260',
		status = :status, 
		meta = :meta, timedate = :timedate,
		defaultFeedCutoffTime = :cutofftime, 
		disable_xml=1,
		bipass_group1_mapping=1,
		bipass_group2_mapping=1,
		exclude_yb=1,
		cap_status=0,
		click_cap=500,
		cap_count=10000,
		clicks_per_day=10,
		whitelist=1,
		staticfeed=1,
		premier = 0, 
		new=1";		
		$stmt = $db->prepare($insert_sql1);
		$ack = $stmt->execute([
			'name' => $aff,
			'status' => $status,
			'meta' => $meta,
			'timedate' => time(),
			'cutofftime' => $cutofftime,
		]);
		if(!$ack) {
			$return_array = array("response"=>0, "error"=>"Error: User exists", "errorcode"=>"06");
			print_r($return_array);
			if ($_SERVER['REMOTE_ADDR']=="74.62.32.106"){
				print $insert_sql1;
			}
		 } else {
			if (!$rev_share){
				$rev_share = 1;
			}
			if ($rev_share > 1 || $rev_share < 0){
				$rev_share = 1;
			}
			$calculated_rev_share = $partner_rev_share * $rev_share;
			$paypal_status =(!$paypal_status ) ? 0 : $paypal_status;
			$pass = generatePassword();
			$clr_pass = $pass; 
			$pass = md5($clr_pass);
			$stmt2 = $db->prepare("INSERT INTO Affiliate_info
			SET Affiliate = :aff,
			email = :email,
			paypal_status = :paypal_status,
			paypal_email = :paypal_email,
			rev_share = :rev_share,
			firstname = :firstname,
			lastname = :lastname,
			company = :company,
			address1 = :address1,
			address2 = :address2,
			city = :city,
			state = :state,
			country = :country,
			zip = :zip,
			telephone = :telephone,
			fax = :fax,
			sales_rep = 'Inhouse',
			SSN = :SSN,
			Tax_ID = :Tax_ID,
			pass_clr = :pass_clr,
			public_IP = :public_IP,
			url = :url,
			check_address = :check_address,
			check_payable = :check_payable,
			payment_wire = :wire,
			subaff=1,
			admin_type = 'AD',
			timedate = :timedate");
			$ack = $stmt2->execute([
				'aff' => $aff,
				'email' => "$admin_type-$email",
				'paypal_status' => $paypal_status,
				'paypal_email' => $paypal_email ?? '',
				'rev_share' => $calculated_rev_share,
				'firstname' => $firstname,
				'lastname' => $lastname,
				'company' => $company,
				'address1' => $address1,
				'address2' => $address2,
				'city' => $city,
				'state' => $state,
				'country' => $country,
				'zip' => $zip,
				'telephone' => $telephone,
				'fax' => $fax,
				'SSN' => $SSN,
				'Tax_ID' => $Tax_ID,
				'pass_clr' => $clr_pass,
				'public_IP' => $public_IP,
				'url' => $url,
				'check_address' => $new_add ?? '',
				'check_payable' => $check_payable ?? '',
				'wire' => $wire,
				'timedate' => time(),
			]);

			$stmt3 = $db->prepare("INSERT INTO Affiliate_product
			SET Affiliate = :aff,
			banners=0,
			email=0,
			domain_redirect=0,
			geopop=0,
			tagcloud=0,
			domain_landing=0,
			socialsearch=0,
			inline=0,
			searchvortal=0,
			popunder=0,
			thankyou_offer=1");
			$pro_ack = $stmt3->execute(['aff' => $aff]);

			if(!$ack || !$pro_ack) {
				$return_array = array("response"=>0, "error"=>"Error: One of more fields missing", "errorcode"=>"02");
				print_r($return_array);
			} else {
			  $level = "1"; // level for affiliates
			  $stmt4 = $db->prepare("INSERT INTO Users SET uname = :uname, pass = :pass, pass_clr = :pass_clr, level = :level");
			  $ack = $stmt4->execute(['uname' => $aff, 'pass' => $pass, 'pass_clr' => $clr_pass, 'level' => $level]);
			  if(!$ack ) {
					$return_array = array("response"=>0, "error"=>"Error: One of more fields missing","errorcode"=>"03");
					print_r($return_array);
			  } else {
				$stmt5 = $db->prepare("INSERT INTO AffiliateIDs(Affiliate) VALUES(:aff)");
				$ack = $stmt5->execute(['aff' => $aff]);
				if(!$ack ) {
					$return_array = array("response"=>0, "error"=>"Error: One of more fields missing", "errorcode"=>"04");
					print_r($return_array);
				} else {
					$id = $db->lastInsertId();
					$display_aff = str_replace($admin_type."_","",$aff);
					$return_array = array("response"=>1, "success"=>"User $display_aff created", "password"=>$clr_pass, "id"=>$id);
					print_r($return_array);
				}
			  }
			}
	  }
	} else {
		$return_array = array("response"=>0, "error"=>"Error: One of more fields missing");
		print_r($return_array);
	}
} 

function check_user_exists($aff,$db){
	$tables = [
		['Affiliate', 'name'],
		['Affiliate_info', 'Affiliate'],
		['Users', 'uname'],
		['Affiliate_product', 'Affiliate'],
		['AffiliateIDs', 'Affiliate'],
	];
	foreach ($tables as [$table, $col]) {
		$stmt = $db->prepare("SELECT $col FROM $table WHERE $col = :aff");
		$stmt->execute(['aff' => $aff]);
		if ($stmt->rowCount() > 0) return 1;
	}
	return 0;
}


/**********************
 ** generatePassword **
 *********************/
function generatePassword($length = 8) {
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz";
  $i = 0;
  while($i < $length) {
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
    if(!strstr($password, $char)) {
      $password .= $char;
      $i++;
    }
  }
  return $password;
}

/********************************
 ** Curl request to read file  **
 ********************************/
function get_file_get_contents($url, $timeout=3) {
  $ch = curl_init($url); // initialize curl handle
  $timeout = 10;
  // curl_setopt($ch, CURLOPT_HEADER, true);  
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // discard SSL verification
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // discard SSL verification
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // times out after 4s  
  $data = curl_exec($ch); // run the whole process  
  if (curl_errno($ch)) {
    return false;
  } else {
    curl_close($ch);
	return $data;
  }
}

/********************************
 ** database connection to localhost **
 ********************************/
function connectWriteDB($production){
	$write_array = array(MSACOMMON_DB_HOST_ADMIN);
	shuffle($write_array);
	$mysql_host = $write_array[0];
	$mysql_user = MSACOMMON_DB_USER_ADMIN;
	$mysql_password = MSACOMMON_DB_PASS_ADMINMM;
	$mysql_db = ($production == 1) ? "Admin" : "Admin_sk";
	return new PDO(
		"mysql:host=$mysql_host;dbname=$mysql_db",
		$mysql_user,
		$mysql_password,
		[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
	);
}

?>