<?php

require_once('URCSystemData.php');


class CmdController 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) {
			return false;
		}

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

		return $userChk;
	}
	
	public static function chkAuthControllerAdmin(&$mac) {

		$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;
		}

		$mac = $pieces[0];
		if(strlen($mac) !== 12) {
			return false;
		}

		if(!URCValues::isMatchBStationAdminPass($pieces[1])) {
			return false;
		}

		return true;
	}

	public function doFunc($funcType) {

		if($funcType == 'get_controller_id') {

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

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

			$modelId = Input::get('model_id');

			if(URCValues::getModelTypeFromId($modelId) === false) {
				return Response::json(array('result' => false, 'error' => 'not valid model id'));
			}
			
			$mac = '';
			if(CmdController::chkAuthControllerAdmin($mac) === false) {

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

			$user = DB::table('sip_user')->where('mac', '=', $mac)->first();
			if(!$user) {

				$sip_id = URCValues::genSIPUserID($mac);
				$password = URCValues::genSIPUserPass();
				$controller_id = URCValues::genSIPControllerID($modelId, $mac);
				
				$httpCode = '';
				$bstationMgr = new BStationManager(URCValues::WAIT_SEC);
				if($bstationMgr->createUser($sip_id, $password, $httpCode) !== true) {
					if($httpCode !== 400) {			
						ErrorDebug::write('Critical => sip_id:'.$sip_id.'  password:'.$password);			
						return Response::json(array('result' => false, 'error' => $bstationMgr->getErrMsg()));
					}

					//already exist
					if($bstationMgr->createBasestation($sip_id, $password, $controller_id) !== true) {
						ErrorDebug::write('Critical => sip_id:'.$sip_id.'  password:'.$password.'  controller:'.$controller_id);
						return Response::json(array('result' => false, 'error' => $bstationMgr->getErrMsg()));
					}
				}
				else {

					if($bstationMgr->createBasestation($sip_id, $password, $controller_id) !== true) {
						$bstationMgr->deleteUser($sip_id);
						ErrorDebug::write('Critical NEW => sip_id:'.$sip_id.'  password:'.$password.'  controller:'.$controller_id);
						return Response::json(array('result' => false, 'error' => $bstationMgr->getErrMsg()));
					}
				}

				try
				{
					DB::table('sip_user')->insert(array('mac' => $mac, 'sip_id' => $sip_id, 
						'password' => Crypt::encrypt($password), 'controller_id' => $controller_id));
				}
				catch(\Exception $e) 
				{
					return Response::json(array('result' => false, 'error' => 'can not insert'));		
				}
				
				$user = DB::table('sip_user')->where('mac', '=', $mac)->first();
				if(!$user) {
					return Response::json(array('result' => false, 'error' => 'insert error'));		
				}
			}

			//ErrorDebug::write(json_encode(array('result' => true, 'id' => $user->sip_id, 'password' => Crypt::decrypt($user->password), 'controller_id' => $user->controller_id)));


			return Response::json(array('result' => true, 'id' => $user->sip_id, 'password' => Crypt::decrypt($user->password), 'controller_id' => $user->controller_id));		
		}

		if($funcType == 'get_sip_id') {

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

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

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

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

			$controllerId = Input::get('controller_id');
			$user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$user) {
				return Response::json(array('result' => false, 'error' => 'not valid - unknown controller id'));		
			}

			return Response::json(array('result' => true, 'id' => $user->sip_id, 'password' => Crypt::decrypt($user->password)));
		}

		if($funcType == 'update_schedule') {

			$rules = array(
				'system_id' => 'Required',
				'room_id' => 'Required',
				'event_id' => 'Required',
				'day_week' => 'Required',
				'time' => 'Required');

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

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

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

			$systemId = Input::get('system_id');
			$roomId = Input::get('room_id');
			$eventId = Input::get('event_id');
			$dayWeek = Input::get('day_week');
			$time = Input::get('time');

			if(!URCSystemData::isValidRoom($userChk->id, $roomId)) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$scheObj = new URCScheEventData($systemId, $roomId);
			$result = $scheObj->updateEventTime($eventId, $dayWeek, $time);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to update' ));
			}

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

}