<?php

/* Requests Handler */

//Start buffering
ob_start();

//Run from /dist/
$oLoader = require __DIR__.'/../vendor/autoload.php';

use Franzz\Objects\ToolBox;
use Franzz\Objects\Main;
use Franzz\Spot\Spot;
use Franzz\Spot\User;

ToolBox::fixGlobalVars($argv ?? array());

//Available variables
$sAction	= $_REQUEST['a']			?? '';
$sTimezone	= $_REQUEST['t']			?? '';
$sName		= $_GET['name']				?? '';
$sContent	= $_GET['content']			?? '';
$iProjectId	= $_REQUEST['id_project']	?? 0 ;
$sField		= $_REQUEST['field']		?? '';
$oValue		= $_REQUEST['value']		?? '';
$iId		= $_REQUEST['id']			?? 0 ;
$sType		= $_REQUEST['type']			?? '';
$sEmail		= $_REQUEST['email']		?? '';
$sLat		= $_REQUEST['latitude']		?? '';
$sLng		= $_REQUEST['longitude']	?? '';
$iTimestamp = $_REQUEST['timestamp']	?? 0;

//Initiate class
$oSpot = new Spot(__FILE__, $sTimezone);
$oSpot->setProjectId($iProjectId);

$sResult = '';
if($sAction!='')
{
	switch($sAction)
	{
		case 'markers':
			$sResult = $oSpot->getMarkers();
			break;
		case 'geojson':
			$sResult = $oSpot->getProjectGeoJson();
			break;
		case 'next_feed':
			$sResult = $oSpot->getNextFeed($iId);
			break;
		case 'new_feed':
			$sResult = $oSpot->getNewFeed($iId);
			break;
		case 'add_post':
			$sResult = $oSpot->addPost($sName, $sContent);
			break;
		case 'subscribe':
			$sResult = $oSpot->subscribe($sEmail, $sName);
			break;
		case 'unsubscribe':
			$sResult = $oSpot->unsubscribe();
			break;
		case 'unsubscribe_email':
			$sResult = $oSpot->unsubscribeFromEmail($iId);
			break;
		case 'update_project':
			$sResult = $oSpot->updateProject();
			break;
		default:
			if($oSpot->checkUserClearance(User::CLEARANCE_ADMIN))
			{
				switch($sAction)
				{
					case 'upload':
						$sResult = $oSpot->upload();
						break;
					case 'add_comment':
						$sResult = $oSpot->addComment($iId, $sContent);
						break;
					case 'add_position':
						$sResult = $oSpot->addPosition($sLat, $sLng, $iTimestamp);
						break;
					case 'admin_get':
						$sResult = $oSpot->getAdminSettings();
						break;
					case 'admin_set':
						$sResult = $oSpot->setAdminSettings($sType, $iId, $sField, $oValue);
						break;
					case 'admin_create':
						$sResult = $oSpot->createAdminSettings($sType);
						break;
					case 'admin_delete':
						$sResult = $oSpot->deleteAdminSettings($sType, $iId);
						break;
					case 'generate_cron':
						$sResult = $oSpot->genCronFile();
						break;
					case 'sql':
						$sResult = $oSpot->getDbBuildScript();
						break;
					case 'build_geojson':
						$sResult = $oSpot->buildGeoJSON($sName);
						break;
					default:
						$sResult = Main::getJsonResult(false, Main::NOT_FOUND);
				}
			}
			else $sResult = Main::getJsonResult(false, Main::NOT_FOUND);
	}
}
else $sResult = $oSpot->getAppMainPage();

$sDebug = ob_get_clean();
if(Settings::DEBUG && $sDebug!='') $oSpot->addUncaughtError($sDebug);

echo $sResult;
