<?php
require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$pdo = getDbConnection();

$pageTitle = 'Dashboard';
$pageSubtitle = (($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher') === 'admin')
    ? 'Quản trị hệ thống EnglishSpeak'
    : 'Create and organize engaging English learning content';
$activeTeacherNav = 'dashboard';
$teacherName = $_SESSION['user_name'] ?? 'Teacher';
$userRole = $_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher';
$isAdmin = ($userRole === 'admin');

$assignedBooks = [];
if (!$isAdmin) {
    $currentUserId = (int)($_SESSION['user_id'] ?? 0);
    if ($currentUserId > 0) {
        $bookStmt = $pdo->prepare(
            "SELECT b.id, b.name, b.slug
             FROM teacher_books tb
             INNER JOIN books b ON b.id = tb.book_id
             WHERE tb.teacher_id = :teacher_id
               AND b.status = 'active'
             ORDER BY b.sort_order ASC, b.name ASC"
        );
        $bookStmt->execute(['teacher_id' => $currentUserId]);
        $assignedBooks = $bookStmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
$assignedBookCount = count($assignedBooks);

// Referral code của giáo viên
$teacherReferralCode = '';
if (!$isAdmin) {
    $currentUserId = (int)($_SESSION['user_id'] ?? 0);
    if ($currentUserId > 0) {
        try {
            $refStmt = $pdo->prepare(
                "SELECT referral_code
                 FROM teacher_referral_codes
                 WHERE teacher_id = :teacher_id
                   AND status = 'active'
                 ORDER BY id DESC
                 LIMIT 1"
            );
            $refStmt->execute(['teacher_id' => $currentUserId]);
            $teacherReferralCode = (string)($refStmt->fetchColumn() ?: '');
        } catch (Throwable $e) {
            $teacherReferralCode = '';
        }
    }
}

$currentHour = (int) date('G');
$greeting = $currentHour < 12 ? 'Good morning' : ($currentHour < 18 ? 'Good afternoon' : 'Good evening');

ob_start();
?>

<!-- ═══════════════════════════════════════
     HERO SECTION
     ═══════════════════════════════════════ -->
<section class="dashboard-greeting">
    <h2><?= $greeting ?>, <?= htmlspecialchars($teacherName, ENT_QUOTES, 'UTF-8') ?> <span>👋</span></h2>

    <?php if (!$isAdmin): ?>
        <a class="button button-primary button-lg" href="../students/">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            View Students
        </a>
    <?php endif; ?>
</section>

<?php if (!$isAdmin): ?>
<div class="teacher-referral-card">
    <div class="teacher-referral-info">
        <span class="teacher-referral-label">Mã giới thiệu của bạn</span>
        <?php if ($teacherReferralCode !== ''): ?>
            <strong id="teacherReferralCode"><?= htmlspecialchars($teacherReferralCode, ENT_QUOTES, 'UTF-8') ?></strong>
          
        <?php else: ?>
            <strong class="teacher-referral-empty">Chưa có mã referral</strong>
            <small>Liên hệ Admin nếu tài khoản đã được duyệt nhưng chưa có mã.</small>
        <?php endif; ?>
    </div>
    <?php if ($teacherReferralCode !== ''): ?>
        <button type="button" class="teacher-referral-copy" id="copyReferralBtn">Copy</button>
    <?php endif; ?>
</div>

<?php if ($teacherReferralCode !== ''): ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('copyReferralBtn');
    const code = document.getElementById('teacherReferralCode');
    if (!btn || !code) return;

    btn.addEventListener('click', async function () {
        const value = code.textContent.trim();
        try {
            await navigator.clipboard.writeText(value);
        } catch (e) {
            const input = document.createElement('textarea');
            input.value = value;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            input.remove();
        }
        const oldText = btn.textContent;
        btn.textContent = 'Đã copy';
        setTimeout(() => btn.textContent = oldText, 1500);
    });
});
</script>
<?php endif; ?>
<?php endif; ?>

<style>
.dashboard-greeting{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:20px;
    margin:22px 0 28px;
}
.dashboard-greeting h2{
    margin:0;
    font-size:28px;
    line-height:1.2;
    font-weight:800;
    color:#12233f;
}
.dashboard-greeting .button{
    flex:0 0 auto;
}
.teacher-referral-card{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:18px;
    margin:-10px 0 28px;
    padding:14px 16px;
    max-width:560px;
    border:1px solid #dce8ff;
    border-radius:14px;
    background:#f7faff;
}
.teacher-referral-info{
    display:flex;
    flex-wrap:wrap;
    align-items:center;
    gap:7px 12px;
}
.teacher-referral-label{
    width:100%;
    color:#64748b;
    font-size:12px;
    font-weight:700;
}
.teacher-referral-info strong{
    color:#126b37;
    background:#eaf9ef;
    border-radius:8px;
    padding:6px 10px;
    font-size:15px;
    letter-spacing:.04em;
}
.teacher-referral-info strong.teacher-referral-empty{
    color:#8a5a00;
    background:#fff6dd;
    letter-spacing:0;
}
.teacher-referral-info small{
    color:#8190a7;
    font-size:12px;
}
.teacher-referral-copy{
    flex:0 0 auto;
    border:0;
    border-radius:9px;
    padding:9px 14px;
    background:#3267e8;
    color:#fff;
    font-weight:700;
    cursor:pointer;
}
.teacher-referral-copy:hover{background:#2858ca}
@media (max-width:700px){
    .dashboard-greeting{
        align-items:flex-start;
        flex-direction:column;
    }
    .teacher-referral-card{
        align-items:flex-start;
        flex-direction:column;
        max-width:none;
    }
}
</style>


<?php if ($isAdmin): ?>
<!-- ADMIN ONLY: chỉ bổ sung nội dung cho tài khoản Admin.
     Khối Teacher phía dưới được giữ nguyên. -->
<section class="admin-home-section">
    <div class="admin-home-heading">
        <div>
            <span class="admin-home-kicker">ADMIN</span>
            <h3>Quản lý hệ thống</h3>
            <p>Các chức năng quản trị thiết yếu.</p>
        </div>
    </div>

    <div class="admin-home-grid">
        <a class="admin-home-card" href="../teachers/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <circle cx="9" cy="7" r="4"/>
                    <path d="M2 21v-2a7 7 0 0 1 14 0v2"/>
                    <path d="M18 8v6M15 11h6"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Quản lý giáo viên</strong>
                <small>Duyệt tài khoản, gán sách và quản lý giáo viên</small>
            </span>
            <b>›</b>
        </a>

        <a class="admin-home-card" href="../students/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <circle cx="9" cy="7" r="4"/>
                    <path d="M2 21v-2a7 7 0 0 1 14 0v2"/>
                    <path d="M17 11a4 4 0 0 1 4 4v6"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Quản lý học sinh</strong>
                <small>Tài khoản, lớp học và dữ liệu học sinh</small>
            </span>
            <b>›</b>
        </a>

        <a class="admin-home-card" href="../books/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
                    <path d="M6.5 2H20v19H6.5A2.5 2.5 0 0 1 4 18.5v-14A2.5 2.5 0 0 1 6.5 2Z"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Quản lý nội dung</strong>
                <small>Book, Level, Unit và cấu trúc học liệu</small>
            </span>
            <b>›</b>
        </a>

        <a class="admin-home-card" href="../reports/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <path d="M4 19V9M10 19V5M16 19v-7M22 19H2"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Báo cáo</strong>
                <small>Theo dõi học tập, tiến độ và hoạt động hệ thống</small>
            </span>
            <b>›</b>
        </a>

        <a class="admin-home-card" href="../schools/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <path d="M3 21h18"/>
                    <path d="M6 21V7l6-4 6 4v14"/>
                    <path d="M9 10h2M13 10h2M9 14h2M13 14h2"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Tỉnh &amp; Trường</strong>
                <small>Quản lý danh mục tỉnh và trường</small>
            </span>
            <b>›</b>
        </a>

        <a class="admin-home-card" href="../word-library/">
            <span class="admin-home-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <rect x="3" y="3" width="18" height="18" rx="2"/>
                    <path d="M7 8h10M7 12h10M7 16h6"/>
                </svg>
            </span>
            <span class="admin-home-text">
                <strong>Word Library</strong>
                <small>Quản lý kho từ dùng chung</small>
            </span>
            <b>›</b>
        </a>
    </div>
</section>

<style>
.admin-home-section{margin:8px 0 34px}
.admin-home-heading{margin-bottom:16px}
.admin-home-kicker{display:block;color:#3267e8;font-size:11px;font-weight:800;letter-spacing:.12em;margin-bottom:5px}
.admin-home-heading h3{margin:0;color:#12233f;font-size:21px;font-weight:800}
.admin-home-heading p{margin:5px 0 0;color:#8090a8;font-size:13px}
.admin-home-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.admin-home-card{min-height:108px;padding:18px;border:1px solid #e6ebf3;border-radius:16px;background:#fff;display:flex;align-items:center;gap:14px;text-decoration:none;color:#12233f;box-shadow:0 2px 8px rgba(26,45,78,.035);transition:.18s ease}
.admin-home-card:hover{transform:translateY(-2px);border-color:#cfd9ea;box-shadow:0 8px 22px rgba(26,45,78,.08)}
.admin-home-icon{width:44px;height:44px;border-radius:12px;background:#f2f6ff;color:#3267e8;display:grid;place-items:center;flex:0 0 44px}
.admin-home-icon svg{width:22px;height:22px}
.admin-home-text{min-width:0;display:flex;flex-direction:column;gap:5px}
.admin-home-text strong{font-size:15px;font-weight:800}
.admin-home-text small{font-size:12px;line-height:1.4;color:#8491a6}
.admin-home-card>b{margin-left:auto;color:#9aa7bb;font-size:24px;font-weight:500}
@media(max-width:1050px){.admin-home-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:650px){.admin-home-grid{grid-template-columns:1fr}}
</style>
<?php endif; ?>


<?php if (!$isAdmin): ?>

<!-- ═══════════════════════════════════════
     YOUR LIBRARY
     ═══════════════════════════════════════ -->
<section class="section-block">
    <div class="section-heading-row">
        <div>
            <span class="section-kicker">Your Library</span>
            <h3>Content Overview</h3>
        </div>
        <span class="updated-label"><i></i> Updated just now</span>
    </div>
    <div class="stats-grid stats-grid-4">
        <!-- Books -->
        <article class="metric-card metric-blue">
            <div class="metric-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v19H6.5A2.5 2.5 0 0 1 4 18.5v-14A2.5 2.5 0 0 1 6.5 2Z"/><path d="M8 7h8M8 11h6"/></svg>
            </div>
            <div class="metric-main">
                <span>Books</span>
                <strong><?= $assignedBookCount ?></strong>
                <small><?= $assignedBookCount > 0 ? htmlspecialchars(implode(', ', array_column($assignedBooks, 'name')), ENT_QUOTES, 'UTF-8') : 'No books assigned' ?></small>
            </div>
            <a href="../books/" aria-label="View books">→</a>
        </article>

        <!-- Lessons -->
        <article class="metric-card metric-violet">
            <div class="metric-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
            </div>
            <div class="metric-main">
                <span>Lessons</span>
                <strong>0</strong>
                <small>Structured learning units</small>
            </div>
            <a href="../lessons/" aria-label="View lessons">→</a>
        </article>

        <!-- Activities -->
        <article class="metric-card metric-green">
            <div class="metric-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
            </div>
            <div class="metric-main">
                <span>Activities</span>
                <strong>0</strong>
                <small>Interactive exercises</small>
            </div>
            <a href="../activities/" aria-label="View activities">→</a>
        </article>





        <!-- Topics -->
        <article class="metric-card metric-rose">
            <div class="metric-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
            </div>
            <div class="metric-main">
                <span>Topics</span>
                <strong>0</strong>
                <small>Vocabulary & grammar topics</small>
            </div>
            <a href="../topic-library/" aria-label="View topics">→</a>
        </article>
    </div>
</section>


<!-- ═══════════════════════════════════════
     QUICK CREATE
     ═══════════════════════════════════════ -->
<section class="section-block">
    <div class="section-heading-row">
        <div>
            <span class="section-kicker">Quick Create</span>
            <h3>Start building something new</h3>
        </div>
    </div>
    <div class="quick-create-grid quick-create-grid-3">
        <!-- Content -->
        <a href="../books/" class="quick-create-tile qc-blue">
            <div class="qc-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v19H6.5A2.5 2.5 0 0 1 4 18.5v-14A2.5 2.5 0 0 1 6.5 2Z"/><path d="M8 7h8M8 11h6"/></svg>
            </div>
             <strong>Content</strong>
             <small>Books, units & lessons</small>
        </a>

        <!-- Lesson -->
        <a href="../lessons/" class="quick-create-tile qc-violet">
            <div class="qc-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
            </div>
            <strong>Lesson</strong>
            <small>Structured learning units</small>
        </a>





        <!-- Vocabulary -->
        <a href="../word-library/" class="quick-create-tile qc-amber">
            <div class="qc-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 3h18v18H3z"/><path d="M7 7h10M7 11h10M7 15h6"/></svg>
            </div>
            <strong>Word Library</strong>
            <small>Manage your word library</small>
        </a>


    </div>
</section>


<?php endif; ?>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';