<?php
$test = include("library/src/isdk.php");
$app = new iSDK;

if ($app->cfgCon("ifconnection"))
{
	$rId 	= $_POST["tagid"];
	$message = $_POST["value"];
	$field =  $_POST["field"];
	$integration = $_POST["integration"];
	$goal = $_POST["callname"];
	
	if (strlen($rId) < 1) 
	{
			echo "no Tag Id given, terminating<br/>";
			die;
	}
	if (strlen($field) < 1) 
	{
			echo "no Infusionsoft Field given, terminating<br/>";
			die;
	}
		if (strlen($integration) < 1) 
	{
			echo "no integration given, terminating<br/>";
			die;
	}
		if (strlen($goal) < 1) 
	{
			echo "no API goal given, terminating<br/>";
			die;
	}
	//echo strlen($rId);

	
	$people = array();
	$page = 0;

	do {
		$u = $app->dsFind("Contact", 1000, $page, "Groups", (int)$rId,
		array(
			"Id"
		));
		//var_dump($u);
		$people = array_merge($people, $u);
    
    ++$page;

	} while ( count($u) > 0 );
	
	//var_dump($people);
	
	foreach($people as $tag)
	{
		$fieldsToUpdate = array($field=> $message);
		$result = $app->dsUpdate("Contact", (int)$tag['Id'], $fieldsToUpdate);
		$test = $app->achieveGoal($integration, $goal , (int)$tag['Id']);
	}
	
	
	//exit;

	//Report save way of doing it
	/*$savedSearchId = $rId;
	$pages = 0;
	$flag = true;
	$reportResults = '';
	while($flag)
	{
		//echo $pages;
		$reportResults = $app->savedSearchAllFields($savedSearchId, $userId, $pages);
		if(sizeof($reportResults)==0)
		{
			$flag = false;
			break;
		}
		
		if(is_array($reportResults))
		{
			//var_dump($reportResults);
			foreach($reportResults as $res)
			{
				$conID = $res["ContactId"];
				$fieldsToUpdate = array('_BroadcastMessage'=> $message);
				$result = $app->dsUpdate("Contact", $conID, $fieldsToUpdate);
				$t = $app->achieveGoal($integration, $goal , $conID);
			}
		}
		else
		{
			echo "there was some type of error in fetching the report ";
			$flag = false;
			break;
			
		}
		$pages++;
		//echo $pages.' again';
	}*/
	//Report save way of doing it, end
	
	
	//echo $integration.'<br/>';
	//echo $goal.'<br/>';
	//echo $pages;*/
	/*$reportResults = $app->savedSearchAllFields($savedSearchId, $userId, 0);
	if(is_array($reportResults))
	{
		//var_dump($reportResults);
		foreach($reportResults as $res)
		{
			$conID = $res["ContactId"];
			$fieldsToUpdate = array('_BroadcastMessage'=> $message);
    		$result = $app->dsUpdate("Contact", $conID, $fieldsToUpdate);
			//$t = $app->achieveGoal('jo760', 'broadcastmessage' , $conID);
		}
	}
	else
	{
		echo "there was some type of error in fetching the report ";
	}*/
	
}
else
{
	$debugText = "connection failed!<br/>";	
	echo $debugText;
}




?>