<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2018 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}


/**
* description
*
* @library	
* @author	
* @since	
*/
class MailChimp{
	
	var $apikey;
	var $datacenter;
	var $link = ".api.mailchimp.com/2.0/";
		var $version = "2.0";

	public static function newInstance(){
		return new self();
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SetApiKey($key) {

		$tmp = explode("-" ,$key );
		$this->apikey = $key;
		$this->datacenter = $tmp[1];
		$this->url = "https://" . $tmp[1].$this->link;

		return $this;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Subscribe($list , $user) {

		return $this->call(
			"lists/subscribe.json",
			array(
				"apikey"	=> $this->apikey,
				"id"		=> $list , 
				"email"		=> array(
					"email"		=> $user["email"],
				),

				"merge_vars"	=> array(
					"optin_time"	=> date("F j, Y, g:i a"),
					"optin_ip"		=> $_SERVER["REMOTE_ADDR"],

					"fname"			=> $user["first_name"],
					"lname"			=> $user["last_name"],
				),

				"double_optin"	=> false,

				"send_welcome"	=> false
			)
		);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function BatchSubscribe($list , $users) {

		return $this->call(
			"lists/subscribe.json",
			array(
				"apikey"	=> $this->apikey,
				"id"		=> $list , 

				"email"		=> array(
					"email"		=> $user["email"],
				),

				"merge_vars"	=> array(
					"optin_time"	=> date("F j, Y, g:i a"),
					"optin_ip"		=> $_SERVER["REMOTE_ADDR"],

					"fname"			=> $user["first_name"],
					"lname"			=> $user["last_name"],
				),

				"double_optin"	=> "false",

				"send_welcome"	=> "false"
			)
		);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function call($action , $data) {

		$fields = json_encode($data);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->url . $action);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );

		curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
			'Content-Type: application/json',                                                                                
			'Content-Length: ' . strlen($fields))                                                                       
		); 

		$result = curl_exec($ch);
		curl_close ($ch);

		return $this->Response($result);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Response($result) {
		return json_decode($result , true);
	}
	

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Debug() {
		return $this;
	}
	
}


?>
