<?php
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
/*
 

Freeway eCommerce 
http://www.openfreeway.org
Copyright (c) 2007 ZacWare 

Released under the GNU General Public License 
*/
  class clickatell {
    var $code, $title, $description, $enabled, $_connected;
	var $params,$host_url,$user_name,$password,$api_id;
	var $error_infos;
	var $session_track,$session_login_id;
	var $sent,$failed,$responses;
	var $error_code,$error_description;
	var $create_log;
	// class constructor
	function clickatell() {
		global $FSESSION,$PHP_SELF;
		$this->code = 'clickatell';
		$this->title = MODULE_SMS_CLICKATELL_TEXT_TITLE;
		$this->description = MODULE_SMS_CLICKATELL_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_SMS_CLICKATELL_SORT_ORDER;
		$this->enabled = ((MODULE_SMS_CLICKATELL_STATUS == 'True') ? true : false);
		//if ($FSESSION->is_registered('login_id') && $FSESSION->get('login_id')!='')
			$this->enabled=true;
		//else if (basename($PHP_SELF) != FILENAME_SEND_MESSAGES_SCRIPT)
		//	$this->enabled=false;
		
		$this->host_url="http://api.clickatell.com";
		$this->user_name=MODULE_SMS_CLICKATELL_USERNAME;
		$this->password=MODULE_SMS_CLICKATELL_PASSWORD;
		$this->api_id=MODULE_SMS_CLICKATELL_API_ID;
		$this->session_track=false;
		$this->session_login_id="";
		$this->sent=array();
		$this->failed=array();
		$this->create_log=false;
		$this->error_infos=array("001"=>"Authentication failed",
								"002"=>"Unknown username or password",
								"003"=>"Sesssion ID expired",
								"004"=>"Account frozen",
								"005"=>"Missing session ID",
								"101"=>"Invalid or missing parameters",
								"102"=>"Invalid UDH. (User Data Header)",
								"103"=>"Unknown apimsgid (API Message ID)",
								"104"=>"Unknown climsgid (Client Message ID)",
								"105"=>"Invalid Destination Address",
								"106"=>"Invalid Source Address",
								"107"=>"Empty message",
								"108"=>"Invalid or missing api_id",
								"109"=>"Missing message ID",
								"110"=>"Error with email message",
								"111"=>"Invalid Protocol",
								"112"=>"Invalid msg_type",
								"113"=>"Max message parts exceeded *",
								"114"=>"Cannot route message **",
								"115"=>"Message Expired",
								"116"=>"Invalid Unicode Data",
								"201"=>"Invalid batch ID",
								"202"=>"No batch template",
								"301"=>"No credit left",
								"302"=>"Max allowed credit");
	}
	function send_sms($to,$from,$contents,$country, $order_id, $customer_name ){
	    // attempt to format number for sending
	    $to = italy_number_crunch($to, $country);

		$this->responses=array();
		if (!$this->_connected && $this->session_track){
		 if (!$this->connecthost()) return false;
		 $this->_connected=true;
		}
		
		$msg=$this->host_url . "/http/sendmsg?";
		$msg.="user=" . $this->user_name . "&password=" . $this->password ."&api_id=" . $this->api_id;
		$msg.="&to=" . urlencode($to);
		//$msg.="&from=" . urlencode(SMS_FROM_NAME);
		$msg.="&text=" . urlencode($contents); 
		//exit($msg);
		$result=$this->_send_msg($msg,"ID");
		if ($result) {$this->sent[$to]=$result;
					  $this->sent['order_id'] = $order_id;
					  $this->sent['to'] = $to;
		
		
		
		
		}
		   else {$this->failed[$to]=$this->error_description;
		         $this->failed['to'] = $to;
				 $this->failed['message'] = $this->error_description;
		         $this->failed['order_id'] = $order_id;
				 $this->failed['customer_name'] = $customer_name;}
		return $result;
	}
    function get_failed_messages(){
		if (sizeof($this->failed)<=0) return "";
		reset($this->failed);
		//sends single emails only
		     //$result.="To: " . $id . " - " . $this->failed[$id];
			 $email_text = sprintf( MODULE_SMS_CLICKATELL_TEXT_FAILED,$this->failed['to'], $this->failed['message'], $this->failed['order_id'],$this->failed['customer_name']);
			 $to_name = $from_email_name = STORE_OWNER;
			 $to_email_address = $from_email_address = STORE_OWNER_EMAIL_ADDRESS;
			 $email_subject = MODULE_SMS_CLICKATELL_TEXT_FAILED_SMS;
			 tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address);
			 
 
 
		return ;
	}
	    function get_sent_messages(){
		if (sizeof($this->sent)<=0) return "";
		reset($this->sent);
		
		{
			$result = sprintf(MODULE_SMS_CLICKATELL_TEXT_SENT_SMS, $this->sent['to']) ;
		//update order
			include_once(DIR_WS_CLASSES . 'order.php');
	        $clickatell_order = new order($this->sent['order_id']);
			$status = $clickatell_order->info['status_id'];
			
				$sql_data_array = array(
						'orders_id' => $this->sent['order_id'],
						'orders_status_id' => $status,
						'date_added' => date('Y-m-d H:i:s',getServerDate(false)),
						'customer_notified' => 1,
						'comments' => $result,
						'user_added'=>"Clickatell"
						);
	tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
			
        }
		return $result;
	}
	function connecthost(){
		$this->responses=array();
		$msg=$this->host_url . "/http/auth?user=" . $this->user_name;
		$msg.="&password=" . $this->password ."&api_id=" . $this->api_id;
		$result=$this->_send_msg($msg,"OK");
		if ($this->session_track==true && isset($this->responses["OK"])){
			$this->session_login_id=$this->responses["OK"];
		}
		return $result;
	}
	function _send_msg($msg,$return_response){
	

		// get response from url;
		$responses=array();
		ini_set('default_socket_timeout',    180);
		$response=@file($msg);
		//if ($this->create_log) 
		// {
			// $log_write=join("\n",$response);
			// $handle=@fopen( "sms.log","a");
			// fwrite($handle,$log_write,strlen($log_write));
			// fclose($handle);
		// }
		if (sizeof($response)<=0) return false;
		$success=false;
		for($icnt=0;$icnt<sizeof($response);$icnt++){
			$cmd=preg_split("/:/",$response[$icnt]);
			if (sizeof($cmd)<2) return false;
			if ($cmd[0]==$return_response){
				$success=$responses[$return_response]=trim($cmd[1]);
			//	$success=true;
			} else if ($cmd[0]=="ERR") {
				//$this->error_code=trim($cmd[1]);
				$this->error_description=trim($cmd[1]);
			} else{
				$this->error_description="unknown error";
			}
		}
		return $success;
	}
	function get_error(){
		return $this->error_description;
	}	
	function set_option($name,$value){
		if (isset($this->$name)){
			$element=&$this->$name;
			$element=$value;
		}
	}
	
	//italy new functions set to return the  sms content
	//may not be used
	function create_sms_text(){
	   global $deadline, $insert_id;
          //this will create the  text that actually goes in the message
		  return array('text' => sprintf(MODULE_SMS_CLICKATELL_TEXT_TRANS_1, $insert_id, STORE_NAME, date("d-m-Y",strtotime($deadline)), date("H:i",strtotime($deadline))));
		}
	function send_order_reminder() {
		return false;
		}
	function send_order_extension() {
		return false;
		}	
	function send_order_expired() {
		return false;
		}
	function send_order_success(){
	
		//italy order confirmation sms

	
      global $order, $insert_id, $sms;

	  
			$to = $order->customer['telephone']; error_log($to);
			$country =  $order->customer['country']['title'];error_log($country);
			$to = italy_number_crunch($to,$country);  error_log($to);
			$from='';
			//$contents = $sms->create_sms_text()['text'];
			$contents =  sprintf(MODULE_SMS_CLICKATELL_TEXT_TRANS_1,  STORE_NAME, $insert_id);
			
			
				
			$sms->send_sms($to,$from,$contents,$country, $insert_id, $order->customer['firstname'] . ' ' . $order->customer['lastname']);
	


	
		return false;
		}		
	// install related procedures
    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Clickatell sms Module', 'MODULE_SMS_CLICKATELL_STATUS', 'True', 'Do you want to include Clickatell SMS?',6, '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Sort order of display.', 'MODULE_SMS_CLICKATELL_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.',6, '2', now())");
    //  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Host Url.', 'MODULE_SMS_CLICKATELL_URL', 'http:\/\/api.clickatell.com', 'Gateway URL used to access system - should not need editing',6, '3', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Username.', 'MODULE_SMS_CLICKATELL_USERNAME', '', 'Username used to authenticate gateway',6, '4', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell Password.', 'MODULE_SMS_CLICKATELL_PASSWORD', '', 'Password used to authenticate gateway',6, '5', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Clickatell API id.', 'MODULE_SMS_CLICKATELL_API_ID', '', 'API id used to authenticate gateway',6, '6', now())");
    
}

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SMS_CLICKATELL_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function keys() {
      return array('MODULE_SMS_CLICKATELL_STATUS',  'MODULE_SMS_CLICKATELL_SORT_ORDER','MODULE_SMS_CLICKATELL_USERNAME','MODULE_SMS_CLICKATELL_PASSWORD','MODULE_SMS_CLICKATELL_API_ID');
    }
  }
?>
