<?php
class opt_api_getresponse implements opt_mailer_api{ 
	public $sApiKey;
	public $sApiUrl = 'http://api2.getresponse.com';
	private $textOperators = array('EQUALS', 'NOT_EQUALS', 'CONTAINS', 'NOT_CONTAINS', 'MATCHES');
	public $aAccountInfo;
	private $error = '';
	
	public function aGetLists($operator = 'CONTAINS', $comparison = '%'){
		$params = null;
		if(in_array($operator, $this->textOperators)) $params = array('name' => array($operator => $comparison));
		$request  = $this->prepRequest('get_campaigns', $params);
		$response = $this->execute($request);
		
		if(is_string($response))
		{
			return $response;
		}
		
		$response = (array)$response;
		
		foreach($response as $key=>$value)
		{
			$response[$key] = (array)$value;
			
			$response[$key]['contacts'] = $this->getContactCount(array($key));
		}
		
		return $response;
	}
	
	//returns 'active', 'unconfirmed', 'unsubbed'
	public function CheckOptinStatus($leads_id = 0){
		$contact = opt_get_lead($leads_id);	
		global $wpdb;
		if($contact['subscription_status'] == 'Subscribed'){
			return true;
		}
		
		$l_t_m = $wpdb->get_results('SELECT * FROM '.OPT_DB_PREFIX.'opt_leads_to_mailers WHERE opt_lead_id = '.$leads_id,ARRAY_A);
		$single_optin = false;
		foreach($l_t_m as $ltm){
			$curMail = $wpdb->get_row('SELECT * FROM '.OPT_DB_PREFIX.'opt_mailers WHERE id='.$ltm['opt_mailer_id'].' AND mailer_type="GetResponse"',ARRAY_A);
			if(empty($curMail) || $curMail['list_name'] == ''){continue;}
			$curList = $this->aGetListById($curMail['list_name']);
			if($curList[$curMail['list_name']]['optin'] == 'single'){
				$single_optin = true;
				break;	
			}
		}
		
		$params['email'] = $this->prepTextOp('CONTAINS',$contact['email_text_id']);
		$request = $this->prepRequest('get_contacts',$params);
		//($request);
		$response = (array)$this->execute($request);
		//($response);	
		if(empty($response) && !$single_optin){
			return false;
		}else{
			$text_id = $contact['email_text_id'];
			$wpdb->update(OPT_DB_PREFIX.'opt_leads',
				array('email_text_id'=>$text_id,'subscription_status'=>'Subscribed'),
				array('id'=>$contact['id']));
			return true;	
		}
	}
	
	public function RegisterCallback(){
		$request = $this->prepRequest('get_account_info');
		$account_info = $this->execute($request);
		
		if(is_string($account_info))
		{
			return $account_info;
		}
		
		$cb_url = home_url().'/wp-content/plugins/opt/admin_pages/ajax/get_response_cb.php';
		
		$actions = array('subscribe','unsubscribe');
		
		$request = $this->prepRequest('set_account_callbacks',array('uri'=>$cb_url,'actions'=>$actions));
		$callback = $this->execute($request);
		
		if(is_string($callback))
		{
			return $callback;
		}
		
		return $account_info;
	}
	public function aGetListById($id){
		$request  = $this->prepRequest('get_campaign', array('campaign' => $id));
		$response = $this->execute($request);
		
		if(is_string($response))
		{
			return $response;
		}
		
		$response = (array)$response;
		
		foreach($response as $key=>$value)
		{
			$response[$key] = (array)$value;
			
			$response[$key]['contacts'] = $this->getContactCount($key);
		}
		
		return $response;	
	}
	
	public function getContactCount($id)
	{
		return count($this->aGetContacts($id));
	}
	
	public function recursiveArrayCast($object)
	{
		if(!is_object($object)) return $object;
		$return = (array)$object;
		foreach($return as $key=>$value)
		{
			if(is_object($value)) $return[$key] = $this->recursiveArrayCast($value);
		}
		return $return;
	}
	
	public function CreateContact($name,$email,$campaign,$phone,$extra, $action = 'standard', $cycle_day = 0, $customs = array()){
		$params = array('campaign' => $campaign, 'action' => $action,
						'email' => $email, 'cycle_day' => $cycle_day, 'ip' => $_SERVER['REMOTE_ADDR']);
		if(!empty($name)){
			$params['name'] = $name;	
		}
		
		if($phone != ''){
			$customs['phone'] = $phone;	
		}
		
		if(is_array($extra)){
			foreach($extra as $key=>$value){
				$customs[$key]=$value;	
			}
		}
		
		if(!empty($customs)) {
			foreach($customs as $key => $val) $c[] = array('name' => $key, 'content' => $val);
			$params['customs'] = $c;
		}
		$request  = $this->prepRequest('add_contact', $params);
		$response = $this->recursiveArrayCast($this->execute($request));
		
		$return = array(
			'response' => $response
		);
		
		return $return;	
	}
	
	public function aGetContacts($campaigns = null, $operator = 'CONTAINS', $comparison = '%', $fields = array('name' => true, 'email' => true)){
		$params = null;
		if(is_array($campaigns)) $params['campaigns'] = $campaigns;
		if($fields['name']) $params['name'] = $this->prepTextOp($operator, $comparison);
		if($fields['email']) $params['email'] = $this->prepTextOp($operator, $comparison);
		$request  = $this->prepRequest('get_contacts', $params);
		$response = $this->recursiveArrayCast($this->execute($request));
		
		if(is_string($response))
		{
			return $response;
		}
		
		return $response;	
	}
	
	
	public function prepTextOp($operator, $comparison)
	{
		if(!in_array($operator, $this->textOperators)) trigger_error('Invalid text operator', E_USER_ERROR);
		if($operator === 'CONTAINS') $comparison = '%'.$comparison.'%';
		return array($operator => $comparison);
	}
	
	public function prepRequest($method, $params = null, $id = null)
	{
		$array = array($this->sApiKey);
		if(!is_null($params)) $array[1] = $params;
		$request = json_encode(array('method' => $method, 'params' => $array, 'id' => $id));
		return $request;
	}
	
	public function execute($request)
	{
		$this->error = '';
		$handle = curl_init($this->sApiUrl);
		curl_setopt($handle, CURLOPT_POST, 1);
		curl_setopt($handle, CURLOPT_POSTFIELDS, $request);
		curl_setopt($handle, CURLOPT_HEADER, 'Content-type: application/json');
		curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);	  			   
		$response = json_decode(curl_exec($handle));
		if(curl_error($handle)) trigger_error(curl_error($handle), E_USER_ERROR);
		$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
		if(!(($httpCode == '200') || ($httpCode == '204'))) trigger_error('API call failed. Server returned status code '.$httpCode, E_USER_ERROR);
		curl_close($handle);
		
		//($response);
		
		if(!$response->error){
			 return $response->result;
		}else{
			return '('.$response->error->code.') '.$response->error->message;
		}
	}
	
	
	function __construct($ApiKey = null,$account_info = NULL){
		if(!extension_loaded('curl')) trigger_error('GetResponsePHP requires PHP cURL', E_USER_ERROR);
		$this->sApiKey = $ApiKey;
		$this->aAccountInfo = $account_info;	
	}

}
?>