<?php
  //ini_set('display_errors', 1);
  //ini_set('display_startup_errors', 1);
  //error_reporting(E_ALL);
  
  define("__ROOT__", $_SERVER["DOCUMENT_ROOT"]);
  const API_PREFIX = "api";
  
  if(!session_id()) session_start();
  
  require '../vendor/autoload.php';
  
  require_once '../../main/app/config/status.php';
  require_once '../../main/app/config/connect.php';
  require_once '../../main/app/config/app.php';
  require_once '../core/helper.php';

  use Api\Controllers\BirFaturaController;
  use Api\Handlers\RouteExceptionHandler;
  use Api\Middlewares\BirFaturaMiddleware;
  use Api\Middlewares\InstallationMiddleware;
  use Api\Middlewares\TokenAuthMiddleware;
  use Pecee\SimpleRouter\SimpleRouter;
  
  global
  $settings,
  $readSettings,
  $modules,
  $readModules,
  $serverIP,
  $readAdmin;
  
  // Initialize
  $settings = $db->query("SELECT * FROM Settings");
  foreach ($settings as $setting) {
    $readSettings[$setting["name"]] = $setting["value"];
  }
  
  $modules = $db->query("SELECT * FROM Modules");
  $readModules = $modules->fetchAll();
  
  $serverIP         = $readSettings["serverIP"];
  $serverVersion    = $readSettings["serverVersion"];
  $serverName       = $readSettings["serverName"];
  $siteTitle        = $serverName.' - '.$readSettings["siteSlogan"];
  
  $websiteURL = settings("websiteURL");
  
  if ($readSettings["timezone"] != null) {
    date_default_timezone_set($readSettings["timezone"]);
  }
  
  // Routes
  SimpleRouter::group(['exceptionHandler' => RouteExceptionHandler::class], function () {
    SimpleRouter::group([
      'prefix' => '/' . API_PREFIX,
      'middleware' => InstallationMiddleware::class
    ], function () {
      SimpleRouter::group(['middleware' => TokenAuthMiddleware::class], function () {
        require_once '../app/config/routes.php';
      });

      /**
       * BirFatura routes
       */
      if (!moduleIsDisabled('birfatura') && isset($_SERVER["HTTP_TOKEN"])) {
        SimpleRouter::group(['middleware' => BirFaturaMiddleware::class], function () {
          SimpleRouter::post('/orderStatus', [BirFaturaController::class, 'orderStatus'])->name('birfatura.orderStatus');
          SimpleRouter::post('/paymentMethods', [BirFaturaController::class, 'paymentMethods'])->name('birfatura.paymentMethods');
          SimpleRouter::post('/orders', [BirFaturaController::class, 'orders'])->name('birfatura.orders');
        });
      }
    });
  });
  
  SimpleRouter::setDefaultNamespace('\Api\Controllers');
  
  SimpleRouter::start();
