<?php

require_once('URCSystemData.php');
require_once('URCJWTWork.php');
require_once('RMSDealer.php');

class DealerController extends BaseController {

	/*
	static public function curl_req($path)//, $req, $data = '')
	{
	    $ch = curl_init();

	    curl_setopt($ch, CURLOPT_URL, Config::get('editorenv.urcDBServerAddr').'/'.$path.'&key=K2016MXHP_PkSg3gUPy3h3NHW3qbRqTuM');
	    //curl_setopt($ch, CURLOPT_USERPWD, Config::get('editorenv.urcDBServerAddr'));
	    //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    
	    $result = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);
	   	
	   	if($httpCode == 200) {
	   		;
	    	return $result;
	    }

	    //ErrorDebug::write($httpCode);

	    return false;
	}

	static public function isExistingUser($email) {
		
		$result = DealerController::curl_req('is_existing_login_name?email='.urlencode($email));
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		return $data;
	}
	*/

	
	public function doClass($funcType) {

		if($funcType == 'login') {

			$rules = array(
				'username' => 'Required',
				'password' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$username = Input::get('username');
			$password = Input::get('password');

			$dealerId = '';
			$dealerGrpId = '';
			$dealerGrpName = '';
			$isAdmin = 0;
			$rmsDealer = new RMSDealer();
			if(!$rmsDealer->login($username, $password, $dealerId, $dealerGrpId, $dealerGrpName, $isAdmin)) {
				return Response::json(array('result' => false, 'error' => 'Your username or password is incorrect.'));
			}

			if(!$rmsDealer->dealerValidate($dealerId, $password, $dealerGrpId, $dealerGrpName, $isAdmin)) {
				return Response::json(array('result' => false, 'error' => 'Validation Error.'));	
			}

			$option = $rmsDealer->getOption($dealerId);
			$jobs = array();
			$timeZones = array();
			$rmsDealer->getJobs($dealerId, $dealerGrpId, $jobs, $timeZones);

			//Get System List
			$token = URCJWTWork::genJWTTokenDealer($dealerId, $dealerGrpId, $dealerGrpName);

			if($isAdmin) {
				$rmsDealer->registerToken($username, $password, $token);
			}

			
			return Response::json(array('result' => true, 'jobs' => $jobs, 'timezones' =>$timeZones, 
				'company' => $dealerGrpName, 'token' => $token, 'admin' => $isAdmin,
				'opt_menu_show' => $option->menu_show, 'opt_help_show' => $option->help_show));
		}
		else if($funcType == 'get_jobs') {

			$dealer_id = '';
			$dealer_grp_id = '';
			$dealer_grp_name = '';
			if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
				return Response::make($errMsg, $errNo);
			}

			$rmsDealer = new RMSDealer();
			$jobs = array();
			$timeZones = array();
			$rmsDealer->getJobs($dealer_id, $dealer_grp_id, $jobs, $timeZones);
			
			return Response::json(array('result' => true, 'jobs' => $jobs, 'timezones' =>$timeZones));
		}
		else if($funcType == 'get_job') {

			$rules = array(
				'system_id' => 'Required');
			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}	

			$systemId = Input::get('system_id');

			$dealer_id = '';
			$dealer_grp_id = '';
			$dealer_grp_name = '';
			if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
				return Response::make($errMsg, $errNo);
			}

			$rmsDealer = new RMSDealer();
			if(!$rmsDealer->getJob($dealer_id, $dealer_grp_id, $systemId, $job, $timeZone, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}
			
			return Response::json(array('result' => true, 'job' => $job, 'timezone' =>$timeZone));
		}
		else if($funcType == 'get_option') {

			$dealer_id = '';
			$dealer_grp_id = '';
			$dealer_grp_name = '';
			if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
				return Response::make($errMsg, $errNo);
			}

			$rmsDealer = new RMSDealer();
			$option = $rmsDealer->getOption($dealer_id);
			if($option === false) {
				return Response::json(array('result' => false, 'error' => 'Invalid user'));
			}

			return Response::json(array('result' => true, 'option' => $option));
		}
		else if($funcType == 'set_option') {

			$rules = array(
				'menu_show' => 'Required',
				'help_show' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$dealer_id = '';
			$dealer_grp_id = '';
			$dealer_grp_name = '';
			if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
				return Response::make($errMsg, $errNo);
			}

			DB::table('dealer')->where('dealer_id', '=', $dealer_id)->
				update(array('opt_menu_show' => Input::get('menu_show'), 'opt_help_show' => Input::get('help_show')));

			return Response::json(array('result' => true));			
		}
		else if($funcType == 'get_system_token') {

			$rules = array(
				'system_id' => 'Required');
			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}
			$system_id = Input::get('system_id');

			$dealer_id = '';
			$dealer_grp_id = '';
			$dealer_grp_name = '';

			if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
				return Response::make($errMsg, $errNo);
			}

			$system = URCSystemData::isValidSystemForDealer($dealer_grp_id, $system_id);
			if($system === false) {
				return Response::json(array('result' => false, 'error' => 'not permitted to this dealer'));
			}
			$user = DB::table('user')->where('id', '=', $system->user_id)->first();
			if(!$user) {
				return Response::json(array('result' => false, 'error' => 'Invalid user'));
			}
			if(!$user->opt_allow_edit) {
				return Response::json(array('result' => false, 'error' => 'Programming access has been disabled by the user.'));
			}

			$token = URCJWTWork::genJWTToken($user->username, $user->id, $user->level);

			return Response::json(array('result' => true, 'token' => $token));			
		}		
		else if($funcType == 'new_email') {
			
			$rules = array(
				'old_email' => 'Required',
				'new_email' => 'Required',
				'password' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$oldEmail = Input::get('old_email');
			$newEmail = Input::get('new_email');
			$password = Input::get('password');

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			if(!$rmsDealer->changeEmail($oldEmail, $newEmail, $password, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			return Response::json(array('result' => true));
		}		
		else if($funcType == 'new_password') {
			
			$rules = array(
				'email' => 'Required',
				'old_password' => 'Required',
				'new_password' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$email = Input::get('email');
			$oldPass = Input::get('old_password');
			$newPass = Input::get('new_password');

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			if(!$rmsDealer->changePassword($email, $oldPass, $newPass, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			return Response::json(array('result' => true));
		}
		else if($funcType == 'add_user_check') {

			$rules = array(
				'creation_id' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$creationId = Input::get('creation_id');

			$rmsDealer = new RMSDealer();
			$email = '';
			$errMsg = '';
			if(!$rmsDealer->addUserCheck($creationId, $email, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			return Response::json(array('result' => true, 'email' => $email));
		}
		else if($funcType == 'add_user_final') {
			
			$rules = array(
				'creation_id' => 'Required',
				'email' => 'Required',
				'password' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$creationId = Input::get('creation_id');
			$email = Input::get('email');
			$password = Input::get('password');

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			if(!$rmsDealer->addUserFinal($creationId, $email, $password, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}
			
			return Response::json(array('result' => true));
		}



		/////admin functions

		$dealer_id = '';
		$dealer_grp_id = '';
		$dealer_grp_name = '';

		if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}

		$token = URCJWTWork::getTokenFromHeader();
		if($token === false) {
			return Response::json(array('result' => false, 'error' => 'unknown token'));
		}			

		if($funcType == 'get_users') {
			
			$rmsDealer = new RMSDealer();
			$errMsg = '';
			$users = $rmsDealer->getUsers($token, $errMsg);
			if($users === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			return Response::json(array('result' => true, 'data' => $users));
		}
		else if($funcType == 'get_user_data') {

			$rules = array(
				'email' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$email = Input::get('email');

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			$data = $rmsDealer->getUserData($token, $email);
			if($data === false) {
				return Response::json(array('result' => false, 'error' => "fail to get the dealer information"));
			}

			return Response::json(array('result' => true, 'data' => $data));
		}
		else if($funcType == 'get_user_categories') {

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			$data = $rmsDealer->getUserCategories($token);
			if($data === false) {
				return Response::json(array('result' => false, 'error' => "fail to get the categories"));
			}

			return Response::json(array('result' => true, 'data' => $data));
		}
		else if($funcType == 'add_user_prepare') {

			$rules = array(
				'email' => 'Required',
				'account_type' => 'Required',
				'first_name' => 'Required',
				'last_name' => 'Required',
				'phone_number' => 'Required'
				);

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$userData = new stdClass;
			$userData->email = Input::get('email');
			$userData->account_type = Input::get('account_type');
			$userData->first_name = Input::get('first_name');
			$userData->last_name = Input::get('last_name');
			$userData->phone_number = Input::get('phone_number');

			$rmsDealer = new RMSDealer();
			$errMsg = '';
			$data = $rmsDealer->addUserPrepare($token, $userData, $errMsg);
			if($data === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			return Response::json(array('result' => true, 'creation_id' => $data));
		}		
		else if($funcType == 'delete_user') {
			
			$rules = array(
				'email' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$email = Input::get('email');
			
			$rmsDealer = new RMSDealer();
			$errMsg = '';
			if(!$rmsDealer->deleteUser($token, $email, $errMsg)) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}
			
			return Response::json(array('result' => true));
		}

		return Response::json(array('result' => false, 'error' => 'unknown command'));
	}

	/*
	public function updateTempPassword($user, $email, $skipChecking) {

		$urcSystem = new URCSystemData($user->id);
		$arController = $urcSystem->getControllersByUserId();
			
		$bstationMgr = new BStationManager(URCValues::WAIT_SEC);			
		if($skipChecking != true) {

			//update cloud user
			if($bstationMgr->checkConnection($user->sip_id, Crypt::decrypt($user->password), $user->sip_id, $arController) == false) {
				foreach($arController as $item) {
					unset($item->id);
				}
				return $arController;			
			}
		}

		if($bstationMgr->updateUser($user->username, Crypt::decrypt($user->password), Crypt::decrypt($user->password_tmp), $user->sip_id, $email, $arController, $skipChecking) == false) {
			return false;
		}

		if($skipChecking != true) {
			foreach($arController as $item) {
				if($item->connection == 2) {
					ErrorDebug::write('Critical Error: mac:'.$item->mac.'  ctrl_id:'.$item->id);
				}
			}
		}

		//DB Update
		User::where('id', '=', $user->id)->
			update(array('password' => $user->password_tmp, 'password_tmp_set' => 0, 'password_tmp' => ''));

		return true;
	}
	*/

	public function deleteUser($username, $password) {
		
		$editor_type = Config::get('editorenv.editor_type');
		$userChk = User::where('username', '=', $username)->where('editor', '=', $editor_type)->first();

		//ErrorDebug::write(Crypt::decrypt($userChk->password));
		//ErrorDebug::write($password);
		if(!$userChk) {
			//ErrorDebug::write(Crypt::decrypt($userChk->password));
			return false;
		}

		if($password !== Crypt::decrypt($userChk->password)) {
			return false;
		}
		
		$urcSystem = new URCSystemData($userChk->id);
		$systems = $urcSystem->getSystems();

		foreach($systems as $system) {

			$urcSystem->destroySystem($system->id);
		}

		DB::table('a_download')->where('id', '=', $userChk->id)->delete();
		DB::table('user')->where('id', '=', $userChk->id)->delete();
		DB::table('user_detail')->where('user_id', '=', $userChk->id)->delete();

		return true;
	}

}
