<?php
/* Uses DT web services to download the latest "optional info" stats, and
 * updates the T202 database instead of having to go to Upload->Subid Stats
 * Sean Walberg <sean@ertw.com> http://ertw.com/
 */

// Hard code this if you're running from cron
include_once "/home/vhosts/track.ertw.com/htdocs/202-config.php";

/************************************
 * For the DT web services, you need the client name, your add code, and your password
 * Try Tools->Web services, or /partners/affiliate_webservices.html from within your DT interface
 * Each array element points to an array containing the username and password, ie
 * $endpoints = array ( "convert2media" => array("CD1234", "password"));
 * If you have multiple services to check, add more elements
 */

$endpoints = array (
	"ads4dough" => array("CD8946", "foo12foo"),
	"canadiansponsors" => array("CD3065", "foobar"),
	"cash4creatives" => array("CD10062", "foobar"),
	"ourfreestuff" => array("CD4232", "foobar"),
	"convert2media" => array("CD4027", "ange9Xu")
	);

$dbconnect = @mysql_connect($dbhost,$dbuser,$dbpass);
if (!$dbconnect) {
	echo "Error connecting to db: " . mysql_error();
	exit;
}
//connect to the mysql database, if couldn't connect error
$dbselect = @mysql_select_db($dbname);
if (!$dbselect) {
	echo "Error selecting database: " . mysql_error();
	exit;
}


if (isset($argv[1]) && $argv[1] == "all") {
	$start = date("Y/m/d", time() - 60*60*24*365*10); // 10 years
} else {
	$start = date("Y/m/d", time() - 60*60*24*7); // 1 week
}
$end = date("Y/m/d", time());

foreach ($endpoints as $endpoint => $creds) {
	$client = new SoapClient("http://$endpoint.directtrack.com/api/soap_affiliate.php?wsdl");
	try {
		$xml = $client->optionalInfo($endpoint, $creds[0], $creds[1], $start, $end);
	} catch (Exception $e) {
    		echo 'Caught exception: ',  $e->getMessage(), "\n";
	}
	if (empty($xml)) {
		continue;
	}
	$reader = new XMLReader();
	$reader->XML($xml);
	while ($reader->read()) {
		if ($reader->name == "Info" && $reader->nodeType == XMLReader::ELEMENT) {
			$reader->read();
			mark_conversion($reader->value);
		}
	}
}

function mark_conversion($subid) {
	 $click_id = mysql_real_escape_string($subid);
         $update_sql = "UPDATE 202_clicks SET click_lead='1', `click_filtered`='0' WHERE click_id='" . $click_id . "'";
         $update_result = mysql_query($update_sql) or die(mysql_error());

         $update_sql = "UPDATE 202_clicks_spy SET click_lead='1', `click_filtered`='0' WHERE click_id='" . $click_id . "'";
         $update_result = mysql_query($update_sql) or die(mysql_error());


}
