<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Recharge extends MX_Controller
{
	public function __construct() 
	{
		parent::__construct();
		$this->load->model('frontend/user_model', 'objUserModel');
		$this->load->helper('lockfile');
		$this->load->model('services_model');
	}
	
	public function recharge_card()
	{
		$userID = $this->uri->segment(4);
		$input = $this->input->post();
		$cardSerial = $input['card_serial'];
		$pinCard = $input['pin_card'];
		$isLocked = 0;
		
		$user = $this->objUserModel->get_user_by_id($userID);
		$lockFilePreFix = $user['cellphone'];
		$lockFilePath = $this->config->item('topup_lock_path');
		$maxReach = $this->config->item('topup_lock_max_reach');
		$timeToUnlock = $this->config->item('topup_unlock_minute');

		$isLocked = createLockFile($lockFilePreFix, $maxReach, $timeToUnlock, $lockFilePath, 1);
		$chargCard = _SBG_CARD_PAY_SUCCESS;
		$result = array();
		$result['maxReach'] = $maxReach;
		$result['timeToUnlock'] = $timeToUnlock;
		$result['isLocked'] = $isLocked;
		$result['tmp'] = $maxReach;
		
		$lockedMsg = 'Quý vị đã nhập sai thông tin thẻ cào '. $maxReach .' lần liên tiếp.<br />Xin chờ '. $timeToUnlock .' phút sau để thao tác lại!';
		$chargErrMsg = 'Mã thẻ hoặc Serial không đúng hoặc đã được sử dụng. Quí vị vui lòng kiểm tra lại!';
		$errMsg = '';
		
		if ($isLocked == 0) {
			$aryParams = array(
					'EWalletID' => $this->config->item('EWalletID'),
					'CardSerial' => $cardSerial,
					'PinCard' => $pinCard,
			);
			
			$aryResult = array();
			$chargCard = $this->services_model->cardPaidProcess($aryParams,  $aryResult);
			
			$paidType = 2;
			$amount = $aryResult['TransactionAmount'];
			$paidTime = date('Y-m-d H:i:s');
			$user['acc_balanced'] = $user['acc_balanced'] + $amount;
			$user['updated_time'] = date('Y-m-d H:i:s');
			if ($amount>0){
				$this->objUserModel->updateUser($userID, $user);
			}
			
			$result['success'] = $chargCard;
			
			if ($chargCard == _SBG_CARD_PAY_SUCCESS){
				$result['username'] = $user['cellphone'];
				$result['acc_balanced'] = $user['acc_balanced'];
				$result['amount'] = $amount;
				$this->objUserModel->insertPaidlog($user['cellphone'], $user['cellphone'], $paidType, $amount, $paidTime);
				releaseLockFile($lockFilePreFix, $lockFilePath);
			}
			else {
				$isLocked = createLockFile($lockFilePreFix, $maxReach, $timeToUnlock, $lockFilePath);
				$errMsg = $isLocked == 1 ? $chargErrMsg .'<br />'.$lockedMsg : $chargErrMsg; 
			}
		}else if ($isLocked == 1) {
			$errMsg = $lockedMsg; 
			$result['success'] = _SBG_CARD_PAY_FAIL;
		}
		
		$result['errMsg'] = $errMsg;
		echo json_encode($result);
	}
}