<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! defined('_SBG_MO_REGISTER')) define('_SBG_MO_REGISTER', 0);
if ( ! defined('_SBG_MO_REGISTER_FOR')) define('_SBG_MO_REGISTER_FOR', 1);
if ( ! defined('_SBG_MO_PHONENUM_CHANGE')) define('_SBG_MO_PHONENUM_CHANGE', 2);
if ( ! defined('_SBG_MO_PASSWORD_RECOVERY')) define('_SBG_MO_PASSWORD_RECOVERY', 3);
if ( ! defined('_SBG_MO_PASSWORD_CHANGE')) define('_SBG_MO_PASSWORD_CHANGE', 4);
if ( ! defined('_SBG_MO_VIP_REGISTER')) define('_SBG_MO_VIP_REGISTER', 5);
if ( ! defined('_SBG_MO_PAY_TO_ACCOUNT')) define('_SBG_MO_PAY_TO_ACCOUNT', 6);
if ( ! defined('_SBG_MO_PAY_TO_ACCOUNT_FOR')) define('_SBG_MO_PAY_TO_ACCOUNT_FOR', 7);
if ( ! defined('_SBG_MO_UNSUBSCRIBE_SERVICE')) define('_SBG_MO_UNSUBSCRIBE_SERVICE', 8);

if ( ! defined('_SBG_MO_SYNTAX_ERR')) define('_SBG_MO_SYNTAX_ERR', -1);
if ( ! defined('_SBG_MO_SYNTAX_ERR_MSG')) define('_SBG_MO_SYNTAX_ERR_MSG', 'soanbaigiang.smas.vn khong co dich vu nay!');

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_ENOUGH_MSG')) define('_SBG_CHARGING_FAIL_NOT_ENOUGH_MSG', 'Tai khoan chinh cua so dien thoai :sendid: khong du de thuc hien lenh nap :amount: vao tai khoan :username: tren soanbaigiang.smas.vn');

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');

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]{4,16})$/'),
		_SBG_MO_PASSWORD_RECOVERY 	=> array('pattern' => '/^(SBG[[:blank:]])(MK)$/'),
		_SBG_MO_PASSWORD_CHANGE 	=> array('pattern' => '/^(SBG[[:blank:]])(MK)([[:blank:]][a-zA-Z0-9]{4,16})$/'),
		_SBG_MO_VIP_REGISTER 		=> array('pattern' => '/^(SBG[[:blank:]])(VIP)([[:blank:]][0-9]{1,2})$/'),
		_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_UNSUBSCRIBE_SERVICE => array('pattern' => '/^(SBG[[:blank:]])(HUY)$/')
	);
	
	public function __construct(){
		parent::__construct();
	}
	
	private function messageAnalys ($message) 
	{
		$aryMatched = array();
		$result = false;
		foreach ($this->_arySmsMO as $key => $pattern) 
		{
			$result = preg_match($pattern['pattern'], $message, $aryMatched);
			if ((bool)$result) break;
		}
		
		$key = (bool)$result ? $key:_SBG_MO_SYNTAX_ERR;
		$aryResult = (bool)$result ? array('case' => $key, 'content' => $aryMatched):array('case' => $key);
		return $aryResult;
	}
	
	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;
		if ($aryContents != null){
			unset($aryContents[0]);
			$aryTmp = array();			
			foreach ($aryContents as $key => $val)
			{
				$aryTmp[] = trim($val);
			}
			$aryContents = $aryTmp;
		}
		
		$this->load->model('frontend/user_model', 'objUserModel');
		$debugMsg .= $case;
		write_file('mt_log', $debugMsg);
		switch ($case) {
			case _SBG_MO_REGISTER:
			case _SBG_MO_REGISTER_FOR:
				$userName = isset($aryContents[2]) ? $this->formatPhoneNumber($aryContents[2]) : $sentNumber;  
				$collaborator = isset($aryContents[2]) ? $sentNumber:null;
				$sms = $this->objUserModel->register($userName, $collaborator);
				if ($case == _SBG_MO_REGISTER_FOR) {
					$smsReturn = '1|Ban da dang ky thanh cong dich vu Soan bai giang Online cho '. $userName;
					$arySMS = explode ('|', $sms);
					$sendMT = $this->sendMT($userName, $arySMS[1]);
				}
				else {
					$smsReturn = $sms;
				}
				break;
			case _SBG_MO_PHONENUM_CHANGE:
				$oldPhoneNumber = $this->formatPhoneNumber($aryContents[2]);
				$password = $aryContents[3];
				$smsReturn = $this->objUserModel->changeProfile($sentNumber, $oldPhoneNumber, $password);
				$sendMT = $this->sendMT($oldPhoneNumber, $smsReturn);
				break;
			case _SBG_MO_PASSWORD_RECOVERY:
			case _SBG_MO_PASSWORD_CHANGE:
				$password = isset($aryContents[2]) ? $aryContents[2] : null;
				$smsReturn = $this->objUserModel->changePassword($sentNumber, $password);
				break;						
			case _SBG_MO_VIP_REGISTER:
				$p_code = $aryContents[2];
				$smsReturn = $this->objUserModel->registerVip($sentNumber, $p_code);
				break;
			case _SBG_MO_PAY_TO_ACCOUNT:
			case _SBG_MO_PAY_TO_ACCOUNT_FOR:
				$userName = isset($aryContents[3]) ? $this->formatPhoneNumber($aryContents[3]) : $sentNumber;
				$amount = $aryContents[2];
				$result =$this->chargeRootAccountProcess($sentNumber, $amount);
				if ($result == _SBG_CHARGING_FAIL_NOT_ENOUGH) {
					$aryPatterns = array ('/:sendid:/', '/:amount:/', '/:username:/');
					$smsReturn = preg_replace($aryPatterns, array($sentNumber, $amount, $userName), _SBG_CHARGING_FAIL_NOT_ENOUGH_MSG);
					$smsReturn = '0|'.$smsReturn;
				}
				else {
					$smsReturn = $this->objUserModel->rechargeAccount($userName, $amount);
					if (_SBG_MO_PAY_TO_ACCOUNT_FOR) {
						$smsMT = $smsReturn .' tu thue bao '. $sentNumber;
						$sendMT = $this->sendMT($userName, $smsMT);
					}
				}
				
				//write to paid log
				$paidTime = date('Y-m-d H:i:s');
				$this->objUserModel->insertPaidlog($sentNumber, $userName, _SBG_PAIDTYPE_SMS, $amount, $paidTime);
				break;
			case _SBG_MO_UNSUBSCRIBE_SERVICE:
			case _SBG_MO_SYNTAX_ERR:
			default:
				$smsReturn = '0|'._SBG_MO_SYNTAX_ERR_MSG;
				break;
		}
		
		return $smsReturn;
	}
	
	public function cardPaidProcess ($aryCardInfo, &$aryTopupResult = array()) 
	{
		/*
	    ["BalanceAfterTransaction"]=>
	    string(1) "0"
	    ["ErrorCode"]=>
	    string(3) "199"
	    ["ErrorMessage"]=>
	    string(29) "L?i exception Payment service"
	    ["LastLockedOutDate"]=>
	    string(19) "0001-01-01T00:00:00"
	    ["RemainTimeToUnLock"]=>
	    string(1) "0"
	    ["Success"]=>
	    string(5) "false"
	    ["TransactionAmount"]=>
	    string(1) "0"
	    ["TransactionID"]=>
	    string(1) "0"
	    ["TransactionTime"]=>
	    string(19) "0001-01-01T00:00:00"
    	*/
		$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]];
		
		if ($aryTopupResult['Success'] == 'false') {
			return _SBG_CARD_PAY_FAIL;
		}
		
		return _SBG_CARD_PAY_SUCCESS;
	}
	
	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;
		}
		
		if ((int)$result['processChargingResult'] == _SBG_CHARGING_FAIL_NOT_ENOUGH) 
			return _SBG_CHARGING_FAIL_NOT_ENOUGH;
		
		return _SBG_CHARGING_SUCCESS;
	}
	
	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);
		
		//write_file('mt_log', var_export($client->fault, true)."\n".var_export($xml, true));
		
		if ($client->fault || (int)$result['InsertMTResult'] != 1) {
			return _SBG_SEND_MT_FAIL;
		}
		
		return _SBG_SEND_MT_SUCCESS;
	}
	
	public function formatPhoneNumber ($phoneNumber) {
		$aryMatch = array();
		if (preg_match('/^(84)([0-9]{9,10})$/', $phoneNumber, $aryMatch) == 1) {
			$result = '0'. $aryMatch[2];
		}
		else if (preg_match('/^(0)([0-9]{9,10})$/', $phoneNumber)) {
			$result = $phoneNumber;
		}
		
		return $result;
	}
}