<?php

require_once('ErrorDebug.php');

class RMSDealer {

	public function curl_req($path, $req, $token = '')
	{
	    $ch = curl_init();

	    curl_setopt($ch, CURLOPT_URL, Config::get('editorenv.urcRMSServerAddr').'/'.$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);
	    
	    //http_build_query
	    if($req == 'POST') {
	    	curl_setopt($ch, CURLOPT_POST, true );
	    	curl_setopt($ch, CURLOPT_POSTFIELDS, $token);

	    	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    	'application/x-www-form-urlencoded','Content-Length: ' . strlen($token)));
	    }

	    $result = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);

	    //ErrorDebug::write($result);

	    if($httpCode == 200) {
	   		;
	    	return $result;
	    }

	    //ErrorDebug::write($httpCode);

	    return false;
	}

	public function getSerialNumber($mac) {

		$result = $this->curl_req('mxhp_mac_to_serial?mac='.urlencode($mac), 'GET');
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['value']) || 
			$data['ROOT']['results']['value'] != 1 ||
			!isset($data['ROOT']['results']['serial'])) {
			return '';
		}

		return $data['ROOT']['results']['serial'];
	}

	public function isExistingUser($email) {
		
		$result = $this->curl_req('is_existing_login_name?email='.urlencode($email), 'GET');
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		return $data;
	}

	public function login($email, $password, &$dealerId, &$dealerGrpId, &$dealerGrpName, &$isAdmin) {

		$result = $this->curl_req('mxhp_login_check?email='.urlencode($email).'&password='.urlencode($password), 'GET');
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			$dealerId = $data['ROOT']['results']['user_id'];
			$dealerGrpId = $data['ROOT']['results']['dealer_id'];
			$dealerGrpName = $data['ROOT']['results']['dealer_name'];
			$isAdmin = (int)$data['ROOT']['results']['is_dealer_admin'];

			return $data;
		}

		return false;
	}

	public function changeEmail($oldEmail, $newEmail, $password, &$errMsg) {

		$result = $this->curl_req('mxhp_password_admin?fn=change_email&email='.urlencode($oldEmail).
			'&cur_password='.urlencode($password).'&new_email='.urlencode($newEmail), 'GET');
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			$errMsg = 'communication error occurred';
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return true;
		}

		$errMsg = $data['ROOT']['results']['msg'];

		return false;
	}

	public function changePassword($email, $oldPass, $newPass, &$errMsg) {

		$result = $this->curl_req('mxhp_password_admin?fn=change_password&email='.urlencode($email).
			'&cur_password='.urlencode($oldPass).'&new_password='.urlencode($newPass), 'GET');
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			$errMsg = 'communication error occurred';
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return true;
		}

		$errMsg = $data['ROOT']['results']['msg'];

		return false;
	}

	public function registerToken($username, $password, &$token) {
		
		$validHour = Config::get('editorenv.jwtTTL')/3600;
		$validHour += 1;//1hour for reserved

		$result = $this->curl_req('mxhp_set_credential_token?email='.urlencode($username).
			'&password='.urlencode($password).'&validity_hours='.$validHour, 'POST', 'token='.$token);
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return true;
		}

		return false;
	}

	public function getDealerData($dealerId) {
	
		$result = $this->curl_req('mxhp_user_id_to_contact_info?user_id='.urlencode($dealerId), 'GET');
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return $data['ROOT']['results'];
		}

		return false;
	}

	public function getUsers(&$token, &$errMsg) {

		$result = $this->curl_req('mxhp_dealer_user_admin?fn=get_users', 'POST', 'token='.$token);
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$option = array('alwaysArray' => array('user'));
		$data = StringGenerator::xmlToArray($xml, $option);

		if(!isset($data['ROOT']['users']['user'])) {
			$empty = array();
			return $empty;
		}
		
		return $data['ROOT']['users']['user'];
	}

	public function getUserData(&$token, $email) {
	
		$result = $this->curl_req(
			'mxhp_dealer_user_admin?fn=get_dealer_member_info&target_email='.urlencode($email), 'POST', 'token='.$token);
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return $data['ROOT']['results'];
		}
		
		return false;
	}

	public function getUserCategories(&$token) {
		
		$result = $this->curl_req(
			'mxhp_dealer_user_admin?fn=get_user_categories', 'POST', 'token='.$token);
		if($result == false) return false;
		
		$xml = simplexml_load_string($result);
		$option = array('alwaysArray' => array('type'));
		$data = StringGenerator::xmlToArray($xml, $option);

		if(!isset($data['ROOT']['account_types']['type'])) {
			return false;
		}

		return $data['ROOT']['account_types']['type'];
	}

	public function deleteUser(&$token, $email, $errMsg) {

		$result = $this->curl_req(
			'mxhp_dealer_user_admin?fn=delete_user&target_email='.urlencode($email), 'POST', 'token='.$token);
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);
		
		if(!isset($data['ROOT']['results']['result'])) {
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return true;
		}

		return false;
	}

	public function addUserPrepare(&$token, &$userData, &$errMsg) {

		$result = $this->curl_req(
			'mxhp_dealer_user_admin?fn=add_user_prepare&target_email='.urlencode($userData->email).
			'&account_type='.urlencode($userData->account_type).
			'&first_name='.urlencode($userData->first_name).
			'&last_name='.urlencode($userData->last_name).
			'&phone_number='.urlencode($userData->phone_number).
			'&product='.urlencode(Config::get('editorenv.editor_name')), 'POST', 'token='.$token);

		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			$errMsg = 'communication error occurred';
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return $data['ROOT']['results']['creation_id'];
		}
		
		$errMsg = $data['ROOT']['results']['msg'];

		return false;
	}

	public function addUserCheck($creationId, &$email, &$errMsg) {
		
		$result = $this->curl_req('mxhp_dealer_user_admin?fn=add_user_check&creation_id='.urlencode($creationId), 'GET');
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			$errMsg = 'communication error occurred';
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			$email = $data['ROOT']['results']['email'];
			return true;
		}

		$errMsg = $data['ROOT']['results']['msg'];

		return false;
	}
	

	public function addUserFinal($creationId, $email, $password, &$errMsg) {
		
		$result = $this->curl_req(
			'mxhp_dealer_user_admin?fn=add_user_final&creation_id='.urlencode($creationId).'&email='.
			urlencode($email).'&new_password='.urlencode($password), 'GET');
		if($result == false) {
			$errMsg = 'communication error occurred';
			return false;
		}
		
		$xml = simplexml_load_string($result);
		$data = StringGenerator::xmlToArray($xml);

		if(!isset($data['ROOT']['results']['result'])) {
			$errMsg = 'communication error occurred';
			return false;
		}

		if($data['ROOT']['results']['result'] == '1') {

			return true;
		}

		$errMsg = $data['ROOT']['results']['msg'];

		return false;
	}			


	public function dealerValidate($dealerId, $password, $dealerGrpId, $dealerGrpName, $isAdmin) {
		
		$user = DB::table('dealer')->where('dealer_id', '=', $dealerId)->first();

		try
		{
			if(!$user) {
				DB::table('dealer')->insert(
					array('dealer_id' => $dealerId, 'dealer_grp_id' => $dealerGrpId,
						'dealer_grp_name' => $dealerGrpName,
						'password' => Crypt::encrypt($password), 'hdr' => 'a',
						'status' => 1, 'editor' => Config::get('editorenv.editor_type'), 'admin' => $isAdmin));
			}
			else {
				if($user->dealer_grp_id != $dealerGrpId) {
					return false;
				}

				if($user->dealer_grp_name !== $dealerGrpName || $user->admin !== $isAdmin) {
					DB::table('dealer')->where('dealer_id', '=', $dealerId)->update(array('dealer_grp_name' => $dealerGrpName, 'admin' => $isAdmin));
				}
			}
		}
		catch(\Exception $e) 
		{
			return false;//return Response::json(array('result' => false, 'error' => $e->getMessage()));//'db error'));
		}

		/*
		$newUser = new Dealer;
		if($newUser->getByDealerId($dealerId)) {

			if($newUser->dealer_grp_id != $dealerGrpId) {
				return false;
			}

			if($newUser->dealer_grp_name !== $dealerGrpName) {
				Dealer::where('dealer_id', '=', $dealerId)->update(array('dealer_grp_name' => $dealerGrpName));
			}

			return true;
		}			

		$newUser->dealer_id = $dealerId;
		$newUser->dealer_grp_id = $dealerGrpId;
		$newUser->dealer_grp_name = $dealerGrpName;
		$newUser->password = Crypt::encrypt($password);
		$newUser->hdr = 'a';
		$newUser->status = 1;
		$newUser->editor = Config::get('editorenv.editor_type');
		//DB insert
		try
		{
			DB::transaction(function() use ($newUser)
			{	
				ErrorDebug::write('aa1');
				if(!$newUser->save()) {
					ErrorDebug::write('aa2');
					throw new \Exception('db error');
				}
				ErrorDebug::write('aa3');
			});
		}
		catch(\Exception $e) 
		{
			return false;//return Response::json(array('result' => false, 'error' => $e->getMessage()));//'db error'));
		}
		*/

		return true;
	}

	public function getJobs($dealerId, $dealerGrpId, &$jobs, &$timeZones) {

		$jobs = DB::table('a_systems')->where('dealer_grp_id', '=', $dealerGrpId)->
			select('id', 'controller_id', 'name', 'timezone_id', 'timezone_dst', 'time_type',
			'dealer_id', 'dealer_grp_id', 'c_address', 'c_name', 'created_at', 'updated_at')->get();

		$arTimezoneId = array();
		foreach($jobs as $job) {
			$arTimezoneId[] = $job->timezone_id;
		}
		$arValidTimezoneId = array_unique($arTimezoneId);
		if(count($arValidTimezoneId) > 0) {
			$timeZones = DB::table('timezone')->whereIn('id', $arValidTimezoneId)->get();
		}
	}

	public function getJob($dealerId, $dealerGrpId, $systemId, &$job, &$timeZone, &$errMsg) {

		$job = DB::table('a_systems')->where('dealer_grp_id', '=', $dealerGrpId)->
			where('id', '=', $systemId)->first();

		if(!$job) {
			$errMsg = "can't find the job";
			return false;
		}

		$userChk = DB::table('user_detail')->where('user_id', '=', $job->user_id)->first();
		if($userChk) {
			$job->c_email = $userChk->user_email;
		}

		$timeZone = DB::table('timezone')->where('id', '=', $job->timezone_id)->first();
		if(!$timeZone) {
			$errMsg = "can't find the timezone";
			return false;
		}

		return true;
	}

	public function getOption($dealerId) {

		$user = DB::table('dealer')->where('dealer_id', '=', $dealerId)->first();
		if(!$user) {
			return false;
		}

		$option = new stdClass;
		$option->menu_show = $user->opt_menu_show;
		$option->help_show = $user->opt_help_show;

		return $option;
	}
}
