<?php
use DI\ContainerBuilder as Builder;
use DI\Bridge\Slim\Bridge;

include_once 'composer.php';

$builder = new Builder();

$folders = [
  implode(DIRECTORY_SEPARATOR, [
    dirname(__DIR__, 2),
    'setup',
    'env'
  ]),
  implode(DIRECTORY_SEPARATOR, [
    dirname(__DIR__, 2),
    'setup',
    'common'
  ]),
  implode(DIRECTORY_SEPARATOR, [
    __DIR__,
    'api'
  ])
];
$files = [
  'settings',
  'setups'
];

foreach ($files as $file) {
  foreach ($folders as $folder) {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $folder,
      $file . '.php'
    ]);
    if (!file_exists($filename)) {
      continue;
    }
    $builder->addDefinitions($filename);
  }
}

$container = $builder->build();
$app = Bridge::create($container);
include_once 'databases.php';

if ($container->has('base_url') and $container->get('base_path') !== null) {
  $app->setBasePath($container->get('base_url'));
}
$app->add(new ProVM\Money\Common\Middleware\Cors());
$app->addRoutingMiddleware();

foreach ($folders as $folder) {
  $filename = implode(DIRECTORY_SEPARATOR, [
    $folder,
    'middleware.php'
  ]);
  if (!file_exists($filename)) {
    continue;
  }
  include_once $filename;
}

include_once 'router.php';
$app->addErrorMiddleware(true, true, true);
