<?php
declare(strict_types=1);

require __DIR__ . '/../partials/auth.php';

$pageTitle = 'Lesson';
$pageSubtitle = 'Manage lesson activities';
$activeTeacherNav = 'content';

require_once __DIR__ . '/../../config/database.php';
$pdo = getDbConnection();

$teacherId = (int)($_SESSION['user_id'] ?? 0);
$role = strtolower((string)($_SESSION['user_role'] ?? 'teacher'));
$isAdmin = ($role === 'admin');

$lessonId = (int)($_GET['id'] ?? 0);

if ($lessonId <= 0) {
    header('Location: ../books/index.php');
    exit;
}

function lessonTableColumns(PDO $pdo, string $table): array {
    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

function lessonTitle(array $lesson): string {
    return (string)($lesson['title']
        ?? $lesson['name']
        ?? $lesson['lesson_number']
        ?? 'Lesson');
}

function activityIcon(string $type): string {
    return match ($type) {
        'flashcards'      => '🃏',
        'listen_repeat'   => '🔊',
        'matching'        => '🧩',
        'memory'          => '🧠',
        'word_builder'    => '🔤',
        'guess_the_word'  => '🔠',
        'word_unscramble' => '🔀',
        'find_word'        => '🖼️',
        'fix_word'         => '✏️',
        'sentence_builder' => '🧩',
        'dialogue', 'ask_answer' => '💬',
        'quiz'            => '❓',
        'worksheet'       => '📄',
        'speaking'        => '🗣️',
        'game'            => '🎮',
        default           => '🎯',
    };
}


function logLessonContributionEvent(PDO $pdo, int $lessonId, int $teacherId, string $eventType, ?string $note = null): void {
    $allowed = ['created', 'submitted', 'returned', 'resubmitted', 'published'];
    if ($lessonId <= 0 || $teacherId <= 0 || !in_array($eventType, $allowed, true)) return;

    $stmt = $pdo->prepare(
        "INSERT INTO content_contribution_events
         (content_type, content_id, teacher_id, event_type, note, created_at)
         VALUES ('lesson', ?, ?, ?, ?, NOW())"
    );
    $stmt->execute([$lessonId, $teacherId, $eventType, ($note !== null && trim($note) !== '') ? trim($note) : null]);
}

$lessonColumns = lessonTableColumns($pdo, 'lessons');

$lessonTypeSelect = isset($lessonColumns['lesson_type'])
    ? 'l.lesson_type'
    : (isset($lessonColumns['type']) ? 'l.type' : "'vocabulary'");

$lessonTitleSelect = isset($lessonColumns['title'])
    ? 'l.title'
    : (isset($lessonColumns['name'])
        ? 'l.name'
        : (isset($lessonColumns['lesson_number']) ? 'l.lesson_number' : "'Lesson'"));

$lessonDescriptionSelect = isset($lessonColumns['description'])
    ? 'l.description'
    : "''";

$stmt = $pdo->prepare("
    SELECT
        l.id,
        l.unit_id,
        l.created_by_teacher_id,
        {$lessonTitleSelect} AS lesson_title,
        {$lessonDescriptionSelect} AS lesson_description,
        {$lessonTypeSelect} AS lesson_type,
        u.unit_number,
        u.title AS unit_title,
        u.level_id,
        b.id AS book_id,
        b.name AS book_name
    FROM lessons l
    INNER JOIN units u ON u.id = l.unit_id
    INNER JOIN books b ON b.id = u.book_id
    WHERE l.id = ?
    LIMIT 1
");
$stmt->execute([$lessonId]);
$lesson = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$lesson) {
    http_response_code(404);
    exit('Lesson not found.');
}

if (!$isAdmin) {
    $bookAccessStmt = $pdo->prepare(
        "SELECT 1
         WHERE EXISTS (
             SELECT 1 FROM teacher_books
             WHERE teacher_id = ? AND book_id = ?
         ) OR EXISTS (
             SELECT 1 FROM teacher_content_assignments
             WHERE teacher_id = ? AND book_id = ? AND level_id = ? AND status = 'active'
         )
         LIMIT 1"
    );
    $bookAccessStmt->execute([
        $teacherId, (int)$lesson['book_id'],
        $teacherId, (int)$lesson['book_id'], (int)$lesson['level_id']
    ]);

    if (!$bookAccessStmt->fetchColumn()) {
        http_response_code(403);
        exit('You are not allowed to view this Lesson.');
    }
}

$lessonOwnerId = (int)($lesson['created_by_teacher_id'] ?? 0);
$canManageLesson = $isAdmin || ($lessonOwnerId > 0 && $lessonOwnerId === $teacherId);

/* ---------- V3.2 Review / Publish ---------- */
$workflowStmt = $pdo->prepare(
    "SELECT * FROM content_review_workflow WHERE content_type = 'lesson' AND content_id = ? LIMIT 1"
);
$workflowStmt->execute([$lessonId]);
$workflow = $workflowStmt->fetch(PDO::FETCH_ASSOC);

if (!$workflow) {
    // Existing V3.1 Lesson: register lazily as Draft without changing the Lesson itself.
    $workflowAuthorId = $lessonOwnerId > 0 ? $lessonOwnerId : $teacherId;
    $createWorkflow = $pdo->prepare(
        "INSERT IGNORE INTO content_review_workflow
            (content_type, content_id, author_id, status, created_at, updated_at)
         VALUES ('lesson', ?, ?, 'draft', NOW(), NOW())"
    );
    $createWorkflow->execute([$lessonId, $workflowAuthorId]);
    $workflowStmt->execute([$lessonId]);
    $workflow = $workflowStmt->fetch(PDO::FETCH_ASSOC);
}

$reviewStatus = (string)($workflow['status'] ?? 'draft');
$isLessonAuthor = $isAdmin || ((int)($workflow['author_id'] ?? 0) === $teacherId);

// V3.2 editing lock:
// - Admin may always manage.
// - Author/owner may edit only while Draft or Needs Revision.
// - Pending Review and Published are read-only for normal teachers.
$canEditLessonContent = $isAdmin || (
    $canManageLesson
    && $isLessonAuthor
    && in_array($reviewStatus, ['draft', 'needs_revision'], true)
);

$leadStmt = $pdo->prepare(
    "SELECT 1
     FROM teacher_content_assignments
     WHERE teacher_id = ?
       AND book_id = ?
       AND level_id = ?
       AND role = 'lead'
       AND status = 'active'
     LIMIT 1"
);
$leadStmt->execute([$teacherId, (int)$lesson['book_id'], (int)$lesson['level_id']]);
$isLeadReviewer = (bool)$leadStmt->fetchColumn();
$canReviewLesson = $isAdmin || $isLeadReviewer;
$isLeadAuthor = $isLessonAuthor && $isLeadReviewer;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'review_workflow') {
    $workflowAction = (string)($_POST['workflow_action'] ?? '');
    $reviewNote = trim((string)($_POST['review_note'] ?? ''));

    if ($workflowAction === 'publish_direct') {
        if (!$isAdmin && (!$isLeadAuthor || !in_array($reviewStatus, ['draft', 'needs_revision'], true))) {
            http_response_code(403);
            exit('You are not allowed to publish this Lesson directly.');
        }

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare(
                "UPDATE content_review_workflow
                 SET status = 'published', submitted_by = ?, submitted_at = NOW(),
                     reviewed_by = ?, reviewed_at = NOW(), review_note = NULL,
                     published_at = NOW(), updated_at = NOW()
                 WHERE content_type = 'lesson' AND content_id = ?"
            );
            $stmt->execute([$teacherId, $teacherId, $lessonId]);

            if ($reviewStatus === 'needs_revision') {
                logLessonContributionEvent($pdo, $lessonId, $teacherId, 'resubmitted');
            }
            logLessonContributionEvent($pdo, $lessonId, $teacherId, 'published');

            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        $_SESSION['lesson_review_message'] = 'Lesson published.';
    } elseif ($workflowAction === 'submit') {
        if (!$isLessonAuthor || !in_array($reviewStatus, ['draft', 'needs_revision'], true)) {
            http_response_code(403);
            exit('This Lesson cannot be submitted by this account.');
        }

        $eventType = $reviewStatus === 'needs_revision' ? 'resubmitted' : 'submitted';

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare(
                "UPDATE content_review_workflow
                 SET status = 'pending_review', submitted_by = ?, submitted_at = NOW(),
                     reviewed_by = NULL, reviewed_at = NULL, review_note = NULL,
                     published_at = NULL, updated_at = NOW()
                 WHERE content_type = 'lesson' AND content_id = ?"
            );
            $stmt->execute([$teacherId, $lessonId]);
            logLessonContributionEvent($pdo, $lessonId, $teacherId, $eventType);
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        $_SESSION['lesson_review_message'] = $eventType === 'resubmitted'
            ? 'Lesson resubmitted for review.'
            : 'Lesson submitted for review.';
    } elseif ($workflowAction === 'approve') {
        if (!$canReviewLesson || $reviewStatus !== 'pending_review') {
            http_response_code(403);
            exit('You are not allowed to approve this Lesson.');
        }

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare(
                "UPDATE content_review_workflow
                 SET status = 'published', reviewed_by = ?, reviewed_at = NOW(),
                     review_note = ?, published_at = NOW(), updated_at = NOW()
                 WHERE content_type = 'lesson' AND content_id = ?"
            );
            $stmt->execute([$teacherId, $reviewNote !== '' ? $reviewNote : null, $lessonId]);
            logLessonContributionEvent($pdo, $lessonId, $teacherId, 'published', $reviewNote !== '' ? $reviewNote : null);
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        $_SESSION['lesson_review_message'] = 'Lesson published.';
    } elseif ($workflowAction === 'needs_revision') {
        if (!$canReviewLesson || $reviewStatus !== 'pending_review' || $reviewNote === '') {
            http_response_code(403);
            exit('A revision note is required.');
        }

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare(
                "UPDATE content_review_workflow
                 SET status = 'needs_revision', reviewed_by = ?, reviewed_at = NOW(),
                     review_note = ?, published_at = NULL, updated_at = NOW()
                 WHERE content_type = 'lesson' AND content_id = ?"
            );
            $stmt->execute([$teacherId, $reviewNote, $lessonId]);
            logLessonContributionEvent($pdo, $lessonId, $teacherId, 'returned', $reviewNote);
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        $_SESSION['lesson_review_message'] = 'Lesson returned for revision.';
    }

    header('Location: detail.php?id=' . $lessonId);
    exit;
}


$activityColumns = lessonTableColumns($pdo, 'activities');

/* ---------- Move Activity Up / Down ---------- */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'move_activity'
    && isset($activityColumns['sort_order'])
) {
    if (!$canEditLessonContent) {
        http_response_code(403);
        exit('This Lesson is locked while Pending Review or Published.');
    }
    $moveActivityId = max(0, (int)($_POST['activity_id'] ?? 0));
    $moveLessonId = max(0, (int)($_POST['lesson_id'] ?? 0));
    $direction = (string)($_POST['direction'] ?? '');

    if (
        $moveActivityId > 0
        && $moveLessonId === $lessonId
        && in_array($direction, ['up', 'down'], true)
    ) {
        $orderStmt = $pdo->prepare("
            SELECT id
            FROM activities
            WHERE lesson_id = ?
            ORDER BY sort_order ASC, id ASC
        ");
        $orderStmt->execute([$lessonId]);
        $orderedIds = array_map('intval', $orderStmt->fetchAll(PDO::FETCH_COLUMN));

        $currentIndex = array_search($moveActivityId, $orderedIds, true);

        if ($currentIndex !== false) {
            $targetIndex = $direction === 'up'
                ? $currentIndex - 1
                : $currentIndex + 1;

            if (isset($orderedIds[$targetIndex])) {
                [$orderedIds[$currentIndex], $orderedIds[$targetIndex]] =
                    [$orderedIds[$targetIndex], $orderedIds[$currentIndex]];

                $pdo->beginTransaction();
                try {
                    $updateOrder = $pdo->prepare("
                        UPDATE activities
                        SET sort_order = ?
                        WHERE id = ? AND lesson_id = ?
                    ");

                    foreach ($orderedIds as $index => $id) {
                        $updateOrder->execute([$index + 1, $id, $lessonId]);
                    }

                    $pdo->commit();
                } catch (Throwable $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    throw $e;
                }
            }
        }
    }

    header('Location: detail.php?id=' . $lessonId);
    exit;
}

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'toggle_activity_status'
    && isset($activityColumns['status'])
) {
    if (!$canEditLessonContent) {
        http_response_code(403);
        exit('This Lesson is locked while Pending Review or Published.');
    }
    $toggleActivityId = max(0, (int)($_POST['activity_id'] ?? 0));
    $toggleLessonId = max(0, (int)($_POST['lesson_id'] ?? 0));
    $toggleTo = strtolower(trim((string)($_POST['toggle_to'] ?? '')));

    if (
        $toggleActivityId > 0
        && $toggleLessonId === $lessonId
        && in_array($toggleTo, ['active', 'inactive'], true)
    ) {
        $toggleStmt = $pdo->prepare(
            "UPDATE activities
             SET status = ?
             WHERE id = ?
               AND lesson_id = ?"
        );
        $toggleStmt->execute([
            $toggleTo,
            $toggleActivityId,
            $lessonId,
        ]);
    }

    header('Location: detail.php?id=' . $lessonId);
    exit;
}

$activityTitleSelect = isset($activityColumns['title'])
    ? 'a.title'
    : (isset($activityColumns['name']) ? 'a.name' : "'Activity'");

$activityTypeSelect = isset($activityColumns['activity_type'])
    ? 'a.activity_type'
    : (isset($activityColumns['type']) ? 'a.type' : "'activity'");

$activityDescriptionSelect = isset($activityColumns['description'])
    ? 'a.description'
    : "''";

$activityStatusWhere = '';

$activityOrder = isset($activityColumns['sort_order'])
    ? 'a.sort_order, a.id'
    : 'a.id';

$activitiesStmt = $pdo->prepare("
    SELECT
        a.id,
        {$activityTitleSelect} AS activity_title,
        {$activityTypeSelect} AS activity_type,
        {$activityDescriptionSelect} AS activity_description,
        " . (isset($activityColumns['status']) ? "a.status" : "'active'") . " AS activity_status
    FROM activities a
    WHERE a.lesson_id = ?
    {$activityStatusWhere}
    ORDER BY {$activityOrder}
");
$activitiesStmt->execute([$lessonId]);
$activities = $activitiesStmt->fetchAll(PDO::FETCH_ASSOC);

$activityOptions = [
    ['type' => 'flashcards',       'icon' => '🃏', 'label' => 'Flashcards',       'desc' => 'Review words with image cards', 'example' => '⚽ ball — xem hình, từ và nghe phát âm.'],
    ['type' => 'listen_repeat',    'icon' => '🔊', 'label' => 'Listen & Repeat',  'desc' => 'Listen and practise pronunciation', 'example' => '🔊 ball → học sinh nghe rồi đọc lại.'],
    ['type' => 'matching',         'icon' => '🧩', 'label' => 'Matching',          'desc' => 'Match words, images or meanings', 'example' => '⚽ ↔ ball — ghép hình với từ đúng.'],
    ['type' => 'memory',           'icon' => '🧠', 'label' => 'Memory',            'desc' => 'Find matching word pairs', 'example' => '🂠 🂠 → lật thẻ để tìm cặp ⚽ + ball.'],
    ['type' => 'word_builder',     'icon' => '🔤', 'label' => 'Word Builder',      'desc' => 'Build words from letters', 'example' => 'b + a + l + l → ball.'],
    ['type' => 'guess_the_word',   'icon' => '🔠', 'label' => 'Guess the Word',    'desc' => 'Look at the picture and guess the word one letter at a time', 'example' => '⚽  _ _ _ _ → đoán từng chữ của “ball”.'],
    ['type' => 'word_unscramble',  'icon' => '🔀', 'label' => 'Word Unscramble',   'desc' => 'Arrange letters to make a word', 'example' => 'l • a • b • l → sắp xếp thành “ball”.'],
    ['type' => 'find_word',        'icon' => '🖼️', 'label' => 'Find the Word',      'desc' => 'Look at the picture and find the correct word', 'example' => '⚽ → chọn: book / ball / bike.'],
    ['type' => 'fix_word',         'icon' => '✏️', 'label' => 'Fix the Word',       'desc' => 'Remove the extra letter to make the correct word', 'example' => 'baall → bỏ chữ thừa để được “ball”.'],
    ['type' => 'sentence_builder', 'icon' => '🧩', 'label' => 'Sentence Builder',  'desc' => 'Build sentences from words', 'example' => 'a / This / ball / is → “This is a ball.”'],
    ['type' => 'dialogue',         'icon' => '💬', 'label' => 'Dialogue',          'desc' => 'Listen and choose the best response', 'example' => 'What’s this? → chọn “It’s a ball.”'],
    ['type' => 'ask_answer',       'icon' => '🎤', 'label' => 'Ask & Answer',      'desc' => 'Listen to the question and answer by speaking', 'example' => 'What’s this? 🎤 Học sinh nói: “It’s a ball.”'],
    ['type' => 'quiz',             'icon' => '❓', 'label' => 'Quiz',              'desc' => 'Quick review questions', 'example' => 'What is this? ⚽ → chọn đáp án đúng.'],
    ['type' => 'speaking',         'icon' => '🗣️', 'label' => 'Speaking',          'desc' => 'Speaking prompts and practice', 'example' => '🎤 “This is a ball.” → học sinh nói và nhận điểm phát âm.'],
    ['type' => 'worksheet',        'icon' => '📄', 'label' => 'Worksheet',         'desc' => 'Printable practice activities', 'example' => '📄 Bài tập có thể in ra để học sinh luyện tập.'],
];

ob_start();
?>

<style>
.lesson-page {
    display: grid;
    gap: 18px;
}

.lesson-hero {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 20px;
}

.lesson-breadcrumb {
    display: flex;
    flex-wrap: wrap;
    gap: 7px;
    color: var(--muted);
    font-size: 12px;
    margin-bottom: 8px;
}

.lesson-breadcrumb a {
    color: inherit;
    text-decoration: none;
}

.lesson-title {
    margin: 0;
    font-size: 28px;
}

.lesson-description {
    margin: 6px 0 0;
    color: var(--muted);
}

.lesson-toolbar {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    align-items: center;
}

.lesson-search {
    max-width: 360px;
    width: 100%;
}

.lesson-grid {
    display: grid;
    gap: 12px;
}

.lesson-activity-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 18px;
    padding: 16px;
    border: 1px solid var(--border);
    border-radius: 14px;
    background: var(--surface);
}

.lesson-activity-row.is-disabled {
    opacity: .58;
    background: #f7f8fa;
}

.lesson-activity-status {
    display: inline-flex;
    width: fit-content;
    margin-top: 2px;
    padding: 3px 8px;
    border-radius: 999px;
    background: #eef1f4;
    color: #6b7280 !important;
    font-size: 11px !important;
    font-weight: 800;
}

.lesson-activity-main {
    display: flex;
    align-items: center;
    gap: 13px;
    min-width: 0;
}

.lesson-activity-icon {
    display: grid;
    place-items: center;
    width: 48px;
    height: 48px;
    flex: 0 0 48px;
    border-radius: 13px;
    background: #eef4ff;
    font-size: 22px;
}

.lesson-activity-info {
    display: grid;
    gap: 4px;
}

.lesson-activity-info span {
    color: var(--muted);
    font-size: 12px;
}

.lesson-activity-actions {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
}

.lesson-move-controls {
    display: inline-flex;
    gap: 4px;
    margin-right: 2px;
}

.lesson-move-button {
    min-width: 34px;
    padding-left: 8px !important;
    padding-right: 8px !important;
    font-size: 15px;
    line-height: 1;
}

.lesson-move-button:disabled {
    opacity: .35;
    cursor: not-allowed;
}

.lesson-empty {
    padding: 56px 22px;
    text-align: center;
    border: 1px dashed var(--border);
    border-radius: 16px;
    background: var(--surface);
}

.lesson-empty-icon {
    font-size: 42px;
    margin-bottom: 12px;
}

.activity-picker {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

.activity-choice {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    padding: 12px;
    border: 1px solid var(--border);
    border-radius: 12px;
    cursor: pointer;
}

.activity-choice:hover {
    border-color: #9bb8ff;
    background: #f7f9ff;
}

.activity-choice input {
    margin-top: 4px;
}

.activity-choice-icon {
    font-size: 22px;
}

.activity-choice-text {
    display: grid;
    gap: 3px;
}

.activity-choice-text small {
    color: var(--muted);
}

.activity-choice {
    position: relative;
}

.activity-choice-example {
    position: absolute;
    z-index: 30;
    left: 14px;
    right: 14px;
    top: calc(100% + 7px);
    display: none;
    padding: 10px 12px;
    border: 1px solid #cbd8f5;
    border-radius: 10px;
    background: #ffffff;
    color: #1f2937;
    font-size: 12px;
    line-height: 1.45;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .14);
    pointer-events: none;
}

.activity-choice-example strong {
    display: block;
    margin-bottom: 3px;
    color: #2563eb;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: .03em;
}

@media (hover: hover) and (pointer: fine) {
    .activity-choice:hover .activity-choice-example,
    .activity-choice:focus-within .activity-choice-example {
        display: block;
    }
}

@media (max-width: 720px) {
    .lesson-hero,
    .lesson-toolbar,
    .lesson-activity-row {
        align-items: stretch;
        flex-direction: column;
    }

    .activity-picker {
        grid-template-columns: 1fr;
    }

    .lesson-activity-actions {
        justify-content: flex-start;
    }
}
.review-box { margin: 0 0 18px; padding: 16px; border: 1px solid var(--border); border-radius: 14px; background: var(--surface); }
.review-row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
.review-pill { display:inline-flex; padding:5px 10px; border-radius:999px; font-size:12px; font-weight:800; background:#eef2ff; }
.review-note { margin-top:10px; color:var(--muted); font-size:13px; }
.review-form { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:12px; }
.review-form input[type=text] { min-width:280px; flex:1; padding:9px 11px; border:1px solid var(--border); border-radius:9px; }
</style>

<div class="lesson-page">
    <div class="lesson-hero">
        <div>
            <div class="lesson-breadcrumb">
                <a href="../books/index.php?book_id=<?= (int)$lesson['book_id'] ?>&unit_id=<?= (int)$lesson['unit_id'] ?>">
                    <?= htmlspecialchars($lesson['book_name']) ?>
                </a>
                <span>›</span>
                                <span><?= htmlspecialchars($lesson['unit_number']) ?></span>
                <span>›</span>
                <strong><?= htmlspecialchars($lesson['lesson_title']) ?></strong>
            </div>

            <span class="section-kicker">Lesson</span>
            <h2 class="lesson-title"><?= htmlspecialchars($lesson['lesson_title']) ?></h2>

            <?php if (!empty($lesson['lesson_description'])): ?>
                <p class="lesson-description">
                    <?= htmlspecialchars($lesson['lesson_description']) ?>
                </p>
            <?php endif; ?>
        </div>

        <a
            href="../books/index.php?book_id=<?= (int)$lesson['book_id'] ?>&unit_id=<?= (int)$lesson['unit_id'] ?>"
            class="button button-secondary"
        >
            ← Back to Unit
        </a>
    </div>

    <?php
        $reviewLabels = [
            'draft' => 'Draft',
            'pending_review' => 'Pending Review',
            'needs_revision' => 'Needs Revision',
            'published' => 'Published',
        ];
        $reviewMessage = (string)($_SESSION['lesson_review_message'] ?? '');
        unset($_SESSION['lesson_review_message']);
    ?>
    <div class="review-box">
        <div class="review-row">
            <strong>Content Review V3.2</strong>
            <span class="review-pill"><?= htmlspecialchars($reviewLabels[$reviewStatus] ?? $reviewStatus) ?></span>
            <?php if ($isLeadReviewer && !$isAdmin): ?><small>Lead reviewer for this Book/Level</small><?php endif; ?>
        </div>

        <?php if ($reviewMessage !== ''): ?>
            <div class="review-note"><strong><?= htmlspecialchars($reviewMessage) ?></strong></div>
        <?php endif; ?>

        <?php if (!empty($workflow['review_note'])): ?>
            <div class="review-note">Review note: <?= nl2br(htmlspecialchars((string)$workflow['review_note'])) ?></div>
        <?php endif; ?>

        <?php if ($isLessonAuthor && in_array($reviewStatus, ['draft', 'needs_revision'], true)): ?>
            <form method="post" class="review-form">
                <input type="hidden" name="action" value="review_workflow">
                <?php if ($isAdmin || $isLeadAuthor): ?>
                    <input type="hidden" name="workflow_action" value="publish_direct">
                    <button class="button button-primary" type="submit">Publish</button>
                <?php else: ?>
                    <input type="hidden" name="workflow_action" value="submit">
                    <button class="button button-primary" type="submit">Submit for Review</button>
                <?php endif; ?>
            </form>
        <?php endif; ?>

        <?php if ($canReviewLesson && $reviewStatus === 'pending_review'): ?>
            <form method="post" class="review-form">
                <input type="hidden" name="action" value="review_workflow">
                <input type="text" name="review_note" placeholder="Review note (required when returning for revision)">
                <button class="button button-primary" type="submit" name="workflow_action" value="approve">Approve & Publish</button>
                <button class="button button-secondary" type="submit" name="workflow_action" value="needs_revision">Needs Revision</button>
            </form>
        <?php endif; ?>
    </div>

    <div class="lesson-toolbar">
        <div>
            <strong><?= count($activities) ?> activit<?= count($activities) === 1 ? 'y' : 'ies' ?></strong>
            <div style="color:var(--muted);font-size:12px;margin-top:3px;">
                Add activities, then choose words from Word Library.
            </div>
        </div>

        <?php if ($canEditLessonContent): ?>
        <button type="button" class="button button-primary" id="btnAddActivity">
            + Add Activity
        </button>
        <?php endif; ?>
    </div>

    <?php if (empty($activities)): ?>
        <div class="lesson-empty">
            <div class="lesson-empty-icon">🎮</div>
            <h3>No activities yet</h3>
            <p>This Lesson is ready. Add the first activity for students to practise.</p>
            <?php if ($canEditLessonContent): ?>
            <button type="button" class="button button-primary" id="btnCreateFirstActivity">
                + Add First Activity
            </button>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="lesson-grid">
            <?php foreach ($activities as $activityIndex => $activity): ?>
                <?php $isActivityDisabled = strtolower((string)($activity['activity_status'] ?? 'active')) !== 'active'; ?>
                <div class="lesson-activity-row<?= $isActivityDisabled ? ' is-disabled' : '' ?>">
                    <div class="lesson-activity-main">
                        <div class="lesson-activity-icon">
                            <?= activityIcon((string)$activity['activity_type']) ?>
                        </div>

                        <div class="lesson-activity-info">
                            <strong><?= htmlspecialchars($activity['activity_title']) ?></strong>

                            <?php if (!empty($activity['activity_description'])): ?>
                                <span><?= htmlspecialchars($activity['activity_description']) ?></span>
                            <?php endif; ?>

                            <span><?= htmlspecialchars(ucwords(str_replace('_', ' ', (string)$activity['activity_type']))) ?></span>
                            <?php if ($isActivityDisabled): ?>
                                <span class="lesson-activity-status">Disabled</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="lesson-activity-actions">
                        <?php if ($canManageLesson && isset($activityColumns['sort_order'])): ?>
                            <div class="lesson-move-controls" aria-label="Reorder Activity">
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="action" value="move_activity">
                                    <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                                    <input type="hidden" name="lesson_id" value="<?= (int)$lessonId ?>">
                                    <input type="hidden" name="direction" value="up">
                                    <button
                                        type="submit"
                                        class="button button-sm button-secondary lesson-move-button"
                                        title="Move up"
                                        aria-label="Move up"
                                        <?= $activityIndex === 0 ? 'disabled' : '' ?>
                                    >↑</button>
                                </form>

                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="action" value="move_activity">
                                    <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                                    <input type="hidden" name="lesson_id" value="<?= (int)$lessonId ?>">
                                    <input type="hidden" name="direction" value="down">
                                    <button
                                        type="submit"
                                        class="button button-sm button-secondary lesson-move-button"
                                        title="Move down"
                                        aria-label="Move down"
                                        <?= $activityIndex === count($activities) - 1 ? 'disabled' : '' ?>
                                    >↓</button>
                                </form>
                            </div>
                        <?php endif; ?>

                        <a
                            href="../../student/student-runtime/index.php?activity_id=<?= (int)$activity['id'] ?>&amp;preview=1"
                            class="button button-sm button-secondary"
                        >
                            Open
                        </a>

                        <?php if ($canEditLessonContent): ?>
                        <a
                            href="../activity-settings/index.php?activity_id=<?= (int)$activity['id'] ?>"
                            class="button button-sm button-secondary"
                        >
                            ⚙ Settings
                        </a>

                        <a
                            href="activity.php?id=<?= (int)$activity['id'] ?>"
                            class="button button-sm button-secondary"
                        >
                            Edit
                        </a>

                        <?php if (isset($activityColumns['status'])): ?>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="action" value="toggle_activity_status">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <input type="hidden" name="lesson_id" value="<?= (int)$lessonId ?>">
                            <input
                                type="hidden"
                                name="toggle_to"
                                value="<?= $isActivityDisabled ? 'active' : 'inactive' ?>"
                            >

                            <button
                                type="submit"
                                class="button button-sm button-secondary"
                            >
                                <?= $isActivityDisabled ? 'Enable' : 'Disable' ?>
                            </button>
                        </form>
                        <?php endif; ?>

                        <form
                            method="post"
                            action="../lesson-activities/delete.php"
                            onsubmit="return confirm('Delete this Activity? This action cannot be undone.');"
                            style="display:inline;"
                        >
                            <input type="hidden" name="id" value="<?= (int)$activity['id'] ?>">
                            <input type="hidden" name="lesson_id" value="<?= (int)$lessonId ?>">

                            <button
                                type="submit"
                                class="button button-sm button-secondary"
                                style="color:var(--danger);"
                            >
                                Delete
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php if ($canEditLessonContent): ?>
<div class="wl-modal-overlay" id="activityModalOverlay">
    <div class="wl-modal" style="max-width:680px;">
        <div class="wl-modal-header">
            <h3>Add Activity</h3>
            <button type="button" class="wl-modal-close" id="activityModalClose">&times;</button>
        </div>

        <div class="form-group">
            <label class="form-label">Choose activity type</label>

            <div class="activity-picker">
                <?php foreach ($activityOptions as $option): ?>
                    <label class="activity-choice">
                        <input
                            type="radio"
                            name="activity_type_choice"
                            value="<?= htmlspecialchars($option['type']) ?>"
                        >

                        <span class="activity-choice-icon"><?= $option['icon'] ?></span>

                        <span class="activity-choice-text">
                            <strong><?= htmlspecialchars($option['label']) ?></strong>
                            <small><?= htmlspecialchars($option['desc']) ?></small>
                        </span>

                        <span class="activity-choice-example" aria-hidden="true">
                            <strong>Ví dụ</strong>
                            <?= htmlspecialchars($option['example']) ?>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="button-group" style="justify-content:flex-end;margin-top:20px;">
            <button type="button" class="button button-secondary" id="activityModalCancel">
                Cancel
            </button>

            <button type="button" class="button button-primary" id="activityContinueBtn">
                Continue
            </button>
        </div>
    </div>
</div>

<script>
(function () {
    'use strict';

    const overlay = document.getElementById('activityModalOverlay');
    const openButtons = [
        document.getElementById('btnAddActivity'),
        document.getElementById('btnCreateFirstActivity')
    ];
    const closeButton = document.getElementById('activityModalClose');
    const cancelButton = document.getElementById('activityModalCancel');
    const continueButton = document.getElementById('activityContinueBtn');

    function openModal() {
        overlay?.classList.add('is-open');
    }

    function closeModal() {
        overlay?.classList.remove('is-open');
    }

    openButtons.forEach(function (button) {
        button?.addEventListener('click', openModal);
    });

    closeButton?.addEventListener('click', closeModal);
    cancelButton?.addEventListener('click', closeModal);

    overlay?.addEventListener('click', function (event) {
        if (event.target === overlay) {
            closeModal();
        }
    });

    continueButton?.addEventListener('click', function () {
        const selected = document.querySelector(
            'input[name="activity_type_choice"]:checked'
        );

        if (!selected) {
            alert('Please choose an Activity type.');
            return;
        }

        window.location.href =
            'activity.php?lesson_id=<?= (int)$lessonId ?>&type=' +
            encodeURIComponent(selected.value);
    });
})();
</script>
<?php endif; ?>

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