<?php declare(strict_types=1);

//
// Copyright (c) 2016, Mike Pultz All rights reserved.
//

ob_start();

require '../prepend.php';
require 'config/settings.php';

//
// TODO: until we release the version 4.0 of the API, which doesn't include a version number in the
//       the output, and then we remove this.
//
$GLOBALS['version'] = '3.15';

//
// for no caching from the API
//
header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);

//
// adjust the include path to include our local lib directory
//
set_include_path($_SERVER['DOCUMENT_ROOT'] . ':' . get_include_path());

//
// build the page details
//
$request = new \capi_request($_SERVER['QUERY_STRING']);

//
// start up logging
//
openlog('api', LOG_ODELAY, $settings['syslog_api']);

//
// used for page messaging
//
$gnotification = new \cnotification();

//
// define the database object so we have a global instance
//
$gdb = new \cdb();

//
// register a new autoloader for our version specific controllers
//
spl_autoload_register(function($_class)
{
    global $request;

    if ( (strpos($_class, '_controller') !== false) || (strpos($_class, '_trait') !== false) )
    {
        $filename = 'controllers/' . str_replace('\\', '/', $_class) . '.php';

        if (file_exists($filename) == true)
        {
            require_once $filename;
        } else
        {
            throw new \cerror(E_ERROR, sprintf('main(): file \'%s\' does not exist.', $filename));
        }
    }

}, true, true);

try
{
    //
    // validate the version; if it's not a known version, then we send them to the 404 page- but we need to fix version for that to work.
    //
    if (in_array($request->m_version, $settings['api_versions']) == false)
    {
        $request->m_version = $settings['default_api_version'];

        throw new \cerror(E_ERROR, 'main(): invalid version number provided.');
    }

    //
    // create the object, and make the request
    //
    $c = new $request->m_path($request);
    if ($c->m_authenticated == true)
    {
        if (method_exists($c, $request->m_section) == false)
        {
            throw new \cerror(E_ERROR, sprintf('main(): invalid section \'%s\'.', $request->m_section));
        }

        $c->{$request->m_section}($request);
    }

} catch(\cerror $e)
{
    try
    {
        new \c404_controller($request)->view($request);

    } catch(\cerror $e)
    {
        exit();
    }
}
