<?php

require_once __DIR__ . '/../Include/LoadConfigs.php';

use ChurchCRM\Slim\Middleware\CorsMiddleware;
use ChurchCRM\Slim\Middleware\VersionMiddleware;
use ChurchCRM\Slim\SlimUtils;
use Slim\Factory\AppFactory;


// Get base path by combining $sRootPath from Config.php with /external endpoint
// Examples: '' + '/external' = '/external' (root install)
//           '/churchcrm' + '/external' = '/churchcrm/external' (subdirectory install)
$basePath = SlimUtils::getBasePath('/external');

$app = AppFactory::create();
$app->setBasePath($basePath);

$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();

// Error middleware must be added AFTER routing (Slim 4 LIFO: last added = first executed)
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
SlimUtils::registerDefaultJsonErrorHandler($errorMiddleware);

$app->add(VersionMiddleware::class);
$app->add(new CorsMiddleware());

// routes
require __DIR__ . '/routes/register.php';
require __DIR__ . '/routes/verify.php';
require __DIR__ . '/routes/calendar.php';
require __DIR__ . '/routes/system.php';
require __DIR__ . '/routes/website.php';

// Run app
$app->run();
