<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

ob_start();

include_once('config.php');
include_once('entities.php');
include_once('core.php');
include_once('pusher.php');

$mode = array_key_exists('mode', $_GET) ? trim($_GET['mode']) : null;
$result = '';

$appId = '74611';
$appKey = '0f1251f9cdd3135dbbd3';
$appSecret = 'e999b2c861798a1da590';

$pusher = new Pusher( $appKey, $appSecret, $appId );

if (!isset($mode))
{
	$result = 'ERROR_UNKNOWN_MODE';
}
else
{
	$core = new Core();

	$core->dbHost = $mysql_host;
	$core->dbUser = $mysql_user;
	$core->dbPass = $mysql_password;
	$core->dbName = $mysql_database;

	$core->startDBConnection();

	switch ($mode)
	{
		case 'save_user':

		$user = new User();

		$user->cityId       = isset($_POST['cityId'])       ? urldecode($_POST['cityId'])       : null;
		$user->email        = isset($_POST['email'])        ? urldecode($_POST['email'])        : null;
		$user->password     = isset($_POST['password'])     ? urldecode($_POST['password'])     : null;
		$user->fullName     = isset($_POST['fullName'])     ? urldecode($_POST['fullName'])     : null;
		$user->registration = isset($_POST['registration']) ? urldecode($_POST['registration']) : null;
		$user->latitude		= isset($_POST['latitude']) 	? urldecode($_POST['latitude']) 	: null;
		$user->longitude	= isset($_POST['longitude']) 	? urldecode($_POST['longitude']) 	: null;

		$emailExists         = $core->getUserIdByEmail($user->email); //data existe ! null no existe
		$emailExistsInClient = $core->getClientIdByEmail($user->email);
		$userExists          = $core->getUserByUserId($user->userId);


		if(isset($emailExists) || isset($emailExistsInClient) || isset($userExists)) {
			if(isset($emailExists) || isset($emailExistsInClient)){
				$result = 'ERROR_EMAIL_EXISTS';
			}else if(isset($userExists)){
				$result = 'ERROR_USER_EXISTS';
			}
		}else {
			$core->saveUser($user);

			$result = 'OK_USER_SAVED';
		}

		break;

		case 'save_client':

		$client = new Client();

		$client->cityId       	= isset($_POST['cityId'])       	? urldecode($_POST['cityId'])       	: null;
		$client->email        	= isset($_POST['email'])        	? urldecode($_POST['email'])        	: null;
		$client->password     	= isset($_POST['password'])     	? urldecode($_POST['password'])     	: null;
		$client->fullName     	= isset($_POST['fullName'])     	? urldecode($_POST['fullName'])     	: null;
		$client->dni          	= isset($_POST['dni'])          	? urldecode($_POST['dni'])          	: null;
		$client->registration 	= isset($_POST['registration']) 	? urldecode($_POST['registration']) 	: null;
		$client->jobs         	= isset($_POST['jobs'])         	? urldecode($_POST['jobs'])         	: null;
		$client->isActive	  	= isset($_POST['isActive'])	  		? urldecode($_POST['isActive']) 	  	: null;
		$client->averageRating	= isset($_POST['averageRating']) 	? urldecode($_POST['averageRating']) 	: null;
		$client->latitude	  	= isset($_POST['latitude'])	  		? urldecode($_POST['latitude']) 	  	: null;
		$client->longitude	  	= isset($_POST['longitude']) 		? urldecode($_POST['longitude']) 	  	: null;

		$profilePhoto = isset($_POST['image'])         ? urldecode($_POST['image'])         : null;

		$emailExists       = $core->getClientIdByEmail($client->email); //data existe ! null no existe
		$emailExistsInUser = $core->getUserIdByEmail($client->email);
		$clientExists      = $core->getClientIdByDni($client->dni);


		if(isset($emailExists) || isset($emailExistsInUser) || isset($clientExists)) {
			if( isset($emailExists) || isset($emailExistsInUser) ){
				$result = 'ERROR_EMAIL_EXISTS';
			}else if(isset($clientExists)){
				$result = 'ERROR_DNI_EXISTS';
			}
		}else {
			$index = $core->saveClient($client);

			if ( !!$profilePhoto ) {
				if ( !!strstr( $profilePhoto, "data:image/jpeg;base64," ) ) {
					$extension = '.jpg';
				} else {
					$extension = '.png';
				}
				$profilePhoto = str_replace("data:image/jpeg;base64,","",$profilePhoto);
				$profilePhoto = str_replace("data:image/png;base64,","",$profilePhoto);
				file_put_contents('../img/profiles/'.$index.$extension, base64_decode($profilePhoto));
			}

			$core->saveJobsByClient( explode(',',$client->jobs), $index );

			$result = 'OK_USER_SAVED';
		}

		break;

		case 'login':

		$user = new User();

		$user->email        = isset($_POST['email'])        ? urldecode($_POST['email'])        : null;
		$user->password     = isset($_POST['password'])     ? urldecode($_POST['password'])     : null;

		$existingUser  = $core->getUserByEmail($user->email); //data existe ! null no existe
		$existingClient = $core->getClientByEmail($user->email);

		if( isset($existingUser) || isset($existingClient) ) {
			if ( isset($existingClient) ) {
				$matches = $core->clientMatches( $user );
			} else {
				$matches = $core->userMatches( $user );
			}
		} else {
			$result = 'ERROR_EMAIL_DOESNT_EXISTS';
			break;
		}

		if ( $matches ) {
			$result = 'OK_USER_CORRECT';
			/*
			if( isset($existingUser) ) {
				$result = 'USER_LOGGED_IN';
			}
			else {
				$result = 'CLIENT_LOGGED_IN';
			}
			*/
			$isLoggedIn = true;
		} else {
			$result = 'ERROR_WRONG_PASSWORD';
		}

		// if(isset($emailExistsInUser) || isset($emailExistsInClient) || isset($userExists)) {
		// 	if(isset($emailExists) || isset($emailExistsInClient)){
		// 		$result = 'ERROR_EMAIL_EXISTS';
		// 	}else if(isset($userExists)){
		// 		$result = 'ERROR_USER_EXISTS';
		// 	}
		// }else {
		// 	$core->saveUser($user);

		// 	$result = 'OK_USER_SAVED';
		// }

		break;

		case 'set_is_active':

		$client = new Client();

		$email        = isset($_POST['email'])        ? urldecode($_POST['email'])        : null;

		$existingClient = $core->getClientByEmail($email); //data existe ! null no existe
		$existingUser  = $core->getUserByEmail($email);

		if( isset($existingUser) || isset($existingClient) ) {

			$result = 'OK_USER_CORRECT';

			if( isset($existingClient) ) {
				$existingClient->isActive  = isset($_POST['isActive'])        ? urldecode($_POST['isActive'])        : null;
				$core->updateClient( $existingClient );

				$result = $existingClient->isActive;
			}


		} else {
			$result = 'ERROR_EMAIL_DOESNT_EXISTS';
			break;
		}
		
		break;

		case 'client_is_active':

		$client = new Client();

		$client->email        = isset($_POST['email'])        ? urldecode($_POST['email'])        : null;

		$isActive = $core->clientIsActive($client);
		
		$result = $isActive;

		break;

		case 'get_jobs' :

		$leResult = $core->getJobs();
		$result = json_encode( $leResult );

		break;

		case 'get_cities' :

		$leResult = $core->getCities();
		$result = json_encode( $leResult );

		break;

		case 'get_near_active_clients_by_user_and_jobs' :

		$user = new User();

		$user->latitude        = isset($_POST['latitude'])        ? urldecode($_POST['latitude'])        : null;
		$user->longitude       = isset($_POST['longitude'])       ? urldecode($_POST['longitude'])        : null;
		$jobs                  = isset($_POST['jobs'])            ? urldecode($_POST['jobs'])        : null;

		$nearClients = $core->getNearActiveClientsByUserAndJobs($user, explode(',',$jobs));
		
		for ($i=0; $i < count($nearClients); $i++) { 
			$nearClients[$i]["jobs"] = $core->getJobsByClientId($nearClients[$i]);
			//12
		}

		$result = json_encode( $nearClients );

		break;

		case 'set_current_location':

		$overrideLocation   = isset($_POST['overrideLocation'])     ? urldecode($_POST['overrideLocation'])     : null;

		if ($overrideLocation) {
			return;
		}

		$user = new User();

		$user->email           = isset($_POST['email'])        ? urldecode($_POST['email'])        : null;
		$user->latitude        = isset($_POST['latitude'])     ? urldecode($_POST['latitude'])     : null;
		$user->longitude       = isset($_POST['longitude'])    ? urldecode($_POST['longitude'])    : null;

		$existingUser  = $core->getUserByEmail($user->email); //data existe ! null no existe
		$existingClient = $core->getClientByEmail($user->email);

		if( isset($existingUser) || isset($existingClient) ) {

			$result = 'OK_USER_CORRECT';
			
			if ( isset($existingClient) ) {
				$existingClient->latitude = $user->latitude;
				$existingClient->longitude = $user->longitude;
				$core->updateClient( $existingClient );
			} else {
				$existingUser->latitude = $user->latitude;
				$existingUser->longitude = $user->longitude;
				$core->updateUser( $existingUser );
			}
		} else {
			$result = 'ERROR_EMAIL_DOESNT_EXISTS';
			break;
		}

		break;

		case 'user_request':

		$user = new User();
		$user->email        = isset($_POST['userEmail'])      ? urldecode($_POST['userEmail'])      : null;
		$user = $core->getUserByEmail($user->email);
		$user->password = null;

		$client = new Client();
		$client->clientId    = isset($_POST['clientId'])    ? urldecode($_POST['clientId'])    : null;
		$client = $core->getClientByClientId($client->clientId);

		$jobIds              = isset($_POST['jobIds'])      ? urldecode($_POST['jobIds'])      : null;
		$client->jobs        = $core->getJobsByIds(explode(',',$jobIds));

		$mail = $core->sendMailToClient($user, $client);

		$address             = isset($_POST['address'])     ? urldecode($_POST['address'])     : null;

		$response['address'] = $address;
		$response['user'] = $user;
		$response['jobs'] = $client->jobs;
		$response['clientId'] = $client->clientId;

		$channel = "appelo-" . $client->email;
		$pusher->trigger( $channel , 'request', $response );

		$result = json_encode( $mail );

		break;

		case 'prueba':

		$user = new User();
		$user->fullName = "Lol Perez";
		$user->email = "lol@perez.com";

		$client = new Client();
		$client->fullName = "Estilista Gay";
		$client->email = "juanlajara@gmail.com";
		$client->jobs = "Faciales, Faciales y más...";

		$result = json_encode($core->sendMailToClient($user, $client));

		break;

		case 'prueba2':

		$user = new User();
		$user->fullName = "Lol Perez";
		$user->email = "lol@perez.com";

		$client = new Client();
		$client->fullName = "Estilista Gay";
		$client->email = "juanlajara@gmail.com";
		$client->jobs = "Faciales, Faciales y más...";

		$result = json_encode($core->sendMailToUser($user, $client));

		break;

		case 'client_response':

		$appointment = new Appointment();
		$appointment->userId   = isset($_POST['userId'])      ? urldecode($_POST['userId'])      : null;
		$appointment->clientId = isset($_POST['clientId'])    ? urldecode($_POST['clientId'])    : null;

		$core->saveAppointment($appointment);

		$user = $core->getUserByUserId($appointment->userId);

		$client = $core->getClientByClientId($appointment->clientId);
		$client->isActive = false;
		$core->updateClient($client);

		$mail = $core->sendMailToUser($user, $client);

		$response['appointmentCreated'] = true;

		$channel = "appelo-" . $user->email;
		$pusher->trigger( $channel , 'response', $response );

		$result = json_encode( $mail );

		break;

		case 'rate_appointment':

		$appointment = new Appointment();
		$appointment->appointmentId   = isset($_POST['appointmentId'])      ? urldecode($_POST['appointmentId'])      : null;
		$appointment->clientId        = isset($_POST['clientId'])           ? urldecode($_POST['clientId'])           : null;
		$appointment->rating          = isset($_POST['rating'])             ? urldecode($_POST['rating']) * 2         : null;

		$core->rateAppointment($appointment);

		break;

		default:
		$result = 'ERROR_UNKNOWN_MODE';
		break;
	}

	$core->endDBConnection();
}

die($result);
?>