<?php
class opt_api_mailchimp implements opt_mailer_api{ 

	public $sApiKey;
	public $sApiUrl = 'https://api.mailchimp.com/2.0';
	public $ch;
	public $options;
	/*curl options*/
	
	//returns Subscribed', 'Pending', 'Unsubscribed'
	public function CheckOptinStatus($leads_id = 0){
		$contact = opt_get_lead($leads_id);
		//print_r($contact);
		if($contact['subscription_status'] == 'Subscribed'){return true;}
		
	    $lists = opt_get_related_mailers_list_name($contact['campaign_id'],'MailChimp');
		//print_r($lists);
		global $wpdb;
		foreach($lists as $list){
			
			$params = array('id' => $list['list_name'], 'emails' => array(array('email'=>$contact['email_text_id'])) );
			//print_r($params);
			$result = $this->_call('lists/member-info',$params);
			//($result);
			//print_r($result);
			if($result['success_count'] > 0){
				foreach($result['data'] as $res){
					if($res['status'] == 'subscribed'){
						$wpdb->update(OPT_DB_PREFIX.'opt_leads',array('subscription_status'=>'Subscribed','email_text_id'=>$contact['email_text_id']),array('id'=>$contact['id']));	
						return true;
					}		
				}
			}
		}
		return false;
	}
	public function aGetLists($params = array()){
		
		$result = $this->_call('lists/list',$params);
		
		if($result == '' || array_key_exists('error',$result)){
			if($result == ''){
				return 'API Error, no response from MailChimp.';	
			}
			return $result['error'];	
		}
		
		$return_array = array();
		foreach($result['data'] as $key=>$value)
		{
			$return_array[$value['id']] = array(
				'name' => $value['name'],
				'description' => '',
				'contacts' => $value['stats']['member_count']
			);
		}
		return $return_array;	
	}
	public function aGetListById($id){
		$params = array('filters'=>array('list_id'=>$id));
		return $this->aGetLists($params);	
	}
	
	public function CreateContact($name,$email,$campaign,$phone,$extra){
		list($fname,$lname) = explode(' ',$name);
		$params = array(
			'email'=>array('email'=>$email),
			'id'=>$campaign,
			'double_optin'=>$this->options['doubleOptin'],
			'send_welcome'=>$this->options['welcomeMessage'],
			'merge_vars'=>array('FNAME'=>$fname,'LNAME'=>$lname)
		);
		
		$result = $this->_call('/lists/subscribe',$params);
		if(array_key_exists('error',$result)){
			return $result['error'];	
		}
		return $result;	
	}
	public function aGetContacts(){}
	
	
	function __construct($sApiKey = '',$options = ''){
		
		$this->sApiKey = $sApiKey;
		$dc = "us1";
        if (strstr($this->sApiKey,"-")){
            list($key, $dc) = explode("-",$this->sApiKey,2);
            if (!$dc) $dc = "us1";
        }
        $this->sApiUrl = str_replace('https://api', 'https://'.$dc.'.api', $this->sApiUrl);
        $this->sApiUrl = rtrim($this->sApiUrl, '/') . '/';	
		
		$this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_USERAGENT, 'MailChimp-PHP/2.0.4');
        curl_setopt($this->ch, CURLOPT_POST, true);
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->ch, CURLOPT_HEADER, false);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($this->ch, CURLOPT_TIMEOUT, 600);
		
		if($options != ''){
			$this->options = $options;
		}else{
			$this->options = array(
				'doubleOptin'=>true,
				'welcomeMessage'=>false
				);
		}
	}
	
	public function __destruct() {
        curl_close($this->ch);
    }
	
	public function _call($url, $params = array())
	{
		$params['apikey'] = $this->sApiKey;
		$params = json_encode($params);
		
		$ch = $this->ch;
		
		curl_setopt($ch, CURLOPT_URL, $this->sApiUrl . $url . '.json');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        // SSL Options
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        
		$response_body = curl_exec($ch);
        $info = curl_getinfo($ch);
		
		if(curl_error($ch)){
			return false;
		}
		
		return json_decode($response_body, true);
		
		
	}
}

?>