<?php

//error_reporting( E_ALL & ~E_STRICT );
//ini_set('display_errors', 1);
date_default_timezone_set("Europe/Madrid");

session_cache_limiter(false);
session_name('labrtvees');
session_start();

require_once( "staticDB.php" );
require_once( "../../commons/libs/Slim/Slim.php" );
require_once '../../commons/libs/Twig/Autoloader.php';
require_once( "../../commons/libs/hybridauth-2.3.0/Hybrid/Auth.php" );

\Slim\Slim::registerAutoloader();
Twig_Autoloader::register();

$templateDir = 'views';
$loader = new Twig_Loader_Filesystem(array($templateDir));
$twig = new Twig_Environment($loader, array(
	'debug' => true,// quitar en PRO
));
$twig->addExtension(new Twig_Extension_Debug()); // quitar en PRO

$config = dirname(__FILE__) . '/hybridauth/config.php';
$hybridauth = new Hybrid_Auth( $config );

/************ VARIABLES COMUNES *************/

$app = new \Slim\Slim(array(
	 // Config requirements for default Slim Auth implementation
    'cookies.encrypt' => true,
    'cookies.secret_key' => 'El laboratorio de RTVE',
	'name' => 'labrtve'
));


$customConfig = array(
	'baseURL'=>'/los-goya/porra',
	'title'=>'Porra para los Goya 2015 '
);

$customConfig['elements'] = StaticDB::getAllElements();
$customConfig['betOptions'] = StaticDB::getAllOptions();
$customConfig['secretToken'] = md5('superlabtop');


$customConfig['limitDate'] = "6-2-2016";
$customConfig['todayDate'] = date("d-m-Y");

$customConfig['limitHour'] = 22;
$customConfig['todayHour'] = date("H");

//si está a true, no se puede votar
$customConfig['votacionesOFF'] = true;
$customConfig['galaEND'] = true;


$customConfig['text03hits'] = 'Nunca te harás rico en un juego de azar, te gusta el cine pero te falta tino para saber quién cuenta con el favor de los académicos. No pasa nada, tienes otras virtudes.';
$customConfig['text46hits'] = 'No sé si por suerte o por conocimientos, pero el caso es que te has lucido. Tus predicciones se han cumplido por encima del 50%, no está nada mal...';
$customConfig['text79hits'] = 'De 7 a 9: El año que viene deberías entregar tú un Goya, qué ojo para saber quién será bendecido por los académicos. ¡Enhorabuena!';
$customConfig['textWinner'] = 'Eres uno de los 15 ganadores de la porra de Los Goya. Estate atento a tu email porque en breve nos pondremos en contacto contigo. Enhorabuena ';


/*********** ENRUTAMIENTO y CONTROLLERS*************/

$app->get('/', function()  use($app, $hybridauth, $twig){

	global $customConfig;
	$provider = isUserLogged();

	$customConfig['meta'] = StaticDB::findMetaByUrl('home');

 	//Si el usuario ya estaba logueado
	if($provider){	
		$user_profile = getUSerProfile($provider);
		$customConfig['resourceURI'] = $app->request->getResourceUri();
		$customConfig['user_profile'] = $user_profile;
		$customConfig['provider'] = $_SESSION['provider'];

		$currentUser = StaticDB::findUserByProviderId($user_profile->identifier);
		$customConfig['bodyclass'] = 'vota';
		$customConfig['currentUser'] = $currentUser;
		
		$customConfig['userBet'] = StaticDB::findUserBet($user_profile->identifier);

		if( $customConfig['userBet'] ){ //si ya hay apuesta relizada, la mostramos

			$customConfig['elementsToShow'] = array();

			//ordenamos el array por id de apuesta
			foreach ($customConfig['userBet'] as $key => $row) {
			    $aux[$key] = $row['idBet'];
			}

			array_multisort($aux, SORT_ASC, $customConfig['userBet']);

			//recogemos los elementos a mostrar de las apuestas realizadas por el usuario
			foreach ($customConfig['userBet'] as $key => $row) {
				array_push($customConfig['elementsToShow'] , StaticDB::findElementById($row['idElement']) );			    
			}

			$customConfig['bodyclass'] = 'indexStart miApuesta vota';

			$app->redirect($customConfig['baseURL'].'/votacion/'.$user_profile->identifier.'/');

		
		}else{ //si aún no hay apuesta	que vaya a realizarla

			if($customConfig['votacionesOFF']){
				$app->redirect($customConfig['baseURL'].'/ranking/');
			}else{
				$app->redirect($customConfig['baseURL'].'/mejor-pelicula/');
			}
			
		}

	//si el usuario aún no se ha logueado
	} else { 

		//chekeamos, si viene de premios no mostramos el loading no el video.
		if(isset($_SERVER['HTTP_REFERER'])){
			$pos = strpos($_SERVER['HTTP_REFERER'], '/porra/premios');
		}			

		if( isset($pos) ) { //se salta el loading y el video
			$customConfig['bodyclass'] = 'indexStart noLoading vota';

		}else{ //te muestra el loading y el video
			$customConfig['bodyclass'] = 'indexStart';
		}

		if($customConfig['votacionesOFF']){
			$app->redirect($customConfig['baseURL'].'/ranking/');
		}else{
			echo $twig->render('index.html', $customConfig);
		}		

	}
});

$app->post('/api/:action/', function($action) use($app, $twig, $hybridauth){
	global $customConfig;

	
	if($action == 'showOptions'){
		$customConfig['bet'] = StaticDB::findBetOptionsByName($app->request->post("categoria"));
		echo $twig->render('partials/opciones.html', $customConfig);

	}elseif ($action == 'saveBet') {
		$betToSave = $app->request->post("userBets");
		
		$provider = isUserLogged();
		$user_profile = getUSerProfile($provider);


		foreach ($betToSave as $key => $value) {
			$idElement = $value;
			$idUser = $user_profile->identifier; //provaiderId en mobgo
			$bet = StaticDB::findBetOptionsByUrl($key);
			$idBet = $bet['id'];

 			StaticDB::doBet( $idBet, $idElement, $idUser );		

		}

		echo  $user_profile->identifier;

	}else if($action == 'getTwitterText'){

		if($app->request->post("actualUrl") ==  'porra'){
			$socialText = StaticDB::findMetaByUrl('home');
		}else{
			$socialText = StaticDB::findMetaByUrl($app->request->post("actualUrl"));
		}
		


		echo $socialText[0]['metaSocialText'];
	
	}else if($action == 'checkUser'){
		$provider = isUserLogged();

		if($provider){
			echo 'yes';
		} else{
			echo 'no';
		}
	}
});

$app->get('/login/:provider/', function($name) use($app, $hybridauth, $twig){
    global $customConfig;
    //$isNewUser = false;
    
	try {
		if($name=="Facebook"){
			$provider = $hybridauth->authenticate( $name, array( "hauth_return_to" => $customConfig['baseURL'] ) );	
		} else {
			$provider = $hybridauth->authenticate( $name );	
		}

		$is_user_logged_in = $provider->isUserConnected();
	} catch (Exception $e) {
		print_r($e);
	}
	
	if( $is_user_logged_in){
		$_SESSION['provider'] = $name;
		$user_profile = getUSerProfile($provider);
        
        //Comprobamos si es un usuario nuevo (no está en BD) para saber si mostramos pantalla de solicitud de e-mail (sólo Twitter)
        $user = StaticDB::findUserByProviderId($user_profile->identifier);
        $isNewUser = (isset($user) ? false : true);
                
		//Buscamos al usuario en la BBDD y si no existe lo insertamos
		$_SESSION['DBUser'] = StaticDB::findUser($user_profile);
		// Obtenemos los datos de la sesion
		$hybridauth_session_data = $hybridauth->getSessionData();
		// Guardamos la sesion en la BBDD
		StaticDB::store_hybridauth_session( $user_profile, $hybridauth_session_data );
	}
        
	//Si el proveedor es Twitter, habrá que mostrar la página de solicitud de email
    if (( $name == "Twitter" ) && ($isNewUser)) {
        //$app->redirect($customConfig['baseURL'].'/email/');
       // echo $twig->render('email.html',$customConfig);
    	$app->redirect($customConfig['baseURL'].'/');
    } else {
        $app->redirect($customConfig['baseURL'].'/');
    }
});

// endpoint from hybridAuth/config.php
$app->get('/endpoint/', function () use($app, $twig, $hybridauth) {
	global $customConfig;
	try {
		require_once( "../../commons/libs/hybridauth-2.3.0/Hybrid/Auth.php" );
		require_once( "../../commons/libs/hybridauth-2.3.0/Hybrid/Endpoint.php" ); 
		Hybrid_Endpoint::process();
	} catch (Exception $e) {
		$app->redirect($customConfig['baseURL']);
	}
});

$app->get('/do-ranking/:token/', function ($token) use($app, $twig, $hybridauth){
	global $customConfig;


	if($token == $customConfig['secretToken']){

		/************ PARA LANZAR EL RANKING *************/
		$allBetsChecked = array();
		//Vaciamos la colección antes dew volver a generar el ranking
		$col = StaticDB::getDB()->ranking;
		$col->remove();
		
		$userBets  = StaticDB::findAllUserBets();
		
		//en el caso de que si tengamos apuesta de ese usuario
		if($userBets){

			$hitsUser = 0;
			foreach ($userBets as $key => $value) {

				$idBet = $value['idBet'];
				$betOptions =  StaticDB::findBetOptionsById($idBet);
				
				$providerId = $value['idUser'];
				$betDate = $value['created_at'];
				$idUserResult =  $value['idElement'];	
				$idResult = $betOptions[0]['result'];

				//en caso de que haya coincidencias vamos sumando los aciertos que ha tenido el usuario
				if($idUserResult == $idResult){
					$hitsUser ++;
				}

				//$numBets = StaticDB::getNumBetsByIdUser($providerId);
				if ($idBet == 9) {
					$userChecked = array(
						"idUser" => $providerId,
						"hits" => $hitsUser,
						"betDay" => $betDate
					   );
					array_push($allBetsChecked, $userChecked);

					$hitsUser = 0;
				}
			}
		}	

		//Ordenamos el array por hits y luego por fecha,  lo guardamos en mongo
		foreach ($allBetsChecked as $key => $row)	{
		    $checked_hits[$key] = $row['hits'];
		    $checked_betDay[$key] = $row['betDay'];
		}
		array_multisort($checked_hits, SORT_DESC, $checked_betDay, SORT_ASC, $allBetsChecked);


		foreach ($allBetsChecked as $key => $value) {
			
			$position = $key+1;
			$result = StaticDB::saveRanking( $value['idUser'], $value['hits'], $value['betDay'], $position );

		}


		//PARA CREAR EL CSV
		$winners = StaticDB::getRanking30();
		$fp1 = fopen("data/ranking.csv", "w");
		fwrite($fp1,'');
		fclose($fp1);

		$fp = fopen("data/ranking.csv", "a+");
		fwrite($fp, 'POSICIÓN;DISPLAY NAME;PROVIDER;CONTACT EMAIL;EMAIL;NOTES'."\n"); 
		
		
		foreach ($winners as $key => $value) {
			$hasEmail = false;
			$stringToFile = '';
			$user = array();

			echo "POSICIÓN: ".$value['position'];
			$stringToFile .= $value['position'].";";

			$user = StaticDB::findUserByProviderId($value['idUser']);
			echo "<br>*******************<br>";

			echo "<strong>displayName</strong>: ".$user['displayName']."<br>";
			$stringToFile .= $user['displayName'].";";

			echo "<strong>provider</strong>: ".$user['provider']."<br>";
			$stringToFile .= $user['provider'].";";

			if( isset($user['contactEmail']) ){
				echo "<strong>contactEmail</strong>: ".$user['contactEmail']."<br>";
				$stringToFile .=  $user['contactEmail'].";";
				$hasEmail = true;
			}else{
				echo "<strong>contactEmail</strong>: -<br>";
				$stringToFile .= "-;";
			}



			if( isset($user['email']) ){				
				echo "<strong>email</strong>: ".$user['email']."<br>";
				$stringToFile .= $user['email'];
				$hasEmail = true;
			}else{					
				echo "<strong>email</strong>: -<br>";
				$stringToFile .= "-";
			}
			
			if($hasEmail == true){
				$stringToFile .= ";-";
			}else{
				$stringToFile .= ";NO HAY EMAIL DE CONTACTO";
			}

			$stringToFile .= "\n";
			echo "<br><br>";
			echo $stringToFile;
			echo "<br><br>";
			fwrite($fp, $stringToFile); 
			
			
		}

		fclose($fp);

	}else{

		 $app->redirect($customConfig['baseURL'].'/');
	}
});

//user email form
$app->get('/email/', function() use($app, $hybridauth, $twig){
    global $customConfig;

	$provider = isUserLogged();
	$customConfig['meta'] = StaticDB::findMetaByUrl('votacion');


	if($provider){ //Si el usuario ya estaba logueado
		$user_profile = getUSerProfile($provider);
		
		$customConfig['resourceURI'] = $app->request->getResourceUri();
		$customConfig['user_profile'] = $user_profile;
		$customConfig['provider'] = $_SESSION['provider'];

		$currentUser = StaticDB::findUserByProviderId($user_profile->identifier);
		$customConfig['currentUser'] = $currentUser;		
	}

    $customConfig['error'] = $_SESSION['slim.flash'];
    
    //si está dentro de fecha
    //checkDateLimit devuelve false en caso de que ya no se pueda votar

    //ahora controlamos  por la variable $customConfig['votacionesOFF'], si vale true, ya no se puede votar
    if($customConfig['galaEND']){    	
    	$app->redirect($customConfig['baseURL'].'/ranking/');
    }else{
    	echo $twig->render('email.html',$customConfig);
    }
    
});

//Save user email
$app->post('/doSaveEmail/', function() use($app, $hybridauth, $twig){
    global $customConfig;
    $message = "";
        
	$req = $app->request();
    $params = $req->params();
    
    $email = $params["email"];
    $emailRepeat = $params["emailRepeat"];
    
    if (($email == "") || ($emailRepeat == "")) {
        $message = "Debes rellenar ambos campos.";
    } elseif ($email !== $emailRepeat) {
        $message = "Los e-mail introducidos no coinciden.";
    } elseif ((!filter_var($email, FILTER_VALIDATE_EMAIL)) || (!filter_var($emailRepeat, FILTER_VALIDATE_EMAIL))) {
        $message = "El formato de email introducido no es correcto.";
    }
    
    if ($message !== "") {
        $app->flash('error', $message);
        $app->redirect($customConfig['baseURL'].'/email/');
    }
        
	if (isset($_SESSION['provider'])){
        $provider = $hybridauth->getAdapter( $_SESSION['provider'] );
        $user_profile = getUSerProfile($provider);
        
        $result = StaticDB::saveEmail($user_profile->identifier, $email);
	}
	
	$app->redirect($customConfig['baseURL'].'/');

});

$app->get('/votacion-general/', function() use($app, $hybridauth, $twig){

	global $customConfig;
	$provider = isUserLogged();
	$customConfig['meta'] = StaticDB::findMetaByUrl('votacion-general');


	if($provider){ //Si el usuario ya estaba logueado
		$user_profile = getUSerProfile($provider);
		
		$customConfig['resourceURI'] = $app->request->getResourceUri();
		$customConfig['user_profile'] = $user_profile;
		$customConfig['provider'] = $_SESSION['provider'];

		$currentUser = StaticDB::findUserByProviderId($user_profile->identifier);
		$customConfig['currentUser'] = $currentUser;
		$customConfig['userID'] = $user_profile->identifier;
		
	}

	$resultsToShow = array();

	//el total de número de apuestas realizadas (1 por user)
	$numBets = StaticDB::getNumBets();
	//veces que se ha votado cada elemento
	$timesVotedElements = StaticDB::numTimesVotedElements();

	foreach ($customConfig['betOptions'] as $key => $bet) {

		//recorremos los elementos de cada apuesta
		$elementsBet = $bet['elements'];
		$dataBet =  StaticDB::findBetOptionsByName($bet['nombre']);
		$urlBet = $dataBet['url'];
		$nameBet = $dataBet['nombre'];

		$arrayToPush[$urlBet] = array(); //iremos almacenando temporalmente los datos de las apuestas realizadas1
		$resultsToShow[$urlBet] = array(); //aquí se almacena lo que mostraremos finalmenete
		
		foreach ($elementsBet as $k => $element) {		
			$dataElement = StaticDB::findElementById((string)$element);

			$imgElement = $dataElement[0]['foto'];
			$nameElement = $dataElement[0]['nombre'];
			$pelicula = $dataElement[0]['pelicula'];
			$type = $dataElement[0]['type'];

			$vecesVotado = timesVoted($element, $timesVotedElements['retval']);	
			$porcent = ($vecesVotado * 100) / $numBets;
			if($porcent == 100){
				$porcent == 100;
			}else{
				$porcent = number_format($porcent, 1, '.', '');
			}
			

			$ratingsElement = array(
										"idElement" => $element,
										"urlBet" => $urlBet,
										"nameBet" => $nameBet,
										"nameElement" => $nameElement,
										"pelicula" => $pelicula,
										"imgElement" => $imgElement,
										"type" => $type,
										"timesVotedElement" => $vecesVotado,
										"porcent" => $porcent
									);
			array_push($arrayToPush[$urlBet], $ratingsElement) ;	
		}


		//ordenamos el array por porcentaje
		uasort($arrayToPush[$urlBet], 'ordename');
		//invertimos el array para que la primera posición sea la que queremos mostrar, la que más votos tiene
		$arrayToPush[$urlBet] = array_reverse($arrayToPush[$urlBet]);

		array_push($resultsToShow[$urlBet], $arrayToPush[$urlBet]) ;	
	}


	//en $resultsToShow tenemos un array por categoría, cada uno de ellos con el id de sus elementos y las veces que a sido votada
	$customConfig['dataToShow'] = $resultsToShow;

	//recogemos datitos y sacamos los porcentajes
	$customConfig['bodyclass'] = 'indexStart apuestaGlobal miApuesta vota';
	echo $twig->render('partials/globalBets.html',$customConfig);

});

$app->get('/votacion/:idUser/', function($idUser) use($app, $hybridauth, $twig){
	//$idUser = 'es el providerId del usuario que realizó la apuesta'

	global $customConfig;
	//$idUser = (double)$idUser;
	$provider = isUserLogged();
	$customConfig['meta'] = StaticDB::findMetaByUrl('votacion');


	if($provider){ //Si el usuario ya estaba logueado
		$user_profile = getUSerProfile($provider);
		
		$customConfig['resourceURI'] = $app->request->getResourceUri();
		$customConfig['user_profile'] = $user_profile;
		$customConfig['provider'] = $_SESSION['provider'];

		$currentUser = StaticDB::findUserByProviderId($user_profile->identifier);
		$customConfig['currentUser'] = $currentUser;		
	}


	//porque el id de Google se guarda como String y el de Twitter como entero, parseamos porque lo traemos como String
	$customConfig['userBet'] = StaticDB::findUserBet( $idUser );
	//si no lo ha encontrado como string lo parseamos
	if(count($customConfig['userBet']) <= 1 ){		
		$customConfig['userBet'] = StaticDB::findUserBet(intval($idUser));
	}
	

	if( $customConfig['userBet'] ){
		 $customConfig['elementsToShow'] = array();
		//ordenamos el array por id de apuesta
		foreach ($customConfig['userBet'] as $key => $row) {
		    $aux[$key] = $row['idBet'];
		}

		array_multisort($aux, SORT_ASC, $customConfig['userBet']);

		//recogemos los elementos a mostrar de las apuestas realizadas por el usuario
		foreach ($customConfig['userBet'] as $key => $row) {

			$idBet = $row['idBet'];
			$resultForBet = StaticDB::findResultForBetById($idBet);
			$resultForBet = $resultForBet[0]['result'];

			$myReslut = $row['idElement'];

			$arryToShow = StaticDB::findElementById($row['idElement']);
			//si ha habido acierto

			if(intval($myReslut) == intval($resultForBet) ){
				array_push($arryToShow ,  array("hit" => 'yes') );			    
			}else{
				array_push($arryToShow ,  array("hit" => 'no') );	
			}
						
			array_push($customConfig['elementsToShow'] , $arryToShow);
		}

		$countHist = 0;
		foreach ($customConfig['elementsToShow'] as $khits => $vhits) {
			if( $vhits[1]['hit'] == 'yes' ){
				$countHist++;
			}
		}

		//según los aciertos que ha tenido, le damos un texto u otro
		if( $countHist >=0 && $countHist <=3 ){
			$customConfig['textHits'] = $customConfig['text03hits'];
		}elseif ( $countHist >=4 && $countHist <=6 ) {
			$customConfig['textHits'] = $customConfig['text46hits'];
		}elseif ( $countHist >=7 && $countHist <=9 ) {
			$customConfig['textHits'] = $customConfig['text79hits'];
		}

		$userPosition = StaticDB::getPositionUserRanking(intval($idUser));
		if(!isset($userPosition)){			
			$userPosition = StaticDB::getPositionUserRanking($idUser);
		}
		if( $userPosition >= 1 && $userPosition <= 15 ){
			$customConfig['textWinner'] = $customConfig['textWinner'];
		}else{
			$customConfig['textWinner'] = '';
		}


		$customConfig['bodyclass'] = 'indexStart miApuesta vota';

		//mostramos la apuesta del usuario
		if(isset( $user_profile )){
			if( $user_profile->identifier == $idUser ){
				echo $twig->render('partials/userBets.html',$customConfig);
			}else{			
				$customConfig['otherUser'] =  StaticDB::findUserByProviderId($idUser);
				if(count($customConfig['otherUser']) <= 1 ){		
					$customConfig['otherUser'] = StaticDB::findUserByProviderId(intval($idUser));
				}
				echo $twig->render('partials/otherUserBets.html',$customConfig);
		}
			//mostramos la porra que le han compartido
		}else{			
			$customConfig['otherUser'] =  StaticDB::findUserByProviderId($idUser);
			if(count($customConfig['otherUser']) <= 1 ){		
				$customConfig['otherUser'] = StaticDB::findUserByProviderId(intval($idUser));
			}

			echo $twig->render('partials/otherUserBets.html',$customConfig);
		}
		
		

	}else{
		$app->redirect($customConfig['baseURL'].'/');

	}

});


$app->get('/ranking/', function() use($app, $hybridauth, $twig){
	global $customConfig;

	$customConfig['bodyclass'] = 'indexStart apuestaGlobal miApuesta vota ranking';
	$winners = StaticDB::getRanking();
	$customConfig['winners'] = array();

	foreach ($winners as $key => $value) {
		$user = array();

		if(gettype($value['idUser']) == 'integer'){
			$user = StaticDB::findUserByProviderId($value['idUser']);
		}elseif(gettype($value['idUser']) == 'string') {
			$user = StaticDB::findUserByProviderId($value['idUser']);			
		}

		array_push($customConfig['winners'], $user);
	}

	echo $twig->render('partials/ranking.html',$customConfig);

});   

// Logout
$app->get('/logout/', function() use($app, $hybridauth){
   global $customConfig;



	if(isset($_SESSION['provider'])){
		$provider = $hybridauth->getAdapter( $_SESSION['provider'] );
		$provider->logout();
		unset($_SESSION['provider']);
	}

	$app->redirect($customConfig['baseURL'].'/');

});


$app->get('/premios/', function() use($app, $hybridauth, $twig){
	global $customConfig;
	$customConfig['bodyclass'] = 'premios';

	$customConfig['meta'] = StaticDB::findMetaByUrl('premios');
	echo $twig->render('condiciones.html', $customConfig);

});


$app->get('/json/', function() use($app, $hybridauth, $twig){
	global $customConfig;

	$totalVotes = StaticDB::getNumBets();

	$allBets = new stdClass;
	foreach ($customConfig['betOptions'] as $key => $value) {

		$globalid = $key+1;
		$opciones = count($value['elements']);
		$enunciado = $value['nombre'];

		$elements = new stdClass;
		foreach ($value['elements'] as $k => $v) {

			$id = $k+1;

			$element = StaticDB::findElementById(strval($v));
			
			$pelicula = $element[0]['pelicula'];
			$titulo = $element[0]['nombre'];
			$alcance = StaticDB::countElementVotesById(strval($v));
			$alcancePorciento = intval(( $alcance *  100) /  $totalVotes);

			$dataElement = new stdClass;
			$dataElement->texto = $titulo;
			$dataElement->hashtag = $pelicula;
			$dataElement->tweets = $alcance;
			$dataElement->tweets_porciento = $alcancePorciento;

			$elements->$id = $dataElement;
		}

		$singleBet = new stdClass;
		$singleBet->id = $globalid;
		$singleBet->opciones = $opciones;
		$singleBet->enunciado = $enunciado;
		$singleBet->opcion = $elements;

		$result =  file_put_contents('data/results'.$globalid.'.json', json_encode($singleBet));

		$allBets->$key = $singleBet;
	}

	$result =  file_put_contents('data/results.json', json_encode($allBets));

});


$app->get('/:opcion/', function($opcion) use($app, $hybridauth, $twig){

	global $customConfig;

	//si está dentro de fecha podremos votar, si no, te lleva al ranking
	//if(checkDateLimit()){    	
	if(!$customConfig['votacionesOFF']){    	

		$customConfig['bodyclass'] = 'vota';

		$customConfig['meta'] = StaticDB::findMetaByUrl($opcion);

		$provider = isUserLogged();

		if($provider){
			$user_profile = getUSerProfile($provider);

			$customConfig['resourceURI'] = $app->request->getResourceUri();
			$customConfig['user_profile'] = $user_profile;
			$customConfig['provider'] = $_SESSION['provider'];

			$currentUser = StaticDB::findUserByProviderId($user_profile->identifier);
			$customConfig['currentUser'] = $currentUser;

		} 

		foreach ($customConfig['betOptions'] as $key => $value) {
			if($value['url'] == $opcion){
				$bet = array();
				$customConfig['bet'] = $value;
			}
		}


		if(isset($customConfig['bet'])){
			if($provider){
				if(StaticDB::findUserBet($user_profile->identifier)){//si ya hay una apuesta guardada para este user
					$app->redirect($customConfig['baseURL'].'/votacion/'.$user_profile->identifier.'/');
				}else{
					echo $twig->render('partials/menu.html', $customConfig);
				}

			}else{
				echo $twig->render('partials/menu.html', $customConfig);
			}	
		}else{
			$app->redirect($customConfig['baseURL'].'/ranking/');
		}

    }else{
    	$app->redirect($customConfig['baseURL'].'/ranking/');
    }
	
});


$app->run();



/******************* FUNCIONES *******************/

//devuelve true o false en función de si está dentro o fuera del dia/hora de votación
function checkDateLimit(){

	global $customConfig;

	if( $customConfig['limitDate'] > $customConfig['todayDate'] ){

		//echo "dentro de fecha<br/>";	
		//return true;

		if( $customConfig['limitHour'] > $customConfig['todayHour'] ){
			//echo "dentro de hora<br/>";	
			return true;
		}else{
			//echo "FUERA de hora<br/>";	
			return false;
		}

	}else{
		//echo "FUERA de fecha<br/>";	
		return false;
	}

}




//devuelve el numeo de veces que se ha votado un elemento
function timesVoted($idElement, $array) {
   foreach ($array as $key => $val) {
       if ($val['idElement'] == $idElement) {
           return $val['count'];
       }
   }
   return null;
}

/***
* Check User login
*/
function isUserLogged(){
	global $hybridauth;
	
	if(!isset($_SESSION['provider'])){
		return false;
	}
	try {
		$provider = $hybridauth->getAdapter($_SESSION['provider']);
		$is_user_logged_in = $provider->isUserConnected();

	} catch (Exception $e) {
		echo $e;	
	}
	
	if(!$is_user_logged_in){
		return false;
	}
	
	return $provider;
}


function getUSerProfile($provider){
	
	global $customConfig;
	global $app, $hybridauth;
	$sesionRestored = false;

	try {
		return $provider->getUserProfile();
	} catch( Exception $e ) {  
		// to know more please refer to Exceptions handling section on the userguide
	  	switch( $e->getCode() ){ 
	  	  case 0 : echo "Unspecified error."; break;
	  	  case 1 : echo "Hybriauth configuration error."; break;
	  	  case 2 : echo "Provider not properly configured."; break;
	  	  case 3 : echo "Unknown or disabled provider."; break;
	  	  case 4 : echo "Missing provider application credentials."; break;
	  	  case 5 : echo "Authentification failed. " 
	  	              . "The user has canceled the authentication or the provider refused the connection."; break;
	  	  //  Google ---> Comprobar si estan habilitadas las APIs de Google+ y Contacts
	  	  // este error se suele producir por no estar activadas
	  	  case 6 : echo "User profile request failed. Most likely the user is not connected to the provider and he should authenticate again."; 
	  	            try {
		  	            // get the stored hybridauth data from your storage system
						$hybridauth_session_data = StaticDB::get_stored_hybridauth_session( $_SESSION['DBUser'][0]['providerId'] );
						// then call Hybrid_Auth::restoreSessionData() to get stored data
						$hybridauth->restoreSessionData( $hybridauth_session_data );
						// call back an instance of adapter
						$provider = $hybridauth->getAdapter( $_SESSION['provider'] );
						try {
							$provider->getUserProfile();
						} catch (Exception $e) {
							$app->redirect($customConfig['baseURL'].'/logout/');
						}
						$sesionRestored = true;
	  	            } catch (Exception $e) {
	  	            	//echo '----------<br/>'.$e;
	  	            	$app->redirect($customConfig['baseURL'].'/');
	  	            }
	  	           	break;
	  	  case 7 : echo "User not connected to the provider."; break;
	  	  case 8 : echo "Provider does not support this feature."; break;
	  	} 
	  	//var_dump($provider->getUserProfile());
	  	// well, basically your should not display this to the end user, just give him a hint and move on.
	  	echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();

	  	if(isset($sesionRestored)){
			return $provider->getUserProfile();
	  	} else {
			$app->redirect($customConfig['baseURL'].'/logout/');
	  	}
	}
}



function ordename ($a, $b) {
    return $a['timesVotedElement'] - $b['timesVotedElement'];
}

?>