<?php
require_once '../config/constants.php';
require_once "../config/http.config.php";
require_once "../config/global.config.php";
require_once ROOT_PATH . "/core/Core.php";
require_once ROOT_PATH . "/core/Exceptions.php";

spl_autoload_register('__AutoLoadClass');

$mod = empty( $_GET['mod'] ) ? 'index' : $_GET['mod'];
$act = empty( $_GET['act'] ) ? 'run' : $_GET['act'];

$mod_camelize = str_camelize($mod);

if($mod_camelize == 'Command')
	die;	//不允许使用网页方式访问 CommandController

$controller = $mod . 'Controller';
$conFile = CONTROLLER_PATH . "/{$controller}.php";
if(!file_exists($conFile)) {
	$controller = $mod_camelize . 'Controller';
	$conFile = CONTROLLER_PATH . "/{$controller}.php";
}
if( file_exists( $conFile ) )
{
	//基类方法和命令行专用方法不可调用
	if(is_callable(array('Controller', $act)) || substr($act, 7) == 'command'){
		if(IS_DEBUG)
			die("{$act} method is not callable!");
		else {
			header("HTTP/1.1 404 Not Found");
			exit;
		}
	}
	
	include $conFile;
}
else
{
	if(IS_DEBUG)
		die("{$mod} module doesn't exist!");
	else {
		header("HTTP/1.1 404 Not Found");
		exit;
	}
}

if(class_exists($controller, false)) {
	$ControlleObject = new $controller($mod, $act);
	$GLOBALS['ControlleObject'] = $ControlleObject;

	//删除内部参数，保证支付回调参数的原始状态
	unset( $_POST['mod'] );
	unset( $_POST['act'] );
	unset( $_GET['mod'] );
	unset( $_GET['act'] );

	if(method_exists($ControlleObject, $act)){
		if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
			// 如果是OPTIONS请求，进行预处理返回CORS信息即可
			header('Access-Control-Allow-Credentials: true');
			header('Access-Control-Allow-Methods: GET, POST');
			header('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
			header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
			exit;
		}
		try {
			$result = $ControlleObject->$act();
			$ControlleObject->Return();
		} catch (ApiException $e) {
			$ControlleObject->ApiError($e->getMessage(), $e->getCode());
		}
	} else {
		if(IS_DEBUG)
			die("No {$act} method in {$mod} module!");
		else {
			header("HTTP/1.1 404 Not Found");
			header("Cache-Control: max-age=3600"); 
			exit;
		}
	}
}