<?php
$teacherName = $_SESSION['user_name'] ?? 'Teacher';
$teacherInitial = function_exists('mb_substr') ? mb_strtoupper(mb_substr($teacherName, 0, 1)) : strtoupper(substr($teacherName, 0, 1));
$currentRole = strtolower(trim((string) ($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$teacherRole = $currentRole === 'admin' ? 'Admin' : 'Teacher';
$teacherEmail = $_SESSION['user_email'] ?? '';

/*
 * Working Book selector
 * - Admin: can choose any active book.
 * - Teacher: can choose only books assigned through teacher_content_assignments.
 * - The selected book is stored in $_SESSION['teacher_book_id'] and reused across Teacher Portal.
 */
$workingBooks = [];
$currentBookId = (int)($_SESSION['teacher_book_id'] ?? 0);
$currentBookName = '';

try {
    require_once __DIR__ . '/../../config/database.php';
    $topbarPdo = getDbConnection();

    if ($currentRole === 'admin') {
        $bookStmt = $topbarPdo->query(
            "SELECT id, name
             FROM books
             WHERE status = 'active'
             ORDER BY id"
        );
        $workingBooks = $bookStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $teacherId = (int)($_SESSION['user_id'] ?? 0);

        $bookStmt = $topbarPdo->prepare(
            "SELECT DISTINCT b.id, b.name
             FROM teacher_content_assignments tca
             INNER JOIN books b ON b.id = tca.book_id
             WHERE tca.teacher_id = ?
               AND tca.status = 'active'
               AND b.status = 'active'
             ORDER BY b.id"
        );
        $bookStmt->execute([$teacherId]);
        $workingBooks = $bookStmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $allowedBookIds = array_map(
        static fn(array $book): int => (int)$book['id'],
        $workingBooks
    );

    if ($currentBookId <= 0 || !in_array($currentBookId, $allowedBookIds, true)) {
        $currentBookId = $allowedBookIds[0] ?? 0;

        if ($currentBookId > 0) {
            $_SESSION['teacher_book_id'] = $currentBookId;
        } else {
            unset($_SESSION['teacher_book_id']);
        }
    }

    foreach ($workingBooks as $book) {
        if ((int)$book['id'] === $currentBookId) {
            $currentBookName = (string)$book['name'];
            break;
        }
    }
} catch (Throwable $e) {
    error_log('EnglishSpeak topbar working book: ' . $e->getMessage());
    $workingBooks = [];
    $currentBookId = 0;
    $currentBookName = '';
}

$currentReturnUrl = $_SERVER['REQUEST_URI'] ?? '/EnglishSpeak/teacher/dashboard/';
?>
<style>
.working-book-selector{
    display:flex;
    align-items:center;
    gap:7px;
    min-height:40px;
    padding:0 10px;
    border:1px solid #dbe2ea;
    border-radius:11px;
    background:#fff;
}
.working-book-icon{
    flex:0 0 auto;
    font-size:16px;
}
.working-book-selector select{
    max-width:190px;
    min-width:145px;
    height:36px;
    padding:0 26px 0 0;
    border:0;
    outline:0;
    background:transparent;
    color:#0f172a;
    font:inherit;
    font-size:12px;
    font-weight:750;
    cursor:pointer;
}
html[data-theme="dark"] .working-book-selector{
    border-color:#334155;
    background:#0f172a;
}
html[data-theme="dark"] .working-book-selector select{
    color:#e2e8f0;
}
@media(max-width:1100px){
    .working-book-selector select{max-width:145px;min-width:120px}
}
@media(max-width:860px){
    .working-book-selector{display:none}
}
</style>

<header class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle icon-button" id="menuToggle" type="button" aria-label="Open menu">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
        </button>

        <div class="page-heading">
            <div class="breadcrumb">
                <span>EnglishSpeak</span>
                <b>/</b>
                <strong><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></strong>
            </div>
            <h1><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
            <?php if (!empty($pageSubtitle)): ?>
                <p><?= htmlspecialchars($pageSubtitle, ENT_QUOTES, 'UTF-8') ?></p>
            <?php endif; ?>
        </div>
    </div>

    <div class="topbar-actions">
        <?php if ($workingBooks !== []): ?>
            <form
                class="working-book-selector"
                method="post"
                action="/EnglishSpeak/teacher/switch-book.php"
                title="Sách đang làm việc"
            >
                <input
                    type="hidden"
                    name="return_url"
                    value="<?= htmlspecialchars($currentReturnUrl, ENT_QUOTES, 'UTF-8') ?>"
                >
                <span class="working-book-icon" aria-hidden="true">📘</span>
                <select
                    name="book_id"
                    aria-label="Sách đang làm việc"
                    onchange="this.form.submit()"
                >
                    <?php foreach ($workingBooks as $book): ?>
                        <option
                            value="<?= (int)$book['id'] ?>"
                            <?= (int)$book['id'] === $currentBookId ? 'selected' : '' ?>
                        >
                            <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </form>
        <?php endif; ?>

        <!-- Search -->
        <label class="global-search" for="teacherSearch">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
            <input id="teacherSearch" type="search" placeholder="Search content, students..." autocomplete="off">
            <kbd>&#8984;K</kbd>
        </label>

        <!-- Notification -->
        <button class="icon-button notification-button" type="button" aria-label="Notifications" title="Notifications">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>
            <span class="badge-dot"></span>
        </button>

        <!-- Theme Toggle -->
        <button class="icon-button" id="themeToggle" type="button" aria-label="Toggle theme" title="Switch theme">
            <svg class="theme-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.42-1.42M17.66 6.34l1.41-1.41"/></svg>
            <svg class="theme-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg>
        </button>

        <!-- Profile -->
        <div class="profile-menu-wrap" id="profileMenuWrap">
            <button class="profile-button" id="profileMenuButton" type="button" aria-expanded="false" aria-haspopup="true">
                <span class="user-avatar"><?= htmlspecialchars($teacherInitial, ENT_QUOTES, 'UTF-8') ?></span>
                <span class="user-copy">
                    <strong><?= htmlspecialchars($teacherName, ENT_QUOTES, 'UTF-8') ?></strong>
                    <small><?= htmlspecialchars($teacherRole, ENT_QUOTES, 'UTF-8') ?></small>
                </span>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6"/></svg>
            </button>
            <div class="profile-dropdown" id="profileDropdown">
                <div class="dropdown-header">
                    <strong><?= htmlspecialchars($teacherName, ENT_QUOTES, 'UTF-8') ?></strong>
                    <span><?= htmlspecialchars($teacherEmail ?: $teacherRole, ENT_QUOTES, 'UTF-8') ?></span>
                </div>
                <a href="../settings/">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09a1.7 1.7 0 0 0-1.1-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.65 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.65a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.15.37.36.71.6 1 .29.32.68.52 1.1.6H21v4h-.09A1.7 1.7 0 0 0 19.4 15Z"/></svg>
                    Settings
                </a>
                <div class="dropdown-divider"></div>
                <a href="../logout.php" class="danger-link">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 17l5-5-5-5"/><path d="M15 12H3"/><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/></svg>
                    Logout
                </a>
            </div>
        </div>
    </div>
</header>