<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/lesson_progress_engine.php';

$pdo = getDbConnection();
$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));
$isPreview = (int)($_GET['preview'] ?? 0) === 1;

if ($lessonId <= 0) {
    http_response_code(400);
    exit('Thiếu lesson_id.');
}

if ($isPreview) {
    $teacherLoggedIn = !empty($_SESSION['user_id'])
        && in_array((string)($_SESSION['user_role'] ?? ''), ['teacher', 'admin'], true);

    if (!$teacherLoggedIn) {
        header('Location: ../teacher/login.php');
        exit;
    }
} elseif (empty($_SESSION['student_id'])) {
    $_SESSION['student_return_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');
    header('Location: student-login.php');
    exit;
}

$stmt = $pdo->prepare(
    "SELECT
        le.id AS lesson_id,
        le.lesson_number,
        le.title AS lesson_title,
        le.sort_order AS lesson_sort_order,
        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,
        u.sort_order AS unit_sort_order,
        lv.id AS level_id,
        lv.slug AS level_slug,
        b.slug AS book_slug
     FROM lessons le
     INNER JOIN units u ON u.id = le.unit_id
     INNER JOIN levels lv ON lv.id = u.level_id
     INNER JOIN books b ON b.id = lv.book_id
     WHERE le.id = ?
     LIMIT 1"
);
$stmt->execute([$lessonId]);
$lesson = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$lesson) {
    http_response_code(404);
    exit('Không tìm thấy Lesson.');
}

/*
 * Chỉ hiển thị "Hoàn thành bài học!" khi nguồn tiến độ dùng chung
 * xác nhận Lesson thực sự đã hoàn thành.
 *
 * Preview của giáo viên không ghi/đồng bộ progress.
 */
$lessonProgress = null;

if (!$isPreview) {
    $studentId = (int)($_SESSION['student_id'] ?? 0);

    $lessonProgress = englishSpeakSyncLessonProgress(
        $pdo,
        $studentId,
        $lessonId
    );

    if (empty($lessonProgress['lesson_completed'])) {
        $returnUrl = 'student-activities.php?' . http_build_query([
            'book' => (string)$lesson['book_slug'],
            'level' => (string)$lesson['level_slug'],
            'level_id' => (int)$lesson['level_id'],
            'unit_id' => (int)$lesson['unit_id'],
            'lesson_id' => $lessonId,
            'lesson' => (string)$lesson['lesson_number'],
        ]);

        header('Location: ' . $returnUrl);
        exit;
    }
}

$unitCompleted = false;
$nextLesson = null;
$nextLessonUrl = '';
$nextUnit = null;
$nextUnitUrl = '';

if (!$isPreview && !empty($studentId)) {
    /*
     * Nếu còn Lesson active kế tiếp trong cùng Unit,
     * nút Next sẽ đi thẳng sang Lesson đó.
     */
    $nextLessonStmt = $pdo->prepare(
        "SELECT id, lesson_number, title, sort_order
         FROM lessons
         WHERE unit_id = ?
           AND status = 'active'
           AND (
                sort_order > ?
                OR (sort_order = ? AND id > ?)
           )
         ORDER BY sort_order ASC, id ASC
         LIMIT 1"
    );
    $nextLessonStmt->execute([
        (int)$lesson['unit_id'],
        (int)($lesson['lesson_sort_order'] ?? 0),
        (int)($lesson['lesson_sort_order'] ?? 0),
        $lessonId,
    ]);
    $nextLesson = $nextLessonStmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if ($nextLesson) {
        /*
         * IMPORTANT:
         * Không đi thẳng sang Lesson kế tiếp từ màn hình hoàn thành.
         * Quyền mở Lesson (scheduled_date / sequential_daily) được xác định
         * tại student-lessons.php. Vì vậy Next quay về danh sách Lesson để
         * tránh bypass Lesson đang khóa.
         */
        $nextLessonUrl = 'student-lessons.php?' . http_build_query([
            'book' => (string)$lesson['book_slug'],
            'level' => (string)$lesson['level_slug'],
            'level_id' => (int)$lesson['level_id'],
            'unit_id' => (int)$lesson['unit_id'],
        ]);
    }

    /*
     * Unit chỉ hoàn thành khi TẤT CẢ Lesson active trong Unit
     * đã có progress lesson = completed.
     */
    $unitProgressStmt = $pdo->prepare(
        "SELECT
            COUNT(*) AS total_lessons,
            SUM(CASE WHEN scp.status = 'completed' THEN 1 ELSE 0 END) AS completed_lessons
         FROM lessons le
         LEFT JOIN student_content_progress scp
           ON scp.student_id = ?
          AND scp.content_type = 'lesson'
          AND scp.content_id = le.id
         WHERE le.unit_id = ?
           AND le.status = 'active'"
    );
    $unitProgressStmt->execute([
        $studentId,
        (int)$lesson['unit_id'],
    ]);
    $unitProgressRow = $unitProgressStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $unitTotalLessons = (int)($unitProgressRow['total_lessons'] ?? 0);
    $unitCompletedLessons = (int)($unitProgressRow['completed_lessons'] ?? 0);
    $unitCompleted = $unitTotalLessons > 0 && $unitCompletedLessons >= $unitTotalLessons;

    if ($unitCompleted) {
        /*
         * Tìm Unit active kế tiếp trong cùng Level.
         * Không cho Next nếu đây là Unit cuối của Level.
         */
        $nextUnitStmt = $pdo->prepare(
            "SELECT id, unit_number, title, sort_order
             FROM units
             WHERE level_id = ?
               AND status = 'active'
               AND (
                    sort_order > ?
                    OR (sort_order = ? AND id > ?)
               )
             ORDER BY sort_order ASC, id ASC
             LIMIT 1"
        );
        $nextUnitStmt->execute([
            (int)$lesson['level_id'],
            (int)($lesson['unit_sort_order'] ?? 0),
            (int)($lesson['unit_sort_order'] ?? 0),
            (int)$lesson['unit_id'],
        ]);
        $nextUnit = $nextUnitStmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($nextUnit) {
            $nextUnitUrl = 'student-lessons.php?' . http_build_query([
                'book' => (string)$lesson['book_slug'],
                'level' => (string)$lesson['level_slug'],
                'level_id' => (int)$lesson['level_id'],
                'unit_id' => (int)$nextUnit['id'],
            ]);
        }
    }
}

$rawLessonNumber = trim((string)($lesson['lesson_number'] ?? ''));
$displayLessonNumber = preg_match('/(\d+)/', $rawLessonNumber, $lessonMatch)
    ? (int)$lessonMatch[1]
    : $rawLessonNumber;

$rawUnitNumber = trim((string)($lesson['unit_number'] ?? ''));
$displayUnitNumber = preg_match('/(\d+)/', $rawUnitNumber, $unitMatch)
    ? (int)$unitMatch[1]
    : $rawUnitNumber;

$lessonTitle = trim((string)($lesson['lesson_title'] ?? ''));
$lessonNumberLabel = 'Lesson ' . (string)$displayLessonNumber;
$normalizedLessonTitle = mb_strtolower(preg_replace('/\s+/', ' ', $lessonTitle), 'UTF-8');
$normalizedLessonNumber = mb_strtolower(preg_replace('/\s+/', ' ', $lessonNumberLabel), 'UTF-8');

$lessonDisplayTitle = $lessonNumberLabel;
if ($lessonTitle !== '' && $normalizedLessonTitle !== $normalizedLessonNumber) {
    $lessonDisplayTitle .= ' · ' . $lessonTitle;
}

$reviewQuery = ['lesson_id' => $lessonId];
if ($isPreview) {
    $reviewQuery['preview'] = 1;
}
$reviewUrl = 'student-runtime/index.php?' . http_build_query($reviewQuery);

$lessonListUrl = 'student-lessons.php?' . http_build_query([
    'book' => (string)$lesson['book_slug'],
    'level' => (string)$lesson['level_slug'],
    'level_id' => (int)$lesson['level_id'],
    'unit_id' => (int)$lesson['unit_id'],
]);

$activitySql = "SELECT id, title, activity_type, passing_score
                FROM activities
                WHERE lesson_id = ?";
if (!$isPreview) {
    $activitySql .= " AND status = 'active'";
}
$activitySql .= " ORDER BY sort_order ASC, id ASC";

$activityStmt = $pdo->prepare($activitySql);
$activityStmt->execute([$lessonId]);
$activities = $activityStmt->fetchAll(PDO::FETCH_ASSOC);

// Đọc Best Score nếu học sinh đang học thật. Preview không hiển thị điểm giả.
$activityScores = [];
if (!$isPreview && !empty($_SESSION['student_id'])) {
    try {
        $progressTableStmt = $pdo->prepare(
            "SELECT COUNT(*)
             FROM information_schema.TABLES
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'student_content_progress'"
        );
        $progressTableStmt->execute();

        if ((int)$progressTableStmt->fetchColumn() > 0) {
            $progressStmt = $pdo->prepare(
                "SELECT content_id, best_score
                 FROM student_content_progress
                 WHERE student_id = ?
                   AND content_type = 'activity'
                   AND content_id IN (" . implode(',', array_fill(0, max(1, count($activities)), '?')) . ")"
            );

            $activityIds = array_map(
                static fn(array $activity): int => (int)$activity['id'],
                $activities
            );

            if ($activityIds !== []) {
                $progressStmt->execute(array_merge([(int)$_SESSION['student_id']], $activityIds));
                foreach ($progressStmt->fetchAll(PDO::FETCH_ASSOC) as $progressRow) {
                    $activityScores[(int)$progressRow['content_id']] = (float)$progressRow['best_score'];
                }
            }
        }
    } catch (Throwable $exception) {
        // Giao diện vẫn hoạt động nếu bảng Progress chưa hoàn chỉnh.
        $activityScores = [];
    }
}

function lessonActivityLabel(array $activity): string
{
    $title = trim((string)($activity['title'] ?? ''));
    if ($title !== '') {
        return $title;
    }

    $type = strtolower(trim((string)($activity['activity_type'] ?? 'activity')));
    $labels = [
        'flashcards' => 'Flashcards',
        'listen_repeat' => 'Listen & Repeat',
        'speaking' => 'Speaking',
        'sentence_listen_repeat' => 'Speaking Sentences',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'quiz' => 'Quiz',
    ];

    return $labels[$type] ?? ucwords(str_replace('_', ' ', $type));
}

function lessonActivityIcon(array $activity): string
{
    $type = strtolower(trim((string)($activity['activity_type'] ?? '')));
    $icons = [
        'flashcard' => '🗂️',
        'flashcards' => '🗂️',
        'listen_repeat' => '🎧',
        'listen_and_repeat' => '🎧',
        'speaking' => '🎤',
        'sentence_speaking' => '🗣️',
        'speaking_sentences' => '🗣️',
        'sentence_listen_repeat' => '🗣️',
        'memory' => '🧠',
        'matching' => '🧩',
        'quiz' => '📝',
    ];

    return $icons[$type] ?? '🎯';
}

function lessonScoreClass(?float $score, int $passingScore): string
{
    if ($score === null) {
        return 'score-empty';
    }

    if ($score < $passingScore) {
        return 'score-needs-practice';
    }

    if ($score >= 100) {
        return 'score-excellent';
    }

    if ($score >= 90) {
        return 'score-great';
    }

    return 'score-good';
}
?>
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Lesson Completed | EnglishSpeak</title>
<style>
:root{
  --blue:#198fe3;--blue-dark:#0868c7;--page:#f4f8fc;--text:#15314b;
  --muted:#718399;--line:#dfe8f0;--green:#26a65b;--width:520px;
  --shadow:0 12px 32px rgba(31,71,108,.12)
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%;background:var(--page);color:var(--text);font-family:"Segoe UI",Tahoma,Arial,sans-serif}
body{display:flex;justify-content:center}
a{font:inherit;-webkit-tap-highlight-color:transparent}
.app{width:min(100%,var(--width));min-height:100dvh;padding:20px 14px 28px;background:#fff;box-shadow:0 0 28px rgba(30,79,115,.08)}
.card{width:100%;padding:30px 20px;border:1px solid var(--line);border-radius:28px;background:linear-gradient(180deg,#fff,#f9fcff);box-shadow:var(--shadow);text-align:center}
.icon{width:88px;height:88px;display:grid;place-items:center;margin:0 auto 16px;border-radius:50%;background:linear-gradient(135deg,#fff6bf,#ffe06e);font-size:48px}
h1{margin:0;color:#123e62;font-size:33px;line-height:1.15}
.lesson-name{margin:12px 0 0;color:var(--blue-dark);font-size:19px;font-weight:850}
.unit-name{margin:6px 0 0;color:var(--muted);font-size:14px}
.message{margin:20px 0 0;padding:15px;border:1px solid #bde7c8;border-radius:18px;background:#eefbf1;color:#16823b;font-weight:800;line-height:1.45}
.section-title{margin:26px 0 4px;text-align:left;color:#123e62;font-size:18px}
.practice-list{overflow:hidden;border:1px solid var(--line);border-radius:18px;background:#fff;text-align:left}
.practice-item{display:grid;text-decoration:none;color:inherit;cursor:pointer;grid-template-columns:minmax(0,1fr) 58px auto;align-items:center;gap:12px;min-height:66px;padding:10px 12px;border-bottom:1px solid #e9eff4}
.practice-item:last-child{border-bottom:0}
.practice-item:hover{background:#f7fbff}
.practice-item:focus-visible{outline:3px solid rgba(25,143,227,.25);outline-offset:-3px}
.practice-name{min-width:0;display:flex;align-items:center;gap:9px;font-weight:800;line-height:1.3}
.practice-icon{flex:0 0 auto;font-size:20px}
.practice-score{text-align:center;font-weight:900}
.practice-score.score-empty{color:var(--muted)}
.practice-score.score-excellent{color:#16823b}
.practice-score.score-great{color:var(--blue-dark)}
.practice-score.score-good{color:#b36b00}
.practice-score.score-needs-practice{color:#c0392b}
.actions{display:grid;gap:11px;margin-top:22px}
.action{min-height:54px;display:grid;place-items:center;border:1px solid var(--blue);border-radius:16px;background:#fff;color:var(--blue-dark);text-decoration:none;font-weight:850}
.action.primary{background:linear-gradient(135deg,#237fe1,#159ddd);color:#fff}
.preview{margin-top:16px;padding-top:14px;border-top:1px solid #edf2f6;color:var(--muted);font-size:12px}
.empty{padding:16px;border:1px dashed var(--line);border-radius:16px;color:var(--muted);text-align:center}
@media(max-width:390px){
  .app{padding:14px 10px 22px}
  .card{padding:26px 16px}
  h1{font-size:29px}
  .practice-item{gap:8px;padding:9px 10px}
}
</style>
</head>
<body>
<main class="app">
  <section class="card">
    <div class="icon" aria-hidden="true">🏆</div>
    <h1>Lesson Completed!</h1>
    
    <div class="unit-name">Unit <?= htmlspecialchars((string)$displayUnitNumber, ENT_QUOTES, 'UTF-8') ?> • Lesson <?= htmlspecialchars((string)$displayLessonNumber, ENT_QUOTES, 'UTF-8') ?></div>

    <div class="message">Practice anytime you like!</div>

    <h2 class="section-title">Activities</h2>
    <?php if ($activities === []): ?>
      <div class="empty">This lesson has no activities to review yet.</div>
    <?php else: ?>
      <div class="practice-list">
        <?php foreach ($activities as $activity): ?>
          <?php
          $practiceQuery = ['activity_id' => (int)$activity['id'], 'runtime_mode' => 'review'];
          if ($isPreview) {
              $practiceQuery['preview'] = 1;
          }
          $practiceUrl = 'student-runtime/index.php?' . http_build_query($practiceQuery);
          ?>
          <?php
          $activityScore = $activityScores[(int)$activity['id']] ?? null;
          $scoreLabel = $activityScore === null
              ? '—'
              : rtrim(rtrim(number_format($activityScore, 1, '.', ''), '0'), '.') . '%';

          $passingScore = max(0, min(100, (int)($activity['passing_score'] ?? 70)));
          $scoreClass = lessonScoreClass($activityScore, $passingScore);

          ?>
<a class="practice-item" href="<?= htmlspecialchars($practiceUrl, ENT_QUOTES, 'UTF-8') ?>">
            <span class="practice-name"><span class="practice-icon" aria-hidden="true"><?= htmlspecialchars(lessonActivityIcon($activity), ENT_QUOTES, 'UTF-8') ?></span><?= htmlspecialchars(lessonActivityLabel($activity), ENT_QUOTES, 'UTF-8') ?></span>
            <span class="practice-score <?= htmlspecialchars($scoreClass, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($scoreLabel, ENT_QUOTES, 'UTF-8') ?></span>
          </a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <div class="actions">
      <?php if ($nextLesson && $nextLessonUrl !== ''): ?>
        <a class="action primary" href="<?= htmlspecialchars($nextLessonUrl, ENT_QUOTES, 'UTF-8') ?>">➡ Next</a>
        <a class="action" href="<?= htmlspecialchars($reviewUrl, ENT_QUOTES, 'UTF-8') ?>">↻ Again</a>
      <?php elseif ($unitCompleted && $nextUnit && $nextUnitUrl !== ''): ?>
        <a class="action primary" href="<?= htmlspecialchars($nextUnitUrl, ENT_QUOTES, 'UTF-8') ?>">➡ Next</a>
        <a class="action" href="<?= htmlspecialchars($reviewUrl, ENT_QUOTES, 'UTF-8') ?>">↻ Again</a>
      <?php else: ?>
        <a class="action primary" href="<?= htmlspecialchars($reviewUrl, ENT_QUOTES, 'UTF-8') ?>">↻ Again</a>
      <?php endif; ?>
      <a class="action" href="<?= htmlspecialchars($lessonListUrl, ENT_QUOTES, 'UTF-8') ?>">← Back</a>
    </div>

    <?php if ($isPreview): ?>
      <div class="preview">Chế độ xem thử — chưa lưu Progress và XP.</div>
    <?php endif; ?>
  </section>
</main>
</body>
</html>