<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// public/index.php
// front controller / router
session_start();

require_once __DIR__ . '/../app/bootstrap.php'; // autoload + helper config()

use App\Core\Database;
use App\Core\Auth;
// načíst konfiguraci DB a vytvořit instanci Database
$dbConfig = config()['db'];
$db = new Database($dbConfig);
$GLOBALS['db'] = $db; // Uložení do GLOBALS pro přístup v layout.php

// Základní URL cesta (funguje i v podsložkách, např. /~user/DMP/teamhub/public)
define('BASE_URL', rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'));

// router podle GET parametrů

$controller = $_GET['controller'] ?? null;
$action     = $_GET['action'] ?? 'index';

// pokud není controller zadaný
if ($controller === null) {
    if (Auth::check()) {
        header('Location: ' . BASE_URL . '/dashboard/index');
    } else {
        header('Location: ' . BASE_URL . '/home/index');
    }
    exit;
}

// vytvoření controlleru (mapování)
switch (strtolower($controller)) {
    case 'dashboard':
        $c = new App\Controllers\DashboardController($db);
        break;

    case 'kalendar':
        $c = new App\Controllers\KalendarController($db);
        break;

    case 'nastenka':
        $c = new App\Controllers\NastenkaController($db);
        break;

    case 'user':
        $c = new App\Controllers\UserController($db);
        break;

    case 'team':
        $c = new App\Controllers\TeamController($db);
        break;

    case 'chat':
        $c = new App\Controllers\ChatController($db);
        break;

    case 'dochazka':
        $c = new App\Controllers\DochazkaController($db);
        break;

    case 'anketa':
        $c = new App\Controllers\AnketaController($db);
        break;

    case 'statistics':
        $c = new App\Controllers\StatisticsController($db);
        break;

    case 'statistictype':
        $c = new App\Controllers\StatisticTypeController($db);
        break;

    case 'home':
        $c = new App\Controllers\HomeController($db);
        break;

    case 'auth':
    default:
        $c = new App\Controllers\AuthController($db);
}


// ověření existující metody
if (!method_exists($c, $action)) {
    http_response_code(404);
    (new App\Core\View())->render('error', ['message' => 'Akce nenalezena (404)']);
    exit;
}

// zavolat akci

// Pokud je chat controller, nevolat layout, pouze akci a exit
if (strtolower($controller) === 'chat') {
    $c->{$action}();
    exit;
}

$c->{$action}();