<?php

/*
 CATC Project
 https://git.lutran.fr/franzz/catc
 Copyright (C) 2015 François Lutran

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see http://www.gnu.org/licenses
 */

/* Requests Handler */

//Start buffering
ob_start();
require_once '../objects/class_management.php';
$oClassManagement = new ClassManagement('catc');
ToolBox::cleanPost($_POST);
ToolBox::cleanPost($_GET);
ToolBox::cleanPost($_REQUEST);
ToolBox::fixGlobalVars(isset($argv)?$argv:array());

//Available variables
$sToken = isset($_REQUEST['token'])?$_REQUEST['token']:'';
$sAction = isset($_REQUEST['a'])?$_REQUEST['a']:'';
$sPage = isset($_GET['p'])?$_GET['p']:'index';
$sNickName = isset($_REQUEST['nickname'])?$_REQUEST['nickname']:'';
$iApiKey = isset($_GET['api'])?$_GET['api']:'';
$sContent = isset($_POST['content'])?$_POST['content']:'';
$iId = isset($_REQUEST['id'])?$_REQUEST['id']:0;

//Initiate class
$oCATC = new CATC($oClassManagement, __FILE__);
$bLoggedIn = $oCATC->isLoggedIn();

$sResult = '';
if($sAction=='logmein') $sResult = $oCATC->logMeIn($sToken);
elseif($sAction!='' && $bLoggedIn)
{
	switch ($sAction)
	{
		default:
			$sResult = CATC::getJsonResult(false, CATC::NOT_FOUND);
	}
}
elseif($sAction!='' && !$bLoggedIn)
{
	if($oCATC->checkApiKey($iApiKey))
	{
		switch ($sAction)
		{
			case '':
				//$sResult = $oCATC->apifunction();
				break;
			default:
				$sResult = CATC::getJsonResult(false, CATC::NOT_FOUND);
		}
	}
	elseif($sAction=='register') $sResult = $oCATC->register($sToken, $sNickName);
	else $sResult = CATC::getJsonResult(false, CATC::UNAUTHORIZED);
}
else $sResult = $oCATC->getPage();

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

echo $sResult;