<?php

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

if ( ! defined('_SBG_PAIDTYPE_SMS')) define('_SBG_PAIDTYPE_SMS', 1);
if ( ! defined('_SBG_PAIDTYPE_CARD')) define('_SBG_PAIDTYPE_CARD', 2);

class User_model extends CI_Model {
	const TOKENPW = 'violet';
	
	public function __construct() {
		parent::__construct ();
		$this->vservices->setApiUrl ( $this->config->item ( 'api_url' ) );
		$this->vservices->setConnection ( $this->curl );
		$this->load->helper('language');
		$this->lang->load('messages', 'message');
	}
	
	public function checkLogin($src, $token, $username, $password) {
		$data = $this->vservices->actionExecute ( 'login', array (
				'src' => $src,
				'token' => $token,
				'username' => $username,
				'password' => $password 
		), 'user' );
		if(!($data) || is_null($data)) return array('success'=>-1, 'data'=>$data);
		parse_str ( $data );
		if ($status == 0 || $status == 4) {
			$us_id = ( int ) $id;
			$query = "SELECT * FROM tbluser WHERE us_id = ?";
			$result = $this->db->query ( $query, array (
					$us_id 
			) );
			if ($result->num_rows () == 1) {
				return array('success'=>1, 'data'=>$data);
			} else {
				return array('success'=>0, 'data'=>$data);
			}
		} else {
			return array('success'=>0, 'data'=>$data);
		}
	}
	
	public function register($username, $collaborator, &$collaboratorMsg = '') {
		
                $user = array ();
		$password = $this->create_random_password ();
		$src = 'SBG';
		$sms = '';
		$id = 0;
		$errMsg = '';
		$token = md5 ( $username . self::TOKENPW );
		$phone = $username;
		$status = 0;
		
		if (! is_null ( $collaborator ) || $collaborator != '') {
			if (! $this->isExistcollaborator ( $collaborator )) {
				$aryPatterns = array('/:collaborator:/');
				$sms = preg_replace($aryPatterns, array($collaborator), lang('_SBG_MO_COLLABORATOR_NOT_FOUND_MSG'));
				$collaboratorMsg = $status . '|'.$sms;
				return $status . '|' . $sms;
			}
		}
		
		$data = $this->vservices->actionExecute ( 'update', array (
				'src' => $src,
				'username' => $username,
				'password' => $password,
				'fullname' => null,
				'phone' => $username,
				'token' => $token 
		), 'user' );
		
		if(!($data) || is_null($data))
		{
			$sms = lang('_SBG_MO_REGISTER_DISCONTINUE_MSG');
			$collaboratorMsg = $status . '|'.$sms;
			return $status . '|' . $sms;
		}
		
		parse_str ( $data );

		switch (( int ) $status) {
			case 0 :
                $this->load->model('frontend/Servicepackage_model');
				$trialpackage=$this->Servicepackage_model->getTrialPackage();
				$us_id = $id;
				$user ['created_time'] = date ( 'Y-m-d H:i:s' );
				$user ['us_id'] = $us_id;
				$user ['p_id'] = $trialpackage['p_id']; 
				$user ['expire_date'] = date('Y-m-d', strtotime("+" . $this->config->item("trial_period") . " days", time()));
				$user ['cellphone'] = $username;
				$user['province'] = $province;
				if (! is_null ( $collaborator ) || $collaborator != '') {
					$user ['collaborator'] = $collaborator;
				}
				$this->db->query ( 'UNLOCK TABLES' );
				$this->db->insert ( 'tbluser', $user );
				$aryPatterns = array ('/:trialdays:/', '/:username:/', '/:password:/');
				$trialdays = $this->config->item('trial_period');
				$trialdays = strlen($trialdays) < 2 ? '0'. $trialdays : $trialdays;
				$sms = preg_replace($aryPatterns, array($trialdays. ' ngay', $username, $password), lang('_SBG_MO_USER_REGISTER_SUCCESS_MSG'));
				$status = 1;
				$aryPatterns = array('/:collaborator:/');
				$collaboratorMsg = $status . '|'. preg_replace($aryPatterns, array($collaborator), lang('_SBG_MO_COLLABOLATOR_REGISTER_SUCCESS_MSG'));
				break;
			case 2 :
			case 4 :
				$sms = lang('_SBG_MO_USER_REGISTER_DUPLICATE_MSG');
				$status = 0;
				$aryPatterns = array('/:username:/');
				$collaboratorMsg = $status . '|'. preg_replace($aryPatterns, array($username), lang('_SBG_MO_COLLABOLATOR_REGISTER_DUPLICATE_MSG'));
				break;
			default :
				$status = 0;
				$sms = $errMsg;
				$collaboratorMsg = $status . '|'. $sms;
				break;
		}
		
		return $status . '|' . $sms;
	}
	
	public function create_random_password() {
		// $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
		$alphabet = "0123456789";
		$pass = array ();
		$alphaLength = strlen ( $alphabet ) - 1;
		for($i = 0; $i < 6; $i ++) {
			$n = rand ( 0, $alphaLength );
			$pass [] = $alphabet [$n];
		}
		return implode ( $pass );
	}
	
	public function get_user_by_id($us_id) {
		$this->db->query ( 'UNLOCK TABLES' );
		$this->db->select ( '*' )->from ( 'tbluser' )->join('tblservicepackage','tbluser.p_id=tblservicepackage.p_id','left')->where ( 'tbluser.us_id', $us_id );
		$query = $this->db->get ();
		if ($query->num_rows () > 0) {
			$row = $query->row_array ();
			return $row;
		}
	}
	
	public function get_user_info($src, $token, $us_id) {
		$data = $this->vservices->actionExecute ( 'getinfo', array (
				'src' => $src,
				'us_id' => $us_id,
				'token' => $token 
		), 'user' );
		return $data;
	}
	
	public function update_user($src, $token, $user, $us_id) {
		$data = $this->vservices->actionExecute ( 'update', array (
				'src' => $src,
				'token' => $token,
				'us_id' => $us_id,
				'password' => $user ['password'],
				'fullname' => $user ['fullname'],
				'school' => $user ['school'],
				'province' => $user ['province'],
				'oldpass' => $user ['oldpass'] 
		), 'user' );
		$u = array('province'=>$user['province'],
				'district'=>$user['district'],
				'updated_time'=>date('Y-m-d H:i:s')
				);
		$this->db->where('us_id', $us_id);
		$this->db->update('tbluser', $u);
		return $data;
	}
	
	public function changeProfile($sentNumber, $username, $password, &$status = '') {
		$user = array ();
		$src = 'SBG';
		$errMsg = '';
		$sms = '';
		$checkSentNumber = $this->get_user_by_cellphone ( $sentNumber );
		
		if ($checkSentNumber) {
			$aryPatterns = array('/:sentNumber:/');
			$sms =  preg_replace($aryPatterns, array($sentNumber), lang('_SBG_MO_USER_PHONENUM_CHANGE_DUPLICATE_MSG'));
			$status = 0;
			return $status . '|' . $sms;
		}
		
		$result = $this->get_user_by_cellphone ( $username );
		
		if ($result) {
			
			$us_id = $result ['us_id'];
			$token = md5 ( $us_id . self::TOKENPW );
			$isCorrectPassword = $this->checkPassword($src, $us_id, $token, $password);
			if(!$isCorrectPassword) return '0|'.lang('_SBG_MO_USER_PHONENUM_CHANGE_INCORRECT_PASSWORD_MSG');

			$data = $this->vservices->actionExecute ( 'update', array (
					'src' => $src,
					'token' => $token,
					'us_id' => $us_id,
					'username' => $sentNumber,
					"password" => $password,
					'oldpass' => $password,
					'phone' => $sentNumber 
			), 'user' );

			if(!($data) || is_null($data))
			{
				$sms = lang('_SBG_MO_PHONENUM_CHANGE_DISCONTINUE_MSG');
				$status = 0;
				return $status . '|' . $sms;
			}
			parse_str ( $data );
			switch (( int ) $status) {
				case 0 :
					$us_id = $id;
					$user ['updated_time'] = date ( 'Y-m-d H:i:s' );
					$user ['us_id'] = $us_id;
					$user ['cellphone'] = $sentNumber;
					$this->updateUser ( $us_id, $user );
					$aryPatterns = array('/:username:/', '/:sentNumber:/');
					$sms =  preg_replace($aryPatterns, array($username, $sentNumber), lang('_SBG_MO_USER_NEW_PHONENUM_CHANGE_SUCCESS_MSG'));
					$status = 1;
					break;
				case 2:
					$aryPatterns = array('/:sentNumber:/');
					$sms = preg_replace($aryPatterns, array($sentNumber), lang('_SBG_MO_USER_PHONENUM_CHANGE_DUPLICATE_MSG'));
					$status = 0;
					break;
				case 5 :
					$aryPatterns = array('/:username:/');
					$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_USER_PHONENUM_NOT_REGISTER_MSG'));
					$status = 0;
					break;
				default :
					$status = 0;
					$sms = $errMsg;
					break;
			}
		} else {
			$aryPatterns = array('/:username:/');
			$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_USER_PHONENUM_NOT_REGISTER_MSG'));
			$status = 0;
		}
		return $status . '|' . $sms;
	}
	
	public function changePassword($username, $password, &$status = '') {
		$user = array ();
		$src = 'SBG';
		$errMsg = '';
		$sms = '';
		$isForgotPassword = false;
		$pass = $password;
		
		if (is_null ( $password ) || $password == '') {
			$pass = $this->create_random_password ();
			$isForgotPassword = true;
		}
		
		$result = $this->get_user_by_cellphone ( $username );
		
		if ($result) {
			$us_id = $result ['us_id'];
			$token = md5 ( $us_id . self::TOKENPW );
			$data = $this->vservices->actionExecute ( 'update', array (
					'src' => $src,
					'token' => $token,
					'us_id' => $us_id,
					"password" => $pass 
			), 'user' );
			
			if(!($data) || is_null($data))
			{
				$sms = lang('_SBG_MO_PASSWORD_CHANGE_DISCONTINUE_MSG');
				$status = 0;
				return $status . '|' . $sms;
			}
			parse_str ( $data );
			switch (( int ) $status) {
				case 0 :
					$us_id = $id;
					$user ['updated_time'] = date ( 'Y-m-d H:i:s' );
					$this->updateUser ( $us_id, $user );
					if ($isForgotPassword) {
						$aryPatterns = array('/:pass:/');
						$sms = preg_replace($aryPatterns, array($pass), lang('_SBG_MO_USER_PASSWORD_RECOVERY_MSG'));
					} else {
						$aryPatterns = array('/:password:/');
						$sms = preg_replace($aryPatterns, array($pass), lang('_SBG_MO_USER_PASSWORD_CHANGE_SUCCESS_MSG'));
					}
					$status = 1;
					break;
				case 5 :
					$aryPatterns = array('/:username:/');
					$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_USER_PHONENUM_NOT_REGISTER_MSG'));
					$status = 0;
					break;
				default :
					$status = 0;
					$sms = $errMsg;
					break;
			}
		} else {
			$aryPatterns = array('/:username:/');
			$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_USER_PHONENUM_NOT_REGISTER_MSG'));
			$status = 0;
		}
		return $status . '|' . $sms;
	}
	
	public function checkLicense($userId) {
		$isNotExpired = false;
		$userInfo = array ();
		$userInfo = $this->get_user_by_id ( $userId );
		
		$expireDate = $userInfo ['expire_date'];
		
		if ((trim ( $expireDate ) == ''))
			return $isNotExpired;
		
		$today = mktime ();
		$expireTime = strtotime ( $expireDate . ' 23:59:59' );
		$isNotExpired = ($today < $expireTime);
                return $isNotExpired;
	}
	
	public function registerVip($username, $p_code) {
		$user = array ();
		$sms = '';
		
		$result = $this->get_user_by_cellphone ( $username );
		$package = $this->get_package ( ( int ) $p_code );
		if (!$package)
		{
			$sms = lang('_SBG_MO_USER_REGISTER_VIP_NOT_FOUND_MSG');
			$status = 0;
			return $status . '|' . $sms;
		}
		if ($result) {
			
			if ($result ['acc_balanced'] >= $package ['p_price']) {
				$us_id = $result ['us_id'];
				$user ['acc_balanced'] = $result ['acc_balanced'] - $package ['p_price'];
				if ($this->checkLicense ( $us_id )) {
					$user ['expire_date'] = date ( 'Y-m-d', strtotime ( $result ['expire_date'] . ' + ' . $package ['p_period'] . ' month' ) );
				} else {
					$user ['expire_date'] = date ( 'Y-m-d', strtotime ( 'now + ' . $package ['p_period'] . ' month' ) );
				}
				
				$user ['p_id'] = $package ['p_id'];
				$user ['updated_time'] = date ( 'Y-m-d H:i:s' );
				
				$this->updateUser ( $us_id, $user );
				$aryPatterns = array('/:period:/');
				$sms = preg_replace($aryPatterns, array(date ( 'd/m/Y', strtotime ( $user ['expire_date'] ) )), lang('_SBG_MO_USER_REGISTER_VIP_SUCCESS_MSG'));
				$status = 1;
			} else {
				$sms = lang('_SBG_MO_USER_REGISTER_VIP_FAIL_NOT_ENOUGH_MSG');
				$status = 0;
			}
		} else {
			$aryPatterns = array('/:username:/');
			$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_ACCOUNT_NOT_FOUND_MSG'));
			$status = 0;
		}
		return $status . '|' . $sms;
	}
	
	public function rechargeAccount($username, $amount) {
		$user = array ();
		$sms = '';
		$result = $this->get_user_by_cellphone ( $username );
		if ($result) {
			$us_id = $result ['us_id'];
			$user ['acc_balanced'] = $result ['acc_balanced'] + $amount;
			$user ['updated_time'] = date ( 'Y-m-d H:i:s' );
			$this->updateUser ( $us_id, $user );
			$aryPatterns = array('/:amount:/', '/:username:/');
			$sms = preg_replace($aryPatterns, array($amount, $username), lang('_SBG_MO_PAY_TO_ACCOUNT_SUCCESS_MSG'));
			$status = 1;
		} else {
			$aryPatterns = array('/:username:/');
			$sms = preg_replace($aryPatterns, array($username), lang('_SBG_MO_ACCOUNT_NOT_FOUND_MSG'));
			$status = 0;
		}
		return $status . '|' . $sms;
	}
	
	public function get_user_by_cellphone($cellphone) {
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'SELECT * FROM tbluser where cellphone = ? LIMIT 0,1';
		$query = $this->db->query ( $sql, array (
				$cellphone 
		) );
		$row = $query->row_array ();
		return $row;
	}
	
	public function isExistcollaborator($collaborator) {
		$this->db->query ( 'UNLOCK TABLES' );
		$this->db->select ( '*' )->from ( 'tblcollaborator' )->where ( 'login_name', $collaborator )->limit ( 1 );
		$result = $this->db->get ()->row_array ();
		if ($result)
			return true;
		else
			return false;
	}
	
	public function updateUser($us_id, $data) {
		$this->db->query ( 'UNLOCK TABLES' );
		$this->db->where ( 'us_id', $us_id );
		$this->db->update ( 'tbluser', $data );
	}
	
	public function get_package($p_code) {
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'SELECT * FROM tblservicepackage where p_code = ? LIMIT 0,1';
		$query = $this->db->query ( $sql, array (
				$p_code 
		) );
		$row = $query->row_array ();
		return $row;
	}
	
	public function insertSmslog($sentNumber, $serviceID, $commandcode, $info, $receiveTime) {
		if (preg_match ( '/^(84)([0-9]{9,10})$/', $sentNumber, $aryMatch ) == 1) {
			$sentNumber = '0' . $aryMatch [2];
		}
		
		try {
			$user = $this->get_user_by_cellphone ( $sentNumber );
		} catch ( Exception $e ) {
		}
		
		$smslog = array ();
		$smslog ['sender'] = $sentNumber;
		$smslog ['us_id'] = isset ( $user ['us_id'] ) ? $user ['us_id'] : NULL;
		$smslog ['service_id'] = $serviceID;
		$smslog ['commandcode'] = $commandcode;
		$smslog ['info'] = $info;
		$smslog ['created_time'] = $receiveTime;
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'INSERT INTO tblsmslog(sender, us_id, service_id, commandcode, info, created_time) VALUES(?,?,?,?,?,?)';
		$query = $this->db->query($sql, $smslog);
	}
	
	public function insertPaidlog($sentNumber, $receiveID, $paidType, $amount, $paidTime) {
		if (preg_match ( '/^(84)([0-9]{9,10})$/', $sentNumber, $aryMatch ) == 1) {
			$sentNumber = '0' . $aryMatch [2];
		}
		
		try {
			$user = $this->get_user_by_cellphone ( $receiveID );
		} catch ( Exception $e ) {
		}
		$paidlog = array ();
		$paidlog ['us_id'] = isset ( $user ['us_id'] ) ? $user ['us_id'] : NULL;
		$paidlog ['paidType'] = $paidType;
		$paidlog ['amount'] = $amount;
		$paidlog['source'] = "";
		if ($paidType == 1)
		{
			$paidlog['source'] = $sentNumber;
			
		}else
		{
			$paidlog['source'] = null;
		}
		$paidlog ['paidTime'] = $paidTime;
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'INSERT INTO tblpaidlog(us_id, paid_type, amount, source, paid_time) VALUES (?,?,?,?,?)';
		$query = $this->db->query ( $sql, $paidlog );
	}
	
	public function insertCardlog($username, $pinCode, $serialNum, $cardValue, $receiveTime)
	{
		try {
			$user = $this->get_user_by_cellphone ( $username );
		} catch ( Exception $e ) {
		}
		
		$cardlog = array();
		$cardlog['sender'] = $username;
		$cardlog['us_id'] = isset ( $user ['us_id'] ) ? $user ['us_id'] : NULL;
		$cardlog['pin_code'] = $pinCode;
		$cardlog['serial_num'] = $serialNum;
		$cardlog['card_value'] = $cardValue;
		$cardlog['created_time'] = $receiveTime;
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'INSERT INTO tblcardlog(sender, us_id, pin_code, serial_num, card_value, created_time) VALUES(?,?,?,?,?,?)';
		$query = $this->db->query ($sql, $cardlog);
	}
	
	public function getPaidlog($data)
	{
		$us_id = $data['us_id'];
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = "SELECT * FROM tblpaidlog where us_id = ? ORDER BY paid_time DESC LIMIT ".$data['start'].", ".$data['perpage']." ";
		$query = $this->db->query ( $sql, array (
				$us_id
		) );
		$row = $query->result_array();
		return $row;
	}
	
	public function countPaiglogs($us_id)
	{
		$this->db->query ( 'UNLOCK TABLES' );
		$sql="SELECT COUNT(paid_id) AS total FROM tblpaidlog WHERE us_id = ?";
		$query = $this->db->query ( $sql, array (
				$us_id
		) );
		$result = $query->row_array();
		return $result['total'];
	}
	
	public function checkPassword($src, $us_id, $token, $password)
	{
		$data = $this->vservices->actionExecute ( 'getinfo', array (
				'src' => $src,
				'us_id' => $us_id,
				'token' => $token,
				'ponly'=>1
		), 'user' );
		
		parse_str($data);
		if(md5($password) == $pencrypted) return true; else return false;
	}
	
	public function insertRegisterVipLog($username, $p_code, $isSms=true)
	{
		if ($isSms) $source = 'SMS'; else $source = 'Web';
		$createdTime = date('Y-m-d H:i:s');
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = 'INSERT INTO tblregisterpackagelog (username, source, p_code, created_time) VALUES (?,?,?,?)';
		$query = $this->db->query ( $sql,  array (
				'username'=>$username,
				'source'=>$source,
				'p_code'=>$p_code,
				'created_time'=>$createdTime
		) );
	}
	
	public function getPackagelog($data)
	{
		$username = $data['username'];
		$this->db->query ( 'UNLOCK TABLES' );
		$sql = "SELECT * FROM tblregisterpackagelog INNER JOIN tblservicepackage ON tblservicepackage.p_code = tblregisterpackagelog.p_code where username = ? ORDER BY created_time DESC LIMIT ".$data['start'].", ".$data['perpage']." ";
		$query = $this->db->query ( $sql, array (
				$username
		) );
		$row = $query->result_array();
		return $row;
	}
	
	public function countPackagelogs($username)
	{
		$this->db->query ( 'UNLOCK TABLES' );
		$sql="SELECT COUNT(id) AS total FROM tblregisterpackagelog WHERE username = ?";
		$query = $this->db->query ( $sql, array (
				$username
		) );
		$result = $query->row_array();
		return $result['total'];
	}
}
