<?php

declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../app-support.php';
require_once __DIR__ . '/../../app/Modules/Support/bootstrap.php';

if (!isset($_SESSION['support_csrf'])) {
    $_SESSION['support_csrf'] = bin2hex(random_bytes(24));
}

function support_h(string $value): string
{
    return app_h($value);
}

function support_dt(?string $value): string
{
    if ($value === null || trim($value) === '') {
        return '-';
    }

    $time = strtotime($value);

    return $time === false ? $value : date('d.m.Y H:i', $time);
}

function support_badge(string $label, string $tone = 'neutral'): string
{
    return '<span class="badge badge--' . support_h($tone) . '">' . support_h($label) . '</span>';
}

$auth = app_require_auth();
$flash = app_flash();
$pdo = null;
$dbError = null;
$supportTablesReady = false;
$tenantLicense = ['plan_name' => 'Free', 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();
$controller = new \App\Modules\Support\Controllers\SupportController(new \App\Modules\Support\Application\SupportService());
$pageData = [
    'title' => 'Support',
    'can_manage' => false,
    'summary' => [
        'all' => 0,
        'new' => 0,
        'open' => 0,
        'waiting_on_user' => 0,
        'resolved' => 0,
        'closed' => 0,
    ],
    'requests' => [],
    'detail' => null,
    'detail_notice' => null,
    'categories' => [],
    'directions' => [],
    'statuses' => [],
    'priorities' => [],
    'route_targets' => [],
];

try {
    $pdo = app_pdo();
    $tenantLicense = app_tenant_license($pdo, (string) $auth['tenant_id']);
    $tenantSettings = app_tenant_settings($pdo, (string) $auth['tenant_id']);
    $supportTablesReady = scripts_table_exists($pdo, 'support_requests')
        && scripts_table_exists($pdo, 'support_request_messages');
} catch (\Throwable $exception) {
    $dbError = $exception->getMessage();
}

if ($pdo instanceof PDO && $supportTablesReady && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!hash_equals((string) ($_SESSION['support_csrf'] ?? ''), (string) ($_POST['csrf'] ?? ''))) {
        app_flash('Die Sitzung ist abgelaufen. Bitte lade die Seite neu.', 'error');
        app_redirect('/support/');
    }

    $controller->handlePost($pdo, $auth, $_POST, $_GET);
}

if ($pdo instanceof PDO && $supportTablesReady) {
    $pageData = $controller->index($pdo, $auth, $_GET);
}

$csrf = (string) ($_SESSION['support_csrf'] ?? '');
$isManager = (bool) ($pageData['can_manage'] ?? false);
$requests = $pageData['requests'] ?? [];
$detail = $pageData['detail'] ?? null;
$summary = $pageData['summary'] ?? [];
$detailNotice = $pageData['detail_notice'] ?? null;
$categories = $pageData['categories'] ?? [];
$directions = $pageData['directions'] ?? [];
$statuses = $pageData['statuses'] ?? [];
$priorities = $pageData['priorities'] ?? [];
$routeTargets = $pageData['route_targets'] ?? [];
$selectedRequestId = (string) ($_GET['request'] ?? '');
$tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);
$tenantNavGroups = app_tenant_navigation_groups($tenantNavItems);
$tenantHeaderNavItems = [];
$mobileBottomNavItems = [];
$mobileDrawerPrimaryItems = [];
foreach ($tenantNavItems as $item) {
    if (in_array((string) ($item['key'] ?? ''), ['dashboard', 'ledger', 'payments'], true)) {
        $tenantHeaderNavItems[] = $item;
        $mobileBottomNavItems[] = $item;
    }
}

$template = dirname(__DIR__, 2) . '/resources/views/support/index.blade.php';
if (!is_file($template)) {
    throw new RuntimeException('Die Support-Ansicht konnte nicht gefunden werden.');
}

ob_start();
require $template;
$output = ob_get_clean();

echo $output;
