<?php
use App\Core\Auth;
use App\Models\TeamRepository;
use App\Models\UserRepository;
use App\Core\Database;

$loggedIn = Auth::check();
$loggedInUser = Auth::user();
$isHome = $isHome ?? false;

$teamCount = 0;
$userCount = 0;

if ($loggedIn && isset($GLOBALS['db']) && $loggedInUser) {
    try {
        $db = $GLOBALS['db'];
        $teamRepo = new TeamRepository($db);
        $userRepo = new UserRepository($db);
        if ($loggedInUser['role'] === 'admin') {
            $allTeams = $teamRepo->findAll();
            $teamCount = count($allTeams ?? []);
        } else {
            $userTeams = $teamRepo->getTeamsForUser($loggedInUser['id']);
            $teamCount = count($userTeams ?? []);
        }
        if ($loggedInUser['role'] === 'admin') {
            $allUsers = $userRepo->findAll();
            $userCount = count($allUsers ?? []);
        } elseif ($loggedInUser['role'] === 'trener') {
            $userCount = $userRepo->getCountCreatedByUser($loggedInUser['id']);
        }
    } catch (\Exception $e) {
        // Pokud dojde k chybě, zůstávají počty na 0
    }
}?>
<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="UTF-8">
    <title><?= $isHome ? 'TeamHub' : ($loggedIn ? 'Nástěnka' : 'Přihlášení') ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="<?= BASE_URL ?>/images/TH_logo.png" type="image/png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest/dist/tabler-icons.min.css" />
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.20/index.global.min.js'></script>
    <script src='https://cdn.jsdelivr.net/npm/@fullcalendar/bootstrap5@6.1.20/index.global.min.js'></script>
    <style>
        body { background-color: #f8f9fa; }
        <?php if ($loggedIn): ?>
        .sidebar { min-height: calc(100vh - 56px); }
        .navbar { min-height: 56px; overflow: visible; }
        .offcanvas-header { height: 56px; }
        .note-card { border-left: 4px solid #0d6efd; }
        .menu-icon { width: 24px; height: 24px; object-fit: contain; }
        @media (max-width: 767.98px) {
            .navbar-nav .dropdown-menu { position: absolute !important; }
        }
        <?php endif; ?>
        @media print {
            nav.navbar, .sidebar, .offcanvas, .no-print,
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter,
            .dataTables_wrapper .dataTables_info,
            .dataTables_wrapper .dataTables_paginate { display: none !important; }
            .tab-pane:not(.active) { display: none !important; }
            main.col-md-9, main.col-lg-10 { max-width: 100% !important; flex: 0 0 100% !important; padding: 0 !important; }
            body { background: #fff !important; }
            input[type="radio"] { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .card { border: none !important; box-shadow: none !important; }
        }
    </style>
</head>
<body>
<?php if ($loggedIn): ?>
<!-- =================== HORNÍ NAVBAR =================== -->
<nav class="navbar navbar-expand-md navbar-dark bg-primary">
    <div class="container-fluid">
        <button id="mobileMenuBtn" class="navbar-toggler collapsed d-md-none me-2"
                type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileSidebar">
            <span class="navbar-toggler-icon" style="opacity: 1;"></span>
        </button>
        <a class="navbar-brand fw-bold d-none d-md-block" href="<?= BASE_URL ?>/dashboard/index">TeamHub</a>
        <ul class="navbar-nav ms-auto">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle d-flex align-items-center text-white"
                   href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <span class="me-2">Přihlášen:</span>
                    <strong><?= htmlspecialchars($loggedInUser['jmeno'] ?? '') ?></strong>
                </a>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="<?= BASE_URL ?>/user/show?id=<?= $loggedInUser['id'] ?>">Můj profil</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="<?= BASE_URL ?>/auth/logout">Odhlásit se</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>
<!-- =================== MOBILNÍ SIDEBAR =================== -->
<div class="offcanvas offcanvas-start d-md-none" id="mobileSidebar">
    <div class="offcanvas-header border-bottom text-bg-primary">
        <h5><a href="<?= BASE_URL ?>/dashboard/index" class="offcanvas-title fw-bold text-decoration-none text-white">TeamHub</a></h5>
        <button type="button" class="btn-close btn-close-white btn-close-focus-opacity" data-bs-dismiss="offcanvas" style="opacity: 1;"></button>
    </div>
    <div class="offcanvas-body">
        <ul class="nav flex-column">
            <li class="nav-item mb-2">
                <a class="nav-link" href="<?= BASE_URL ?>/nastenka/index">
                    <img src="<?= BASE_URL ?>/images/pin.png" class="menu-icon me-2"> Nástěnka
                </a>
            </li>
            <li class="nav-item mb-2">
                <a class="nav-link" href="<?= BASE_URL ?>/kalendar/index">
                    <img src="<?= BASE_URL ?>/images/calendarnovy.png" class="menu-icon me-2"> Kalendář akcí
                </a>
            </li>
            <li class="nav-item mb-2">
                <a class="nav-link" href="<?= BASE_URL ?>/team/index">
                    <img src="<?= BASE_URL ?>/images/users.png" class="menu-icon me-2"> Týmy
                    <span class="badge bg-secondary ms-2"><?= $teamCount ?></span>
                </a>
            </li>
            <?php if ($loggedInUser && in_array($loggedInUser['role'], ['admin', 'trener'])): ?>
            <li class="nav-item mb-2">
                <a class="nav-link" href="<?= BASE_URL ?>/user/index">
                    <img src="<?= BASE_URL ?>/images/add-user.png" class="menu-icon me-2"> Uživatelé
                    <span class="badge bg-secondary ms-2"><?= $userCount ?></span>
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </div>
</div>
<!-- =================== LAYOUT =================== -->
<div class="container-fluid">
    <div class="row">
        <nav class="col-md-3 col-lg-2 d-none d-md-block bg-white sidebar border-end p-3">
            <ul class="nav flex-column">
                <li class="nav-item mb-2">
                    <a class="nav-link <?= ($_GET['controller'] ?? '') === 'nastenka' ? 'active fw-semibold' : '' ?>"
                       href="<?= BASE_URL ?>/nastenka/index">
                        <img src="<?= BASE_URL ?>/images/pin.png" class="menu-icon me-2"> Nástěnka
                    </a>
                </li>
                <li class="nav-item mb-2">
                    <a class="nav-link <?= ($_GET['controller'] ?? '') === 'kalendar' ? 'active fw-semibold' : '' ?>"
                       href="<?= BASE_URL ?>/kalendar/index">
                        <img src="<?= BASE_URL ?>/images/calendarnovy.png" class="menu-icon me-2"> Kalendář akcí
                    </a>
                </li>
                <li class="nav-item mb-2">
                    <a class="nav-link <?= ($_GET['controller'] ?? '') === 'team' ? 'active fw-semibold' : '' ?>"
                       href="<?= BASE_URL ?>/team/index">
                        <img src="<?= BASE_URL ?>/images/users.png" class="menu-icon me-2"> Týmy
                        <span class="badge bg-secondary ms-2"><?= $teamCount ?></span>
                    </a>
                </li>
                <?php if ($loggedInUser && in_array($loggedInUser['role'], ['admin', 'trener'])): ?>
                <li class="nav-item mb-2">
                    <a class="nav-link <?= ($_GET['controller'] ?? '') === 'user' ? 'active fw-semibold' : '' ?>"
                       href="<?= BASE_URL ?>/user/index">
                        <img src="<?= BASE_URL ?>/images/user.png" class="menu-icon me-2"> Uživatelé
                        <span class="badge bg-secondary ms-2"><?= $userCount ?></span>
                    </a>
                </li>
                <?php endif; ?>
            </ul>
        </nav>
        <main class="col-12 col-md-9 col-lg-10 px-md-4 py-4">
<?php
$flash = \App\Core\Auth::getFlash();
if ($flash):
?>
            <div class="alert alert-<?= $flash['type'] === 'success' ? 'success' : ($flash['type'] === 'error' ? 'danger' : 'warning') ?> alert-dismissible fade show" role="alert">
                <i class="ti <?= $flash['type'] === 'success' ? 'ti-check' : ($flash['type'] === 'error' ? 'ti-alert-circle' : 'ti-info-circle') ?>"></i>
                <?= htmlspecialchars($flash['message']) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
<?php endif; ?>

<?php elseif ($isHome): ?>

<!-- =================== HOME NAVBAR =================== -->
<nav class="navbar navbar-expand-md navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand fw-bold" href="<?= BASE_URL ?>">TeamHub</a>
        <div class="ms-auto">
            <a href="<?= BASE_URL ?>/auth/login" class="btn btn-outline-light btn-sm">Přihlásit se</a>
        </div>
    </div>
</nav>
<div>

<?php else: ?>

<!-- =================== LOGIN =================== -->
<div class="container d-flex justify-content-center align-items-center" style="height:100vh;">
    <div class="col-md-4">

<?php endif; ?>

<?php
/** @var \App\Core\View $this */
include $this->file;
?>

<?php if ($loggedIn): ?>
        </main>
    </div>
</div>
<?php else: ?>
</div>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const offcanvas = document.getElementById('mobileSidebar');
    const button = document.getElementById('mobileMenuBtn');
    if (offcanvas && button) {
        offcanvas.addEventListener('hidden.bs.offcanvas', function () {
            setTimeout(() => { button.blur(); }, 50);
        });
    }
});
</script>
    <!-- datatables-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/2.3.7/css/dataTables.bootstrap5.css" />
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.datatables.net/2.3.7/js/dataTables.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/2.3.7/js/dataTables.bootstrap5.js"></script>
    <script src="https://cdn.datatables.net/responsive/3.0.4/js/dataTables.responsive.js"></script>
    <script src="https://cdn.datatables.net/responsive/3.0.4/js/responsive.bootstrap5.js"></script>
    <script>
        const dtLanguageCZ = {
            search: "Hledat:",
            searchPlaceholder: "Hledat...",
            lengthMenu: "Zobrazit _MENU_ záznamů",
            info: "Zobrazeno _START_–_END_ z _TOTAL_ záznamů",
            infoEmpty: "Zobrazeno 0 záznamů",
            infoFiltered: "(filtrováno z _MAX_ záznamů)",
            zeroRecords: "Žádné záznamy nenalezeny",
            emptyTable: "Tabulka neobsahuje žádná data",
            paginate: { first: "«", last: "»", next: "›", previous: "‹" },
            aria: {
                sortAscending: ": aktivovat pro řazení vzestupně",
                sortDescending: ": aktivovat pro řazení sestupně"
            }
        };
        const tables = $('#TableTeams, #TableUsers, #TableEvents, #TableMembers, #TableAttendance').DataTable({
            language: dtLanguageCZ,
            responsive: true,
            pageLength: 10
        });
    </script>
</body>
</html>
