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

include_once 'composer.php';

function buildApp($__environment): Slim\App {
    $builder = new Builder();
    if (isset($__environment)) {
        $builder->addDefinitions(['environment' => $__environment]);
    }
    $folders = [
        'settings',
        'setups'
    ];
    foreach ($folders as $f) {
        $folder = implode(DIRECTORY_SEPARATOR, [
            __DIR__,
            $f
        ]);
        if (!file_exists($folder)) {
            continue;
        }
        $files = new DirectoryIterator($folder);
        foreach ($files as $file) {
            if ($file->isDir() or $file->getExtension() != 'php') {
                continue;
            }
            $builder->addDefinitions($file->getRealPath());
        }
    }

    $container = $builder->build();
    $app = Bridge::create($container);
    if ($app->getContainer()->has('base_url') and $app->getContainer()->get('base_url') != '') {
        $app->setBasePath($app->getContainer()->get('base_url'));
    }
    $app->addRoutingMiddleware();

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

    $app->addErrorMiddleware(true, true, true);

    include_once 'database.php';

    include_once 'router.php';

    return $app;
}

return buildApp($__environment);
