<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! defined('_SBG_MO_REGISTER')) 					define('_SBG_MO_REGISTER', 				'SUBSCR');
if ( ! defined('_SBG_MO_REGISTER_FOR')) 				define('_SBG_MO_REGISTER_FOR', 			'SUBSCR_FOR');
if ( ! defined('_SBG_MO_PHONENUM_CHANGE')) 				define('_SBG_MO_PHONENUM_CHANGE', 		'PHONE_CHANGE');
if ( ! defined('_SBG_MO_PASSWORD_RECOVERY')) 			define('_SBG_MO_PASSWORD_RECOVERY', 	'PWD_RECOVER');
if ( ! defined('_SBG_MO_VIP_REGISTER')) 				define('_SBG_MO_VIP_REGISTER', 			'REG_VIP');
if ( ! defined('_SBG_MO_PAY_TO_ACCOUNT')) 				define('_SBG_MO_PAY_TO_ACCOUNT', 		'PAY');
if ( ! defined('_SBG_MO_PAY_TO_ACCOUNT_FOR')) 			define('_SBG_MO_PAY_TO_ACCOUNT_FOR', 	'PAY_FOR');
if ( ! defined('_SBG_MO_UNSUBSCRIBE_SERVICE')) 			define('_SBG_MO_UNSUBSCRIBE_SERVICE', 	'UNSUBSCR');
if ( ! defined('_SBG_MO_SUPPOR_SERVICE')) 				define('_SBG_MO_SUPPOR_SERVICE', 		'SUPPORT');
if ( ! defined('_SBG_MO_SYNTAX_ERR')) 					define('_SBG_MO_SYNTAX_ERR', 			'SYNTAX_ERR');

if ( ! defined('_SBG_CARD_PAY_FAIL')) 					define('_SBG_CARD_PAY_FAIL', 			-1);
if ( ! defined('_SBG_CARD_PAY_SUCCESS')) 				define('_SBG_CARD_PAY_SUCCESS', 		1);

if ( ! defined('_SBG_CHARGING_FAIL')) 					define('_SBG_CHARGING_FAIL', -1);
if ( ! defined('_SBG_CHARGING_SUCCESS')) 				define('_SBG_CHARGING_SUCCESS', 1);
if ( ! defined('_SBG_CHARGING_FAIL_NOT_ENOUGH')) 		define('_SBG_CHARGING_FAIL_NOT_ENOUGH', 401);
if ( ! defined('_SBG_CHARGING_FAIL_NOT_VIETTEL')) 		define('_SBG_CHARGING_FAIL_NOT_VIETTEL', 402);
if ( ! defined('_SBG_CHARGING_NUMBER_NOT_EXISTED')) 	define('_SBG_CHARGING_NUMBER_NOT_EXISTED', 403);
if ( ! defined('_SBG_CHARGING_NUMBER_NOT_AVAILABLE')) 	define('_SBG_CHARGING_NUMBER_NOT_AVAILABLE', 404);
if ( ! defined('_SBG_CHARGING_NUMBER_CHANGED_OWNER')) 	define('_SBG_CHARGING_NUMBER_CHANGED_OWNER', 405);
if ( ! defined('_SBG_CHARGING_FAIL_MORETHAN_LIMIT')) 	define('_SBG_CHARGING_FAIL_MORETHAN_LIMIT', 406);
if ( ! defined('_SBG_CHARGING_GENERAL_ERROR')) 			define('_SBG_CHARGING_GENERAL_ERROR', 440);
if ( ! defined('_SBG_CHARGING_NUMBER_NOT_REGISTED')) 	define('_SBG_CHARGING_NUMBER_NOT_REGISTED', 501);

if ( ! defined('_SBG_SEND_MT_FAIL')) 					define('_SBG_SEND_MT_FAIL', -1);
if ( ! defined('_SBG_SEND_MT_SUCCESS')) 				define('_SBG_SEND_MT_SUCCESS', 1);
if ( ! defined('_SBG_MT_SEND_NUMBER')) 					define('_SBG_MT_SEND_NUMBER', '841662860000');
if ( ! defined('_SBG_MT_CP_CODE')) 						define('_SBG_MT_CP_CODE', '601');

if ( ! defined('_SBG_SERVICE_COMMAND_CODE'))			define('_SBG_SERVICE_COMMAND_CODE', 'SBG');
if ( ! defined('_SBG_SERVICE_SERVICEID')) 				define('_SBG_SERVICE_SERVICEID', '8062');

if ( ! defined('_SBG_MO_PROCCESS_ERR')) 				define('_SBG_MO_PROCCESS_ERR', 0);

Class Services_model extends CI_Model 
{
	private $_arySmsMO = array(
		_SBG_MO_REGISTER 			=> array('pattern' => '/^(SBG)([[:blank:]])(DK)$/'),
		_SBG_MO_REGISTER_FOR 		=> array('pattern' => '/^(SBG)([[:blank:]])(DK)([[:blank:]])([0-9]{10,11})$/'),
		_SBG_MO_PHONENUM_CHANGE 	=> array('pattern' => '/^(SBG)([[:blank:]])(DDT)([[:blank:]])([0-9]{10,11})([[:blank:]])([a-zA-Z0-9]{1,})$/'),
		_SBG_MO_PASSWORD_RECOVERY 	=> array('pattern' => '/^(SBG)([[:blank:]])(MK)$/'),
		_SBG_MO_VIP_REGISTER 		=> array('pattern' => '/^(SBG)([[:blank:]])(VIP)([[:blank:]])([a-zA-Z0-9]{1,})$/'),
		_SBG_MO_PAY_TO_ACCOUNT 		=> array('pattern' => '/^(SBG)([[:blank:]])(NAP)([[:blank:]])([0-9]{3,})$/'),
		_SBG_MO_PAY_TO_ACCOUNT_FOR 	=> array('pattern' => '/^(SBG)([[:blank:]])(NAP)([[:blank:]])([0-9]{3,})([[:blank:]])([0-9]{10,11})$/'),
		_SBG_MO_SUPPOR_SERVICE 		=> array('pattern' => '/^(SBG)([[:blank:]])(HD)$/'),
		_SBG_MO_UNSUBSCRIBE_SERVICE => array('pattern' => '/^(SBG)([[:blank:]])(HUY)$/')
	);	
	
	public function __construct(){
		parent::__construct();
		$this->load->helper('language');
		$this->lang->load('messages', 'message');
	}
	
	/**
	 * messageAnalys
	 * 
	 * @todo Analysis content of incoming message
	 * 
	 * @param String $message - coming SMS
	 * @return multitype:Ambigous <string, multitype> multitype:multitype
	 */
	public function messageAnalys ($message)
	{
		$aryMatched = array();	
		$aryContent = array();
		$result = FALSE;
		
		foreach ($this->_arySmsMO as $case => $pattern)
		{
			$result = preg_match($pattern['pattern'], strtoupper(trim($message)));
			if ((bool)$result) {
				$aryMatched = explode(' ', trim($message));
				break;
			}
		}
		
		$case = (bool)$result ? $case:_SBG_MO_SYNTAX_ERR;
		
		foreach($aryMatched as $k => $val) {
			if ($k > 1) $aryContent[] = $val;			
		}
		
		return array('case' => $case, 'content' => $aryContent);;
	}
	
	/**
	 * processMORequest
	 * 
	 * @todo process action analysed from messageAnalys
	 * 
	 * @param unknown $sentNumber
	 * @param unknown $message
	 * @return string
	 */
	public function processMORequest ($sentNumber, $message) 
	{
		$debugMsg = $message."\n";
		
		$sentNumber = $this->formatPhoneNumber($sentNumber);
		
		$smsReturn = '';
		$aryMOAnalys = $this->messageAnalys($message);		
		$case = $aryMOAnalys['case'];
		$aryContents = isset($aryMOAnalys['content']) ? $aryMOAnalys['content']: null;
		$this->load->model('frontend/user_model', 'objUserModel');
		$debugMsg .= $case;
		
		switch ($case) {
			case _SBG_MO_REGISTER:
			case _SBG_MO_REGISTER_FOR:
				if ($case == _SBG_MO_REGISTER_FOR) {
					if (!preg_match('/^([0-9]{10,11}$)$/', $aryContents[0])) {
						$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_PHONENUM_WRONG_FORMAT_MSG');
						break;
					}
				}
				
				$userName = isset($aryContents[0]) ? $this->formatPhoneNumber($aryContents[0]) : $sentNumber;  
				$collaborator = isset($aryContents[0]) ? $sentNumber:null;
				$collaboratorMsg = '';
				
				$sms = $this->objUserModel->register($userName, $collaborator, $collaboratorMsg);
				if ($case == _SBG_MO_REGISTER_FOR) {
					$smsReturn = $collaboratorMsg;
					$arySMS = explode ('|', $sms);
					if ((int)$arySMS[0] == 1 )
						$sendMT = $this->sendMT($this->formatPhoneNumber($userName, -1), $arySMS[1]);
				}
				else {
					$smsReturn = $sms;
				}
				break;
			case _SBG_MO_PHONENUM_CHANGE:
				if (!preg_match('/^(09\d{8}|01\d{9})$/', $aryContents[0])) {
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_PHONENUM_WRONG_FORMAT_MSG');
					break;
				}
				
				$oldPhoneNumber = $this->formatPhoneNumber($aryContents[0]);
				$password = $aryContents[1];
				$smsReturn = $this->objUserModel->changeProfile($sentNumber, $oldPhoneNumber, $password);
				
				$arySMS = explode('|', $smsReturn);
				$changeResult = (int)$arySMS[0];
				
				$aryPatterns = array('/:sentNumber:/');
				$sms = preg_replace($aryPatterns, array($sentNumber), lang('_SBG_MO_USER_OLD_PHONENUM_CHANGE_SUCCESS_MSG'));
				$sendMT = $changeResult == 1 ? $this->sendMT($this->formatPhoneNumber($oldPhoneNumber, -1), $sms) : '';
				break;
			case _SBG_MO_PASSWORD_RECOVERY:
				$smsReturn = $this->objUserModel->changePassword($sentNumber);
				break;
			case _SBG_MO_VIP_REGISTER:
				$p_code = $aryContents[0];
				$smsReturn = $this->objUserModel->registerVip($sentNumber, $p_code);
				$this->objUserModel->insertRegisterVipLog($sentNumber, $p_code, true);
				break;
			case _SBG_MO_PAY_TO_ACCOUNT:
			case _SBG_MO_PAY_TO_ACCOUNT_FOR:
				$userName = isset($aryContents[1]) ? $this->formatPhoneNumber($aryContents[1]) : $sentNumber;
				
				if ($case == _SBG_MO_PAY_TO_ACCOUNT_FOR && !preg_match('/^(09\d{8}|01\d{9})$/', $userName)) {
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_PHONENUM_WRONG_FORMAT_MSG');
					break;
				}
				
				$amount = $aryContents[0];
				if (!preg_match('/^[0-9]{3,}$/', $amount)) {
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_AMOUNT_WRONG_FORMAT_MSG');
					break;
				}
				
				$result =$this->chargeRootAccountProcess($sentNumber, $amount, $sentNumber.' paid for SBG');
				
				if ($result == _SBG_CHARGING_SUCCESS) {
					$smsReturn = $this->objUserModel->rechargeAccount($userName, $amount);
					if ($case == _SBG_MO_PAY_TO_ACCOUNT_FOR) {
						$arySmsReturn = explode ('|', $smsReturn);
						$aryPatterns = array('/:amount:/', '/:sentNumber:/');
						$smsMT = preg_replace($aryPatterns, array($amount, $sentNumber), lang('_SBG_MO_PAY_TO_ACCOUNT_FOR_MSG'));
						$sendMT = $this->sendMT($this->formatPhoneNumber($userName, -1), $smsMT);
					}
					
					//write to paid log
					$paidTime = date('Y-m-d H:i:s');
					$this->objUserModel->insertPaidlog($sentNumber, $userName, _SBG_PAIDTYPE_SMS, $amount, $paidTime);
				}
				else if ($result == _SBG_CHARGING_FAIL_NOT_ENOUGH) {
					$aryPatterns = array ('/:amount:/');
					$smsReturn = preg_replace($aryPatterns, array($amount), lang('_SBG_MO_CHARGING_FAIL_NOT_ENOUGH_MSG'));
					if ($case == _SBG_MO_PAY_TO_ACCOUNT_FOR) {
						$aryPatterns = array ('/:amount:/', '/:username:/');
						$smsReturn = preg_replace($aryPatterns, array($amount, $userName), lang('_SBG_MO_CHARGING_FAIL_NOT_ENOUGH_FOR_MSG'));
					}
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.$smsReturn;
				}
				else if ($result == _SBG_CHARGING_FAIL_MORETHAN_LIMIT) {
					$aryPatterns = array ('/:sendid:/');
					$smsReturn = preg_replace($aryPatterns, array($sentNumber), lang('_SBG_MO_CHARGING_FAIL_MORETHAN_LIMIT_MSG'));
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.$smsReturn;
				}else if ($result == _SBG_CHARGING_FAIL_NOT_VIETTEL || $result == _SBG_CHARGING_NUMBER_NOT_EXISTED || $result == _SBG_CHARGING_NUMBER_NOT_AVAILABLE) {
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_CHARGING_FAIL_NOT_VIETTEL_MSG');
				}				
				else {
					$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_CHARGING_FAIL_MSG');
				}
				break;
			case _SBG_MO_SUPPOR_SERVICE:
				$smsReturn = '1|'.lang('_SBG_MO_SUPPORT_MSG');
				break;
			case _SBG_MO_UNSUBSCRIBE_SERVICE:
			case _SBG_MO_SYNTAX_ERR:
			default:
				$smsReturn = _SBG_MO_PROCCESS_ERR.'|'.lang('_SBG_MO_SYNTAX_ERR_MSG');
				break;
		}
		
		return $smsReturn.'|'.$case;
	}
	
	
	/**
	 * cardPaidProcess
	 * 
	 * @todo Call Topup webservice to check and lock prepaid-card
	 * @param Array $aryCardInfo
	 * @param Array $aryTopupResult
	 * @return string
	 */
	public function cardPaidProcess ($aryCardInfo, &$aryTopupResult = array()) 
	{
		$url = $this->config->item('topup_service_url');
		$action = 'http://tempuri.org/ITopupService/TopUp';
		$xml = $this->load->view('topup', $aryCardInfo, true);
		
		$client = new nusoap_client($url);
		$client->useHTTPPersistentConnection();
		$client->soap_defencoding = 'UTF-8';
		$client->operation = $action;
		
		$result = $client->send($xml, $action);
		
		if ($client->fault) {
			return _SBG_CARD_PAY_FAIL;
		}
		
		$keys = array_keys($result);
		
		$aryTopupResult = $result[$keys[0]];

		$debugMsg = 'Logged time: '. date('Y-m-d H:i:s') ."\n";
		$debugMsg .=  'Send:'."\n" .$xml ."\n\n";
		$debugMsg .= 'Result:'."\n". var_export($result, TRUE);
		write_file('./log/topup_log', $debugMsg);

		if ($aryTopupResult['Success'] == 'false') {
			return _SBG_CARD_PAY_FAIL;
		}
		
		return _SBG_CARD_PAY_SUCCESS;
	}
	
	/**
	 * chargeRootAccountProcess
	 * 
	 * @todo Call charging webservice to charged fee from phone root account
	 * @param String $sentID
	 * @param Integer $amount
	 * @param String $contents
	 * @return string|number
	 */
	public function chargeRootAccountProcess ($sentID, $amount = 0, $contents = '') 
	{
		$url = $this->config->item('charging_service_url');
		$username = $this->config->item('charging_username');
		$password = $this->config->item('charging_password');
		$action = 'http://tempuri.org/processCharging';		
		
		$aryParams = array(
				'user' => $username,
				'pass' => $password,
				'MSISDN' => $sentID,
				'Charging' => $amount,
				'Contents' => $contents
		);
		
		$xml = $this->load->view('charging', $aryParams, true);
		$client = new nusoap_client($url);
		$client->useHTTPPersistentConnection();
		$client->soap_defencoding = 'UTF-8';
		$client->operation = $action;
		$result = $client->send($xml, $action);

		if ($client->fault) {
			return _SBG_CHARGING_FAIL;
		}
		
		$aryErrs = array (	_SBG_CHARGING_FAIL_NOT_ENOUGH, 
							_SBG_CHARGING_FAIL_NOT_VIETTEL, 
							_SBG_CHARGING_FAIL_MORETHAN_LIMIT,
							_SBG_CHARGING_NUMBER_NOT_EXISTED,
							_SBG_CHARGING_NUMBER_NOT_AVAILABLE,
							_SBG_CHARGING_NUMBER_CHANGED_OWNER,
							_SBG_CHARGING_GENERAL_ERROR,
							_SBG_CHARGING_NUMBER_NOT_REGISTED);
		
		if (in_array((int)$result['processChargingResult'], $aryErrs)) 
			return (int)$result['processChargingResult'];		
		
		return _SBG_CHARGING_SUCCESS;
	}
	
	/**
	 * sendMT
	 * 
	 * @todo Calling MT webservice to send a SMS to a phone number
	 * @param String $receiverID
	 * @param String $message
	 * @return string
	 */
	public function sendMT ($receiverID, $message)
	{
		$aryMatch = array();
		
		if (preg_match('/^(0)([0-9]{9,10})$/', $receiverID, $aryMatch) == 1) {
			$receiverID = '84'. $aryMatch[2];
		}
		
		$username = $this->config->item('mt_username');
		$password = $this->config->item('mt_password');
		$action = 'http://tempuri.org/InsertMT';
		
		$aryParams = array(
				'User' => $username,
				'Pass' => $password,
				'CPCode' => _SBG_MT_CP_CODE,
				'UserID' => _SBG_MT_SEND_NUMBER,
				'RequestID' => '4',
				'ReceiverID' => $receiverID,
				'ServiceID' => _SBG_SERVICE_SERVICEID,
				'CommandCode' => _SBG_SERVICE_COMMAND_CODE,
				'ContentType' => '0',
				'Info' => $message
		);
		
		$xml = $this->load->view('mt', $aryParams, true);
		$url = $this->config->item('mt_service_url');
		$client = new nusoap_client($url);
		$client->useHTTPPersistentConnection();
		$client->soap_defencoding = 'UTF-8';
		$client->operation = $action;
		$result = $client->send($xml, $action);
		
		if ($client->fault || (int)$result['InsertMTResult'] != 1) {
			return _SBG_SEND_MT_FAIL;
		}
		
		return _SBG_SEND_MT_SUCCESS;
	}
	
	/**
	 * formatPhoneNumber
	 * 
	 * @todo format phone number to prefix 0 or 84
	 * @param String $phoneNumber
	 * @param Integer $direction
	 * @return String
	 */
	public function formatPhoneNumber ($phoneNumber, $direction = 1) {
		$aryMatch = array();
		if (preg_match('/^(84)([0-9]{9,10})$/', $phoneNumber, $aryMatch) == 1 && $direction == 1) {
			$result = '0'. $aryMatch[2];
		}
		else if (preg_match('/^(0)([0-9]{9,10})$/', $phoneNumber) == 1 && $direction == 1) {
			$result = $phoneNumber;
		}
		else if (preg_match('/^(84)([0-9]{9,10})$/', $phoneNumber) == 1 && $direction == -1) {
			$result = $phoneNumber;
		}
		else if (preg_match('/^(0)([0-9]{9,10})$/', $phoneNumber, $aryMatch) == 1 && $direction == -1) {
			$result = '84'. $aryMatch[2];
		}
		
		return $result;
	}
}