<?php


class opt_api_icontact implements opt_mailer_api{ 

	public $sApiKey;
	public $sApiUrl = 'https://app.icontact.com/icp';
	public $login,$password;
	
	public $iAccountId        = null;    // This holds the account ID
	public $iClientFolderId   = null;    // This holds the client folder ID
	public $aConfig           = array(); // This is our array for pragmatically overriding configuration constants
	public $aErrors           = array(); // This holds the errors encountered with the iContact API
	public $sLastRequest      = null;    // This holds the last request JSON
	public $sLastResponse     = null;    // This holds the last response JSON
	public $sRequestUri       = null;    // This stores the last used URL
	public $bSandbox          = false;   // This tells the system whether or not to use the iContact Sandbox or not
	public $aSearchParameters = array(); // This is our container for search params
	public $iTotal            = 0;       // If the results return a total, it will be stored here
	public $aWarnings         = array(); // This holds the warnings encountered with the iContact API
	
	//returns 'active', 'unconfirmed', 'unsubbed'
	public function CheckOptinStatus($leads_id = 0){
		$contact = opt_get_lead($leads_id);
		
		if($contact['subscription_status'] == 'Subscribed'){return true;}
		
		
		
		
		$wpdb->update(OPT_DB_PREFIX.'opt_leads',array('subscription_status'=>'Subscribed' ) ,array('id'=>$contact['id']) );	
		return true;
	}
	public function aGetLists(){
		$result = $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/lists', 'GET', null);	
		
		if(!empty($result->errors)){
			$retVal = '';
			foreach($result->errors as $error)
			{
				$retVal .= $error;
			}
			return $retVal;
		}
		
		$return = array();
		foreach($result->lists as $value)
		{
			$return[$value->listId] = array(
				'name'=>$value->name,
				'description'=>$value->description,
				'contacts'=>$this->GetContactCountForList($value->listId));
		}
		return $return;
	}
	public function aGetListById($id){
		$result = $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/lists/'.$id, 'GET', null);
		
		if(!empty($result->errors)){
			$retVal = '';
			foreach($result->errors as $error)
			{
				$retVal .= $error;
			}
			return $retVal;
		}
		
		$result = $result->lists;
				
		$return = array($result->listId=>array(
				'name'=>$result->name,
				'description'=>$result->description,
				'contacts'=>$this->GetContactCountForList($result->listId)));
		return $return;
	}
	
	public function CreateContact($name,$email,$campaign,$phone,$extra){
		list($fname,$lname) = explode(' ',$name);
		
		$contact = array(
			'firstName'=>$fname,
			'lastName'=>$lname,
			'email'=>$email			
		);
		
		if($phone != ''){
			$contact['phone'] = $phone;	
		}
		
		if(is_array($extra)){
			foreach($extra as $key=>$value){
				if($key == 'address1'){
					$contact['street'] = $value;	
				}elseif($key == 'address2'){
					$contact['street2'] = $value;	
				}elseif($key == 'city'){
					$contact['city'] = $value;	
				}elseif($key == 'state'){
					$contact['state'] = $value;
				}elseif($key == 'zip'){
					$contact['postalCode'] = $value;		
				}
			}
		}
		
		$result = $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/contacts','POST',array($contact),'contacts');
		
		$subscribe = $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/subscriptions','POST',array(array('contactId'=>$result[0]->contactId,'listId'=>$campaign,'status'=>'normal')),'subscriptions');
		return $result;
	}
	
	public function aGetContacts(){
		
		$result =  $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/contacts', 'GET');
		
		if(!empty($result->errors)){
			$retVal = '';
			foreach($result->errors as $error)
			{
				$retVal .= $error;
			}
			return $retVal;
		}
		
		return $result;
	}
	public function GetContactCountForList($id){
		$result = $this->makeCall('/a/'.$this->setAccountId().'/c/'.$this->setClientFolderId().'/contacts?status=total&limit=1&listId='.$id, 'GET');
		return $result->total;
	}
	
	function __construct($login = '',$password = ''){
		$this->login = $login;
		$this->password = $password;
		$this->sApiKey = OPT_ICONTACT_KEY;	
	}
	
	public function makeCall($sResource, $sMethod = 'GET', $mPostData = null, $sReturnKey = null) {
		
		// Set the URI that we will be calling
		$sApiUrl    = $this->sApiUrl.$sResource;
		// Initialize the cURL handle
		$rHandle     = curl_init();
		// Give our handle headers
		curl_setopt($rHandle, CURLOPT_HTTPHEADER, $this->getHeaders());
		// Tell our handle that we 
		// want the data returned
		curl_setopt($rHandle, CURLOPT_RETURNTRANSFER, true);
		// Turn SSL verifcation off, so scripts do not get broken
		curl_setopt($rHandle, CURLOPT_SSL_VERIFYPEER, false);
		// Determine the request
		// method we are using
		switch (strtoupper($sMethod)) {
			// Deleting data
			case 'DELETE' : 
				// Set the cURL custom header
				curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, 'DELETE');
			break;
			// Recieving data
			case 'GET'    :
				// Check for a query string
				if (!empty($this->aSearchParameters)) {
					// Add the query string
					$sApiUrl .= (string) '?'.http_build_query($this->aSearchParameters);
				}
			break;
			// Sending data
			case 'POST'   :
				// Check for POST data
				if (empty($mPostData)) {
					// Add an error, for there is no
					// POST data to send to the API
					$this->addError('No POST data was provided.');
				} else {
					// Tell our handle that 
					// we want to send data
					curl_setopt($rHandle, CURLOPT_POST, true);
					// Give our handle the data
					curl_setopt($rHandle, CURLOPT_POSTFIELDS, json_encode($mPostData));
					// Set the request JSON
					$this->sLastRequest = (string) json_encode($mPostData);
				}
			break;
			// Uploading data
			case 'PUT'    :
				if (empty($mPostData)) {
					// Is there data?
					
				} elseif (!is_string($mPostData) || !file_exists($mPostData)) {
					// Not a file, so we assume this is just data
					curl_setopt($rHandle, CURLOPT_CUSTOMREQUEST, "PUT");
					curl_setopt($rHandle, CURLOPT_POSTFIELDS, $mPostData);
				} else {
					$rFileContentHandle = fopen($mPostData, 'r');
					if ($rFileContentHandle === false) {
					} else {
						// Found a file, so upload its contents
						curl_setopt($rHandle, CURLOPT_PUT, true);
						curl_setopt($rHandle, CURLOPT_INFILE, $rFileContentHandle);
					}
				}
			break;
		}
		// Store the URL into the instance
		$this->sRequestUri = (string) $sApiUrl;
		// Give our handle a URL
		curl_setopt($rHandle, CURLOPT_URL, $sApiUrl);
		// Try to execute the handle
		if (!$sResponse = curl_exec($rHandle)) {
			// Add an error, for we could
			// not even execute the handle
			//$this->addError('We were unable to execute the cURL handle.');
		}
		// Set the response JSON
		$this->sLastResponse = (string) $sResponse;
		// Try to decode the response
		if ((!$aResponse = json_decode($sResponse)) && (strtoupper($sMethod) != 'DELETE')) {
			// Add an error, for the API
			// did not return valid JSON
			//$this->addError('The iContact API did not return valid JSON.');
		}
		// Close the cURL handle
		curl_close($rHandle);
		
		// Return the response
		if (strtoupper($sMethod) == 'DELETE') {
			// Return success
			return true;
		} elseif (empty($sReturnKey)) {
			// Return the entire 
			// base response
			return $aResponse;
		} else {
			// Return the narrowed resposne
			return $aResponse->$sReturnKey;
		}
	}
	
	public function getHeaders() {
		// Return the headers
		return array(
			'Except:', 
			'Accept:  application/json', 
			'Content-type:  application/json', 
			'Api-Version:  2.2',
			'Api-AppId:  '   . $this->sApiKey, 
			'Api-Username:  '. $this->login, 
			'Api-Password:  '. $this->password
		);
	}
	
	public function setAccountId($iAccountId = null) {
		// Check for an overriding
		// Account ID
		if (!empty($iAccountId)) {
			// Override the Account ID
			$this->iAccountId = (integer) $iAccountId;
		} else {
			// Check to see if the 
			// Account ID has already
			// been stored in the 
			// instance
			if (empty($this->iAccountId)) {
				// Load the Account ID
				if ($aAccounts = $this->makeCall('/a/', 'get', null, 'accounts')) {
					// Set the account
					
					$aAccount = $aAccounts[0];
					// Make sure the account is active
					if (intval($aAccount->enabled) === 1) {
						// The account is active
						// set the Account ID
						$this->iAccountId = (integer) $aAccount->accountId;
					} else {
						// Set an error, for this account
						// has been disabled
						$this->addError('Your account has been disabled.');
					}
				}
			}
		}
		// Inevitably return instance
		return $this->iAccountId;
	}
	
	protected function addError($sText) {
		// Append the error
		array_push($this->aErrors, $sText);
		// Return instance
		return $this;
	}
	
	public function setClientFolderId($iClientFolderId = null) {
		// Check for an overriding 
		// Client Folder ID
		if (!empty($iClientFolderId)) {
			// Set the Client Folder ID
			$this->iClientFolderId = (integer) $iClientFolderId;
		} elseif (empty($this->iClientFolderId)) {
			// Check for an Account ID
			if (empty($this->iAccountId)) {
				// Set the Account ID
				$this->setAccountId();
			}
			// Set the resource
			$sResource = (string) '/a/'.$this->iAccountId.'/c/';
			// Find the Client Folder ID
			if ($aClients = $this->makeCall($sResource, 'get', null, 'clientfolders')) {
				if (empty($aClients)) {
					// Add an error, for there
					// are no client folders
					//$this->addError('No client folders were found for this account.');
				} else {
					// Grab the default client folder
					
					$aClient = $aClients[0];
					// Set the Client Folder ID
					$this->iClientFolderId = (integer) $aClient->clientFolderId;
				}
			}
		}
		// Inevitably return instance
		return $this->iClientFolderId;
	}
}
?>