<?php
/**
 * fahrschuldesk API - Entry Point
 */

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use App\Support\Database;
use App\Support\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteCollectorProxy;

// Load config
$config = require __DIR__ . '/../config/app.php';

// Set timezone
date_default_timezone_set($config['app']['timezone']);

// Create app
$app = AppFactory::create();

// Get container
$container = $app->getContainer();

// Database connection for SSH tunnel
$dsn = sprintf(
    'pgsql:host=%s;port=%d;dbname=%s',
    $config['db']['host'],
    $config['db']['port'],
    $config['db']['database']
);

try {
    $pdo = new PDO($dsn, $config['db']['username'], $config['db']['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    Database::setConnection($pdo);
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}

// CORS Middleware
$app->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler) use ($config) {
    $origin = $request->getHeaderLine('Origin');
    $allowed = $config['cors']['allowed_origins'];
    
    if (in_array('*', $allowed) || in_array($origin, $allowed)) {
        return $handler->handle($request)
            ->withHeader('Access-Control-Allow-Origin', $origin ?: '*')
            ->withHeader('Access-Control-Allow-Methods', implode(', ', $config['cors']['allowed_methods']))
            ->withHeader('Access-Control-Allow-Headers', implode(', ', $config['cors']['allowed_headers']))
            ->withHeader('Access-Control-Allow-Credentials', 'true');
    }
    
    return $handler->handle($request);
});

// Error middleware
$displayErrors = $config['app']['debug'];
$app->addErrorMiddleware($displayErrors, true, true);

// Import routes
require __DIR__ . '/../routes/api.php';

// Run
$app->run();