<?php

require_once('URCSystemData.php');


class CSPController extends BaseController {

	public static function chkAuthorization() {

		$aHeaders = getallheaders();
		if(!array_key_exists('Authorization', $aHeaders)) {
			return false;
		}

		$authorization = $aHeaders['Authorization'];
		if(strncmp($authorization, "Basic ", 6)) {
			return false;
		}

		$token = substr($authorization, 6);
		$decodedData = base64_decode($token);

		$pieces = explode(':', $decodedData);

		if(count($pieces) < 2) {
			return false;
		}

		$user = $pieces[0];
		$pass = $pieces[1];

		$editor_type = Config::get('editorenv.editor_type');
		$userChk = User::where('username', '=', $user)->where('editor', '=', $editor_type)->first();
		if(!$userChk) {

			$userChk = new stdClass;
			$userChk->username = Config::get('editorenv.urcCSPServerAdmin');
			$userChk->password = Config::get('editorenv.urcCSPServerAdminPass');
				
			if($user === $userChk->username && $pass === $userChk->password) {
				
				$userChk->id = -1;
				return $userChk;
			}

			return false;
		}

		if($pass !== Crypt::decrypt($userChk->password)) {
			return false;
		}

		return $userChk;
	}

	public function isAdmin($username) {

		if($username === Config::get('editorenv.urcCSPServerAdmin'))
			return true;

		return false;
	}

	public function isFactory($macAddr, &$defaultCtrlId) {

		/*
		$bstationMgr = new BStationManager(URCValues::WAIT_SEC);
		if(!$bstationMgr->getBasestations($bstationMgr->defaultUniqueId, $bstationMgr->defaultPass, $bstationMgr->defaultUniqueId, $macAddr, 10, $resultData)) {
			return 'U';
		}

		$bstationData = json_decode($resultData);	
		if(isset($bstationData->items) && count($bstationData->items) > 0) {

			$defaultCtrlId = $bstationData->items[0]->controller_id;
			return 'Y';
		}

		return 'N';
		*/

		return 'U';
	}

	public function getEditorVersionInfo(&$editorVer, &$errorInfo) {

		$verFileName = './scripts/version.json';
		if(!file_exists($verFileName)) { 

			$errorInfo = "can't find the editor version file";			
			return false;
		}
		
		$verJson = file_get_contents($verFileName);
		$verData = json_decode($verJson);
		if(!isset($verData->version)) {
			$errorInfo = "Wrong version file";
			return false;
		}

		$editorVer = $verData->version;
		
		return true;
	}
	
	public function getFirmVersionInfo($modelType, &$firmVer, &$errorInfo) {

		$infoFileName = './file/'.$modelType.'/Info.json';
		if(!file_exists($infoFileName)) { 

			$errorInfo = "can't find the firmware version";			
			return false;
		}
		
		$infoJson = file_get_contents($infoFileName);
		$infoData = json_decode($infoJson);
		if(!isset($infoData->files)) {
			$errorInfo = "Wrong firmware information file";			
			return false;
		}

		$infoDataCnt = count($infoData->files);
		if($infoDataCnt < 1) {
			$errorInfo = "Wrong firmware information file";			
			return false;
		}
		
		for($idx = 0; $idx < $infoDataCnt; $idx++) {

			if($infoData->files[$idx]->name == 'RCMain') {
				$firmVer = $infoData->files[$idx]->version;
				return true;
			}
			else if($infoData->files[$idx]->name == 'BSMain') {
				$firmVer = $infoData->files[$idx]->version;
				return true;
			}
		}

		$errorInfo = "Wrong firmware information file";			
		return false;
	}

	public function getRealSystemInfo($macAddr, &$userInfo, &$system, &$bstationInfo, &$errorInfo) {

		$bstationInfo = DB::table('a_bstations')->where('mac', '=', $macAddr)->first();
		if(!$bstationInfo) {
			$errorInfo = 'not valid basestation';
			return false;
		}

		$system = DB::table('a_systems')->where('id', '=', $bstationInfo->system_id)->first();
		if(!$system) {
			$errorInfo = 'not valid basestation';
			return false;
		}

		if($system->user_id !== $userInfo->id) {

			if(!$this->isAdmin($userInfo->username)) {
				return Response::json(array('result' => false, 'error' => 'not valid info'));
			}

			$editor_type = Config::get('editorenv.editor_type');
			$userInfo = User::where('id', '=', $system->user_id)->where('editor', '=', $editor_type)->first();
			if(!$userInfo) {
				$errorInfo = 'not valid user info';
				return false;
			}
		}

		return true;
	}

	public function applySystemInfoToBasestation(&$bstations, &$systems) {

		//get user ids
		$userIdsAll = array();
		foreach($systems as $system) {

			//apply profile
			foreach($bstations as $bstation) {
				if($bstation->SystemId === $system->id) {
					$bstation->Profile = $system->name;
					$bstation->UserId = $system->user_id;
					$bstation->OperatingMode = 'M';
					break;
				}
			}

			//add user
			$userIdsAll[] = $system->user_id;
		}
		$userIds = array_unique($userIdsAll);

		//get user info
		$users = DB::table('user')->join('user_detail', function($join)
		{
			$join->on('user.id', '=', 'user_detail.user_id')
				->where('user.editor', '=', Config::get('editorenv.editor_type'));
		})->whereIn('user.id', $userIds)->get();
		
		//apply user info
		foreach($bstations as $bstation) {

			if(!isset($bstation->UserId)) continue;

			foreach($users as $user) {
				if($bstation->UserId === $user->id) {
					$bstation->username = $user->username;
					$bstation->email = $user->user_email;
					break;
				}
			}

			unset($bstation->UserId);
		}
	}

	public function doFunc($funcType) {

		if($funcType == 'get_software_version') {

			$rules = array(
				//'ServerChannel' => 'Required',
				'Model' => 'Required');

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

			//$svrChannel = Input::get('ServerChannel');
			$modelType = Input::get('Model');

			$editorVer = '';
			$errorInfo = '';
			if($this->getEditorVersionInfo($editorVer, $errorInfo) == false) {
				return Response::json(array('result' => 'false', 'error' => $errorInfo));
			}

			$firmVer = '';
			$errorInfo = '';
			if($this->getFirmVersionInfo($modelType, $firmVer, $errorInfo) == false) {
				return Response::json(array('result' => 'false', 'error' => $errorInfo));
			}

			return Response::json(array('result' => 'true', 'EditorVersion' => $editorVer, 'FVersion' => $firmVer));
		}

		if($funcType == 'get_controller_info') {

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

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

			$userChk = CSPController::chkAuthorization();
			if($userChk === false) {

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

			$macAddr = Input::get('MAC');
			
			$isFactory = $this->isFactory($macAddr, $factoryCtrlId);
			
			$system = null;
			$bstationInfo = null;
			$errorInfo = '';
			if($this->getRealSystemInfo($macAddr, $userChk, $system, $bstationInfo, $errorInfo) == false) {
				if($isFactory == 'Y') {
					return Response::json(array('Result' => 'true', 'IsFactoryMode' => $isFactory, //'SipUsername' => $userChk->sip_id, 
						'ControllerID' => $factoryCtrlId));
				}
				return Response::json(array('result' => 'false', 'error' => $errorInfo));
			}

			$userDetail = DB::table('user_detail')->where('user_id', '=', $userChk->id)->first();
			if(!$userDetail) {
				return Response::json(array('result' => 'false', 'error' => 'not valid info'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $system->controller_id)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}
	
			//$arData = array('Result' => 'true', 'Model' => $bstationInfo->type, 'IsFactoryMode' => $isFactory, 'EditorUsername' => $userChk->username, 
			//	'SipUsername' => $sip_user->sip_id, 'ControllerID' => $system->controller_id, 'FullName' => $userChk->username, 
			//	'Email' => $userDetail->user_email);

			return Response::json(array('Result' => 'true', 'Model' => $bstationInfo->type, 'IsFactoryMode' => $isFactory, 'EditorUsername' => $userChk->username, 
				'SipUsername' => $sip_user->sip_id, 'ControllerID' => $system->controller_id, 'FullName' => $userChk->username, 
				'Email' => $userDetail->user_email));
		}

		if($funcType == 'get_slave_controllers') {

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

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

			$userChk = CSPController::chkAuthorization();
			if($userChk === false) {

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

			$macAddr = Input::get('MAC');

			$system = null;
			$bstationInfo = null;
			$errorInfo = '';
			if($this->getRealSystemInfo($macAddr, $userChk, $system, $bstationInfo, $errorInfo) == false) {
				return Response::json(array('result' => 'false', 'error' => $errorInfo));
			}

			$systems = DB::table('a_bstations')->where('system_id', '=', $system->id)->where('master', '=', 0)->select('mac as MAC', 'type as Model')->get();
			foreach($systems as $system) {
				$system->OperatingMode = 'S';
			}
			
			return Response::json(array('result' => 'true', 'controllers' => $systems));		
		}

		if($funcType == 'get_remote_controllers') {

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

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

			$userChk = CSPController::chkAuthorization();
			if($userChk === false) {

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

			$macAddr = Input::get('MAC');

			$system = null;
			$bstationInfo = null;
			$errorInfo = '';
			if($this->getRealSystemInfo($macAddr, $userChk, $system, $bstationInfo, $errorInfo) == false) {
				return Response::json(array('result' => 'false', 'error' => $errorInfo));
			}

			$remotes = DB::table('a_remotes')->where('system_id', '=', $system->id)->select('mac as MAC', 'type as Model')->get();


			return Response::json(array('result' => 'true', 'remotes' => $remotes));		
		}

		if($funcType == 'get_master_controllers') {

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

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

			$userChk = CSPController::chkAuthorization();
			if($userChk === false) {

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

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

			$editor_type = Config::get('editorenv.editor_type');
   			$userReal = User::where('username', '=', $username)->where('editor', '=', $editor_type)->first();
   			if(!$userReal) {
   				return Response::json(array('result' => 'false', 'error' => 'not valid'));
   			}

   			if($userChk->id !=  $userReal->id) {
				if(!$this->isAdmin($userChk->username)) {
					return Response::json(array('result' => 'false', 'error' => 'not valid info'));
				}

				$userChk = $userReal;
			}

			//get systems
			$systems = DB::table('a_systems')->where('user_id', '=', $userChk->id)->get();
			if(!$systems || count($systems) < 1) {
				return Response::json(array('result' => 'false', 'error' => 'not found any system'));
			}

			//get system ids
			$systemIds = array();
			foreach($systems as $system) {
				$systemIds[] = $system->id;
			}

			//get user email
			$useremail = '';
			$userDetail = DB::table('user_detail')->where('user_id', '=', $userChk->id)->first();
			if($userDetail) {
				$useremail = $userDetail->user_email;
			}
	
			//apply info with system ids
			$bstations = DB::table('a_bstations')->whereIn('system_id', $systemIds)->where('master', '=', 1)->select('mac as MAC', 'type as Model', 'system_id as SystemId')->get();
			foreach($bstations as $bstation) {
				foreach($systems as $system) {

					if($bstation->SystemId === $system->id) {
						$bstation->Profile = $system->name;
						break;
					}
				}

				$bstation->OperatingMode = 'M';
				$bstation->username = $userChk->username;
				$bstation->email = $useremail;
			}
			
			return Response::json(array('result' => 'true', 'controllers' => $bstations));		
		}

		if($funcType == 'search_master_controllers') {

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

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

			$userChk = CSPController::chkAuthorization();
			if($userChk === false) {

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

			if(!$this->isAdmin($userChk->username)) {
				return Response::json(array('result' => 'false', 'error' => 'not valid info'));
			}

			$macAddr = Input::get('MAC');

			//search bstation with mac
			$bstations = DB::table('a_bstations')->where('mac', 'LIKE', "%$macAddr%")->where('master', '=', 1)->select('mac as MAC', 'type as Model', 'system_id as SystemId')->take(5)->get();

			//get system ids
			$systemIds = array();
			foreach($bstations as $bstation) {
				$systemIds[] = $bstation->SystemId;
			}

			//get systems
			$systems = DB::table('a_systems')->whereIn('id', $systemIds)->get();

			//apply info with systems
			if($systems && count($systems) > 0) {
				$this->applySystemInfoToBasestation($bstations, $systems);
			}
			
			return Response::json(array('result' => 'true', 'controllers' => $bstations));
		}
		
		return Response::json(array('result' => 'false', 'error' => 'unknown command'));
	}

}