<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Lesson Activities
 * File: teacher/lesson-activities/index.php
 *
 * Activity Builder
 * Book -> Unit -> Lesson -> Activity -> Flashcard Set
 */

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

$pdo = getDbConnection();

$pageTitle = 'Lesson Activities';
$pageSubtitle = 'Manage Activity order, Game Template and Flashcard Set';
$activeTeacherNav = 'content';

$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));
$keyword = trim((string)($_GET['keyword'] ?? ''));
$status = (string)($_GET['status'] ?? '');

if (!in_array($status, ['', 'active', 'inactive'], true)) {
    $status = '';
}

function laiTableExists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        "SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?"
    );
    $stmt->execute([$table]);

    return (int)$stmt->fetchColumn() > 0;
}

function laiColumns(PDO $pdo, string $table): array
{
    if (!laiTableExists($pdo, $table)) {
        return [];
    }

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

function laiFirstColumn(array $columns, array $candidates): ?string
{
    foreach ($candidates as $candidate) {
        if (isset($columns[$candidate])) {
            return $candidate;
        }
    }

    return null;
}


function laiInsertDynamic(PDO $pdo, string $table, array $data): int
{
    $columns = laiColumns($pdo, $table);
    $fields = [];
    $values = [];
    $params = [];

    foreach ($data as $field => $value) {
        if (!isset($columns[$field])) {
            continue;
        }

        $fields[] = "`{$field}`";

        if ($value === '__NOW__') {
            $values[] = 'NOW()';
        } else {
            $values[] = '?';
            $params[] = $value;
        }
    }

    if ($fields === []) {
        throw new RuntimeException("Table {$table} has no supported columns.");
    }

    $sql = "INSERT INTO `{$table}` (" . implode(', ', $fields) . ")
            VALUES (" . implode(', ', $values) . ")";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    return (int)$pdo->lastInsertId();
}

function laiTypeLabel(string $type): string
{
    return match ($type) {
        'flashcards' => 'Flashcards',
        'listen_repeat', 'pronunciation' => 'Listen & Repeat',
        'speaking' => 'Speaking',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'quiz' => 'Quiz',
        'typing' => 'Typing',
        'word_search' => 'Word Search',
        'sentence_builder' => 'Sentence Builder',
        'worksheet' => 'Worksheet',
        'vocabulary' => 'Word List',
        default => ucwords(str_replace(['_', '-'], ' ', $type ?: 'Activity')),
    };
}

function laiTypeIcon(string $type): string
{
    return match ($type) {
        'flashcards' => '🃏',
        'listen_repeat', 'pronunciation' => '🔊',
        'speaking' => '🎤',
        'memory' => '🧠',
        'matching' => '🧩',
        'quiz' => '🎯',
        'typing' => '⌨️',
        'word_search' => '🔎',
        'sentence_builder' => '🧱',
        'worksheet' => '📄',
        'vocabulary' => '🔤',
        default => '🎮',
    };
}


function laiGameTemplates(): array
{
    return [
        'flashcards' => [
            'label' => 'Flashcards',
            'icon' => '🃏',
            'description' => 'Look, listen and flip vocabulary cards.',
            'uses_word_set' => true,
        ],
        'listen_repeat' => [
            'label' => 'Listen & Repeat',
            'icon' => '🔊',
            'description' => 'Listen, record and practise pronunciation.',
            'uses_word_set' => true,
        ],
        'memory' => [
            'label' => 'Memory',
            'icon' => '🧠',
            'description' => 'Match picture and word cards from memory.',
            'uses_word_set' => true,
        ],
        'matching' => [
            'label' => 'Matching',
            'icon' => '🧩',
            'description' => 'Match words with the correct pictures.',
            'uses_word_set' => true,
        ],
        'quiz' => [
            'label' => 'Quiz',
            'icon' => '🎯',
            'description' => 'Answer questions and check understanding.',
            'uses_word_set' => false,
        ],
        'speaking' => [
            'label' => 'Speaking',
            'icon' => '🎤',
            'description' => 'Practise speaking with guided prompts.',
            'uses_word_set' => true,
        ],
        'sentence_builder' => [
            'label' => 'Sentence Builder',
            'icon' => '🧱',
            'description' => 'Arrange words to build correct sentences.',
            'uses_word_set' => false,
        ],
        'worksheet' => [
            'label' => 'Worksheet',
            'icon' => '📄',
            'description' => 'Complete a teacher-prepared worksheet.',
            'uses_word_set' => false,
        ],
    ];
}

$gameTemplates = laiGameTemplates();

$activityColumns = laiColumns($pdo, 'activities');
$setColumns = laiColumns($pdo, 'flashcard_sets');


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $postLessonId = max(0, (int)($_POST['lesson_id'] ?? 0));
    $activityId = max(0, (int)($_POST['activity_id'] ?? 0));

    $returnUrl = 'index.php' . ($postLessonId > 0 ? '?lesson_id=' . $postLessonId : '');

    try {
        if ($action === 'create_activity') {
            $title = trim((string)($_POST['title'] ?? ''));
            $type = trim((string)($_POST['activity_type'] ?? 'flashcards'));
            $description = trim((string)($_POST['description'] ?? ''));
            $flashcardSetId = max(0, (int)($_POST['flashcard_set_id'] ?? 0));
            $xpReward = max(0, (int)($_POST['xp_reward'] ?? 0));
            $passingScore = min(100, max(0, (int)($_POST['passing_score'] ?? 0)));

            if ($postLessonId <= 0) {
                throw new RuntimeException('Lesson not found.');
            }

            if (!isset($gameTemplates[$type])) {
                $type = 'flashcards';
            }

            if ($title === '') {
                $title = (string)$gameTemplates[$type]['label'];
            }

            if ($description === '') {
                $description = (string)$gameTemplates[$type]['description'];
            }

            $sortStmt = $pdo->prepare(
                'SELECT COALESCE(MAX(sort_order), 0) + 1
                 FROM activities
                 WHERE lesson_id = ?'
            );
            $sortStmt->execute([$postLessonId]);

            laiInsertDynamic($pdo, 'activities', [
                'lesson_id' => $postLessonId,
                'title' => $title,
                'name' => $title,
                'activity_type' => $type,
                'type' => $type,
                'instructions' => $description,
                'description' => $description,
                'flashcard_set_id' => $flashcardSetId > 0 ? $flashcardSetId : null,
                'xp_reward' => $xpReward,
                'passing_score' => $passingScore,
                'sort_order' => (int)$sortStmt->fetchColumn(),
                'status' => 'active',
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            $_SESSION['activities_message'] = 'Activity created successfully.';
            $_SESSION['activities_message_type'] = 'success';
        }

        if ($action === 'update_activity') {
            $title = trim((string)($_POST['title'] ?? ''));
            $type = trim((string)($_POST['activity_type'] ?? 'flashcards'));
            $description = trim((string)($_POST['description'] ?? ''));
            $flashcardSetId = max(0, (int)($_POST['flashcard_set_id'] ?? 0));
            $xpReward = max(0, (int)($_POST['xp_reward'] ?? 0));
            $passingScore = min(100, max(0, (int)($_POST['passing_score'] ?? 0)));

            if ($activityId <= 0 || $postLessonId <= 0) {
                throw new RuntimeException('Please enter valid Activity information.');
            }

            if (!isset($gameTemplates[$type])) {
                $type = 'flashcards';
            }

            if ($title === '') {
                $title = (string)$gameTemplates[$type]['label'];
            }

            if ($description === '') {
                $description = (string)$gameTemplates[$type]['description'];
            }

            $sets = [];
            $params = [];

            $titleColumn = laiFirstColumn($activityColumns, ['title', 'name']);
            if ($titleColumn) {
                $sets[] = "`{$titleColumn}` = ?";
                $params[] = $title;
            }

            $typeColumn = laiFirstColumn($activityColumns, ['activity_type', 'type']);
            if ($typeColumn) {
                $sets[] = "`{$typeColumn}` = ?";
                $params[] = $type;
            }

            $descriptionColumn = laiFirstColumn($activityColumns, ['instructions', 'description']);
            if ($descriptionColumn) {
                $sets[] = "`{$descriptionColumn}` = ?";
                $params[] = $description;
            }

            if (isset($activityColumns['flashcard_set_id'])) {
                $sets[] = '`flashcard_set_id` = ?';
                $params[] = $flashcardSetId > 0 ? $flashcardSetId : null;
            }

            if (isset($activityColumns['xp_reward'])) {
                $sets[] = '`xp_reward` = ?';
                $params[] = $xpReward;
            }

            if (isset($activityColumns['passing_score'])) {
                $sets[] = '`passing_score` = ?';
                $params[] = $passingScore;
            }

            if (isset($activityColumns['updated_at'])) {
                $sets[] = '`updated_at` = NOW()';
            }

            if ($sets === []) {
                throw new RuntimeException('Activities table has no editable columns.');
            }

            $params[] = $activityId;
            $params[] = $postLessonId;

            $stmt = $pdo->prepare(
                'UPDATE activities SET ' . implode(', ', $sets) .
                ' WHERE id = ? AND lesson_id = ?'
            );
            $stmt->execute($params);

            $_SESSION['activities_message'] = 'Activity updated successfully.';
            $_SESSION['activities_message_type'] = 'success';
        }

        if ($action === 'duplicate_activity') {
            if ($activityId <= 0 || $postLessonId <= 0) {
                throw new RuntimeException('Activity not found.');
            }

            $stmt = $pdo->prepare(
                'SELECT * FROM activities WHERE id = ? AND lesson_id = ? LIMIT 1'
            );
            $stmt->execute([$activityId, $postLessonId]);
            $activity = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$activity) {
                throw new RuntimeException('Activity not found.');
            }

            $titleColumn = laiFirstColumn($activityColumns, ['title', 'name']);
            $typeColumn = laiFirstColumn($activityColumns, ['activity_type', 'type']);
            $descriptionColumn = laiFirstColumn($activityColumns, ['instructions', 'description']);

            $originalTitle = $titleColumn ? (string)($activity[$titleColumn] ?? 'Activity') : 'Activity';
            $originalType = $typeColumn ? (string)($activity[$typeColumn] ?? 'activity') : 'activity';
            $originalDescription = $descriptionColumn ? (string)($activity[$descriptionColumn] ?? '') : '';

            $sortStmt = $pdo->prepare(
                'SELECT COALESCE(MAX(sort_order), 0) + 1
                 FROM activities
                 WHERE lesson_id = ?'
            );
            $sortStmt->execute([$postLessonId]);

            laiInsertDynamic($pdo, 'activities', [
                'lesson_id' => $postLessonId,
                'title' => $originalTitle . ' Copy',
                'name' => $originalTitle . ' Copy',
                'activity_type' => $originalType,
                'type' => $originalType,
                'instructions' => $originalDescription,
                'description' => $originalDescription,
                'flashcard_set_id' => $activity['flashcard_set_id'] ?? null,
                'xp_reward' => (int)($activity['xp_reward'] ?? 0),
                'passing_score' => (int)($activity['passing_score'] ?? 0),
                'sort_order' => (int)$sortStmt->fetchColumn(),
                'status' => 'active',
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            $_SESSION['activities_message'] = 'Activity duplicated successfully.';
            $_SESSION['activities_message_type'] = 'success';
        }

        if ($action === 'move_activity') {
            $direction = (string)($_POST['direction'] ?? '');

            if ($activityId <= 0 || $postLessonId <= 0) {
                throw new RuntimeException('Activity not found.');
            }

            $pdo->beginTransaction();

            $listStmt = $pdo->prepare(
                'SELECT id
                 FROM activities
                 WHERE lesson_id = ?
                 ORDER BY sort_order, id
                 FOR UPDATE'
            );
            $listStmt->execute([$postLessonId]);

            $ids = array_map('intval', $listStmt->fetchAll(PDO::FETCH_COLUMN));
            $currentIndex = array_search($activityId, $ids, true);

            if ($currentIndex === false) {
                throw new RuntimeException('Activity not found.');
            }

            $targetIndex = $direction === 'up'
                ? $currentIndex - 1
                : $currentIndex + 1;

            if ($targetIndex >= 0 && $targetIndex < count($ids)) {
                [$ids[$currentIndex], $ids[$targetIndex]] =
                    [$ids[$targetIndex], $ids[$currentIndex]];
            }

            if (isset($activityColumns['sort_order'])) {
                $sql = 'UPDATE activities SET sort_order = ?';
                if (isset($activityColumns['updated_at'])) {
                    $sql .= ', updated_at = NOW()';
                }
                $sql .= ' WHERE id = ? AND lesson_id = ?';

                $updateStmt = $pdo->prepare($sql);

                foreach ($ids as $index => $id) {
                    $updateStmt->execute([$index + 1, $id, $postLessonId]);
                }
            }

            $pdo->commit();

            $_SESSION['activities_message'] = 'Activity order updated.';
            $_SESSION['activities_message_type'] = 'success';
        }

        if ($action === 'toggle_activity') {
            if ($activityId <= 0 || $postLessonId <= 0 || !isset($activityColumns['status'])) {
                throw new RuntimeException('Activity status cannot be changed.');
            }

            $stmt = $pdo->prepare(
                "UPDATE activities
                 SET status = CASE WHEN status = 'inactive' THEN 'active' ELSE 'inactive' END" .
                 (isset($activityColumns['updated_at']) ? ', updated_at = NOW()' : '') .
                 ' WHERE id = ? AND lesson_id = ?'
            );
            $stmt->execute([$activityId, $postLessonId]);

            $_SESSION['activities_message'] = 'Activity visibility updated.';
            $_SESSION['activities_message_type'] = 'success';
        }

        if ($action === 'delete_activity') {
            if ($activityId <= 0 || $postLessonId <= 0) {
                throw new RuntimeException('Activity not found.');
            }

            $stmt = $pdo->prepare(
                'DELETE FROM activities WHERE id = ? AND lesson_id = ?'
            );
            $stmt->execute([$activityId, $postLessonId]);

            $_SESSION['activities_message'] = 'Activity deleted successfully.';
            $_SESSION['activities_message_type'] = 'success';
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $_SESSION['activities_message'] = $e->getMessage() !== ''
            ? $e->getMessage()
            : 'The Activity action could not be completed.';
        $_SESSION['activities_message_type'] = 'error';
    }

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

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

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

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

$statusExpression = isset($activityColumns['status'])
    ? 'a.status'
    : "'active'";

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

$xpExpression = isset($activityColumns['xp_reward'])
    ? 'a.xp_reward'
    : '0';

$passingExpression = isset($activityColumns['passing_score'])
    ? 'a.passing_score'
    : '0';

$hasSetLink = isset($activityColumns['flashcard_set_id']) && $setColumns !== [];

$flashcardSetIdExpression = isset($activityColumns['flashcard_set_id'])
    ? 'a.flashcard_set_id'
    : '0';

$setLabelColumn = laiFirstColumn(
    $setColumns,
    ['title', 'name', 'set_name', 'label']
);

$setSelect = $hasSetLink && $setLabelColumn
    ? "fs.`{$setLabelColumn}` AS flashcard_set_name"
    : 'NULL AS flashcard_set_name';

$setJoin = $hasSetLink
    ? 'LEFT JOIN flashcard_sets fs ON fs.id = a.flashcard_set_id'
    : '';

$wordCountExpression = '0 AS word_count';
$wordCountJoin = '';

$relationTable = null;

foreach (['flashcard_set_words', 'flashcard_set_items', 'set_words'] as $candidate) {
    if (laiTableExists($pdo, $candidate)) {
        $relationTable = $candidate;
        break;
    }
}

if ($hasSetLink && $relationTable !== null) {
    $relationColumns = laiColumns($pdo, $relationTable);

    $relationSetFk = laiFirstColumn(
        $relationColumns,
        ['flashcard_set_id', 'set_id']
    );

    $relationWordFk = laiFirstColumn(
        $relationColumns,
        ['word_id', 'vocabulary_id']
    );

    if ($relationSetFk && $relationWordFk) {
        $wordCountJoin = "
            LEFT JOIN (
                SELECT
                    `{$relationSetFk}` AS set_id,
                    COUNT(DISTINCT `{$relationWordFk}`) AS word_count
                FROM `{$relationTable}`
                GROUP BY `{$relationSetFk}`
            ) swc ON swc.set_id = fs.id
        ";

        $wordCountExpression = 'COALESCE(swc.word_count, 0) AS word_count';
    }
}

$lesson = null;

if ($lessonId > 0) {
    $lessonStmt = $pdo->prepare(
        "SELECT
            l.id,
            l.lesson_number,
            l.title AS lesson_title,
            u.id AS unit_id,
            u.unit_number,
            u.title AS unit_title,
            lv.id AS level_id,
            lv.name AS level_name,
            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 levels lv ON lv.id = u.level_id
         INNER JOIN books b ON b.id = u.book_id
         WHERE l.id = ?
         LIMIT 1"
    );
    $lessonStmt->execute([$lessonId]);
    $lesson = $lessonStmt->fetch(PDO::FETCH_ASSOC);

    if (!$lesson) {
        $_SESSION['lessons_message'] = 'Lesson not found.';
        $_SESSION['lessons_message_type'] = 'error';
        header('Location: ../lessons/index.php');
        exit;
    }
}

$where = [];
$params = [];

if ($lessonId > 0) {
    $where[] = 'a.lesson_id = :lesson_id';
    $params[':lesson_id'] = $lessonId;
}

if ($keyword !== '') {
    $where[] = "(
        {$titleExpression} LIKE :keyword
        OR {$typeExpression} LIKE :keyword
        OR {$descriptionExpression} LIKE :keyword
        OR l.title LIKE :keyword
        OR u.title LIKE :keyword
        OR b.name LIKE :keyword
    )";
    $params[':keyword'] = '%' . $keyword . '%';
}

if ($status !== '' && isset($activityColumns['status'])) {
    $where[] = 'a.status = :status';
    $params[':status'] = $status;
}

$whereSql = $where !== [] ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT
        a.id,
        a.lesson_id,
        {$titleExpression} AS activity_title,
        {$typeExpression} AS activity_type,
        {$descriptionExpression} AS activity_description,
        {$statusExpression} AS activity_status,
        {$sortExpression} AS sort_order,
        {$xpExpression} AS xp_reward,
        {$passingExpression} AS passing_score,
        {$flashcardSetIdExpression} AS flashcard_set_id,
        {$setSelect},
        {$wordCountExpression},
        l.lesson_number,
        l.title AS lesson_title,
        u.unit_number,
        u.title AS unit_title,
        b.name AS book_name
    FROM activities a
    INNER JOIN lessons l ON l.id = a.lesson_id
    INNER JOIN units u ON u.id = l.unit_id
    INNER JOIN books b ON b.id = u.book_id
    {$setJoin}
    {$wordCountJoin}
    {$whereSql}
    ORDER BY
        b.sort_order ASC,
        u.sort_order ASC,
        l.sort_order ASC,
        {$sortExpression} ASC,
        a.id ASC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$activities = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalActivities = count($activities);
$activeActivities = 0;
$hiddenActivities = 0;

foreach ($activities as $activity) {
    if ((string)$activity['activity_status'] === 'inactive') {
        $hiddenActivities++;
    } else {
        $activeActivities++;
    }
}


$flashcardSets = [];

if ($setColumns !== [] && $setLabelColumn) {
    $setStatusWhere = isset($setColumns['status'])
        ? "WHERE status = 'active'"
        : '';

    $setOrder = isset($setColumns['sort_order'])
        ? 'ORDER BY sort_order, id'
        : "ORDER BY `{$setLabelColumn}`, id";

    $flashcardSets = $pdo->query(
        "SELECT id, `{$setLabelColumn}` AS set_label
         FROM flashcard_sets
         {$setStatusWhere}
         {$setOrder}"
    )->fetchAll(PDO::FETCH_ASSOC);
}

$message = (string)($_SESSION['activities_message'] ?? '');
$messageType = (string)($_SESSION['activities_message_type'] ?? 'success');

unset($_SESSION['activities_message'], $_SESSION['activities_message_type']);

ob_start();
?>

<style>
.lai-page{display:grid;gap:18px}
.lai-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}
.lai-head h2{margin:4px 0 0;font-size:28px}
.lai-kicker{display:block;color:#ea580c;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.lai-path{margin:7px 0 0;color:#64748b;line-height:1.55}
.lai-top-actions{display:flex;gap:9px;flex-wrap:wrap}
.lai-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
.lai-stat{padding:16px 18px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.lai-stat span{display:block;color:#64748b;font-size:12px;font-weight:750;text-transform:uppercase}
.lai-stat strong{display:block;margin-top:6px;color:#0f172a;font-size:25px}
.lai-toolbar{display:grid;grid-template-columns:minmax(220px,1fr) minmax(160px,210px) auto;gap:10px;padding:14px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.lai-input,.lai-select{width:100%;min-height:42px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.lai-list{display:grid;gap:12px}
.lai-card{display:grid;grid-template-columns:64px minmax(0,1fr) auto;align-items:center;gap:18px;padding:18px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.lai-card:hover{border-color:#fed7aa;box-shadow:0 8px 24px rgba(15,23,42,.05)}
.lai-order{display:grid;place-items:center;width:52px;height:52px;border-radius:15px;background:#fff7ed;color:#c2410c;font-size:18px;font-weight:850}
.lai-main{min-width:0}
.lai-title-line{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
.lai-main h3{margin:0;color:#0f172a;font-size:16px}
.lai-type{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;background:#eff6ff;color:#2563eb;font-size:12px;font-weight:800}
.lai-description{margin:7px 0 0;color:#64748b;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lai-meta{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:10px}
.lai-meta span{display:inline-flex;padding:5px 8px;border-radius:8px;background:#f8fafc;color:#64748b;font-size:11px;font-weight:700}
.lai-set{background:#eff6ff!important;color:#1d4ed8!important}
.lai-status{display:inline-flex!important;align-items:center;gap:6px}
.lai-status:before{content:"";width:7px;height:7px;border-radius:50%}
.lai-active{background:#ecfdf3!important;color:#15803d!important}.lai-active:before{background:#22c55e}
.lai-hidden{background:#f1f5f9!important;color:#64748b!important}.lai-hidden:before{background:#94a3b8}
.lai-buttons{display:flex;align-items:center;gap:7px;white-space:nowrap}
.lai-link{display:inline-flex;align-items:center;justify-content:center;min-height:35px;padding:0 11px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:12px;font-weight:750}
.lai-link:hover{border-color:#ea580c;color:#c2410c}
.lai-danger:hover{border-color:#ef4444;color:#dc2626}
.lai-empty{padding:60px 20px;border:1px solid #e5e7eb;border-radius:18px;background:#fff;text-align:center}
.lai-empty-icon{font-size:43px}
.lai-empty h3{margin:12px 0 6px}
.lai-empty p{margin:0 0 18px;color:#64748b}
.lai-flash{padding:12px 15px;border-radius:12px;font-weight:650}
.lai-success{border:1px solid #bbf7d0;background:#ecfdf3;color:#166534}
.lai-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}

.lai-buttons form{display:inline-flex;margin:0}
.lai-buttons button{font:inherit;cursor:pointer}
.lai-icon-btn{min-width:35px;padding:0}
.lai-modal-overlay{position:fixed;inset:0;z-index:1000;display:none;align-items:center;justify-content:center;padding:20px;background:rgba(15,23,42,.48)}
.lai-modal-overlay.is-open{display:flex}
.lai-modal{width:min(680px,100%);max-height:calc(100vh - 40px);overflow:auto;padding:22px;border-radius:20px;background:#fff;box-shadow:0 24px 70px rgba(15,23,42,.24)}
.lai-modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:18px}
.lai-modal-head h3{margin:4px 0 0;font-size:23px}
.lai-modal-close{width:36px;height:36px;border:0;border-radius:10px;background:#f1f5f9;color:#334155;font-size:24px;cursor:pointer}
.lai-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px}
.lai-form-grid label,.lai-field{display:grid;gap:7px}
.lai-form-grid label span,.lai-field span{color:#334155;font-size:13px;font-weight:750}
.lai-field{margin-top:13px}
.lai-textarea{min-height:90px;padding-top:10px;resize:vertical}
.lai-planner-note{
    margin-top:16px;
    padding:11px 13px;
    border:1px solid #dbeafe;
    border-radius:12px;
    background:#eff6ff;
    color:#1d4ed8;
    font-size:12px;
    line-height:1.55;
}
.lai-modal-actions{display:flex;justify-content:flex-end;gap:9px;margin-top:20px}
@media(max-width:620px){.lai-form-grid{grid-template-columns:1fr}}
@media(max-width:850px){
 .lai-head{flex-direction:column}
 .lai-toolbar{grid-template-columns:1fr}
 .lai-card{grid-template-columns:54px minmax(0,1fr)}
 .lai-buttons{grid-column:1/-1;justify-content:flex-end}
}
@media(max-width:620px){
 .lai-stats{grid-template-columns:1fr}
 .lai-card{grid-template-columns:1fr}
 .lai-order{width:46px;height:46px}
 .lai-buttons{justify-content:stretch}
 .lai-link{flex:1}
}
</style>

<div class="lai-page">
    <div class="lai-head">
        <div>
            <span class="lai-kicker">Activity Builder</span>
            <h2>Lesson Activities</h2>

            <p class="lai-path">
                <?php if ($lesson): ?>
                    <?= htmlspecialchars((string)$lesson['book_name'], ENT_QUOTES, 'UTF-8') ?>
                    → <?= htmlspecialchars((string)$lesson['level_name'], ENT_QUOTES, 'UTF-8') ?>
                    → <?= htmlspecialchars(
                        (string)$lesson['unit_number'] . ' • ' . (string)$lesson['unit_title'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                    → <strong><?= htmlspecialchars(
                        (string)$lesson['lesson_number'] . ' • ' . (string)$lesson['lesson_title'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?></strong>
                <?php else: ?>
                    View Activities across all Lessons.
                <?php endif; ?>
            </p>
        </div>

        <div class="lai-top-actions">
            <a
                href="../lessons/index.php<?= $lesson ? '?book_id=' . (int)$lesson['book_id'] . '&unit_id=' . (int)$lesson['unit_id'] : '' ?>"
                class="button button-secondary"
            >
                ← Lessons
            </a>

            <?php if ($lesson): ?>
                <button type="button" class="button button-primary" data-open-activity-modal>
                    + Add Activity
                </button>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($message !== ''): ?>
        <div class="lai-flash <?= $messageType === 'error' ? 'lai-error' : 'lai-success' ?>">
            <?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <div class="lai-stats">
        <div class="lai-stat">
            <span>Total Activities</span>
            <strong><?= $totalActivities ?></strong>
        </div>
        <div class="lai-stat">
            <span>Active</span>
            <strong><?= $activeActivities ?></strong>
        </div>
        <div class="lai-stat">
            <span>Hidden</span>
            <strong><?= $hiddenActivities ?></strong>
        </div>
    </div>

    <form class="lai-toolbar" method="get" action="index.php">
        <?php if ($lessonId > 0): ?>
            <input type="hidden" name="lesson_id" value="<?= $lessonId ?>">
        <?php endif; ?>

        <input
            class="lai-input"
            type="search"
            name="keyword"
            value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>"
            placeholder="Search Activity, Template or Flashcard Set..."
        >

        <?php if (isset($activityColumns['status'])): ?>
            <select class="lai-select" name="status" onchange="this.form.submit()">
                <option value="">All Status</option>
                <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
                <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Hidden</option>
            </select>
        <?php else: ?>
            <div></div>
        <?php endif; ?>

        <div style="display:flex;gap:8px">
            <button type="submit" class="button button-primary">Search</button>

            <?php if ($keyword !== '' || $status !== ''): ?>
                <a
                    href="index.php<?= $lessonId > 0 ? '?lesson_id=' . $lessonId : '' ?>"
                    class="button button-secondary"
                >
                    Reset
                </a>
            <?php endif; ?>
        </div>
    </form>

    <?php if (!$lesson): ?>
        <div style="padding:12px 15px;border:1px solid #dbeafe;border-radius:12px;background:#eff6ff;color:#1d4ed8;font-size:13px;">
            To add a new Activity, open a specific Lesson first. Each Activity must belong to one Lesson.
        </div>
    <?php endif; ?>

    <?php if ($activities === []): ?>
        <div class="lai-empty">
            <div class="lai-empty-icon">🎯</div>
            <h3>No Activities yet</h3>
            <p>
                <?= $lesson
                    ? 'Add the first learning Activity for this Lesson.'
                    : 'Open a Lesson to create its learning Activities.' ?>
            </p>

            <?php if ($lesson): ?>
                <button type="button" class="button button-primary" data-open-activity-modal>
                    + Add Activity
                </button>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="lai-list">
            <?php foreach ($activities as $index => $activity): ?>
                <?php
                $type = (string)$activity['activity_type'];
                $isActive = (string)$activity['activity_status'] !== 'inactive';
                $displayNumber = $index + 1;
                ?>
                <article class="lai-card">
                    <div class="lai-order"><?= $displayNumber ?></div>

                    <div class="lai-main">
                        <div class="lai-title-line">
                            <h3>
                                <?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?>
                            </h3>

                            <span class="lai-type">
                                <?= laiTypeIcon($type) ?>
                                <?= htmlspecialchars(laiTypeLabel($type), ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        </div>

                        <p class="lai-description">
                            <?= htmlspecialchars(
                                (string)($activity['activity_description'] ?: 'No instructions yet'),
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </p>

                        <div class="lai-meta">
                            <?php if (!$lesson): ?>
                                <span>
                                    <?= htmlspecialchars(
                                        (string)$activity['book_name']
                                        . ' → '
                                        . (string)$activity['unit_number']
                                        . ' → '
                                        . (string)$activity['lesson_number'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </span>
                            <?php endif; ?>

                            <span>
                                Game: <?= htmlspecialchars(laiTypeLabel($type), ENT_QUOTES, 'UTF-8') ?>
                            </span>

                            <span class="lai-set">
                                Flashcard Set:
                                <?= htmlspecialchars(
                                    (string)($activity['flashcard_set_name'] ?: 'Not selected'),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </span>

                            <span><?= (int)$activity['word_count'] ?> words</span>
                            <span>
                                Runtime:
                                student/student-runtime/index.php?activity_id=<?= (int)$activity['id'] ?>
                            </span>

                            <?php if (isset($activityColumns['xp_reward'])): ?>
                                <span>XP <?= (int)$activity['xp_reward'] ?></span>
                            <?php endif; ?>

                            <?php if (isset($activityColumns['passing_score'])): ?>
                                <span>Pass <?= (int)$activity['passing_score'] ?>%</span>
                            <?php endif; ?>

                            <span class="lai-status <?= $isActive ? 'lai-active' : 'lai-hidden' ?>">
                                <?= $isActive ? 'Active' : 'Hidden' ?>
                            </span>
                        </div>
                    </div>

                    <div class="lai-buttons">
                        <?php if ($index > 0): ?>
                        <form method="post">
                            <input type="hidden" name="action" value="move_activity">
                            <input type="hidden" name="lesson_id" value="<?= (int)$activity['lesson_id'] ?>">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <input type="hidden" name="direction" value="up">
                            <button type="submit" class="lai-link lai-icon-btn" title="Move up">↑</button>
                        </form>
                        <?php endif; ?>

                        <?php if ($index < count($activities) - 1): ?>
                        <form method="post">
                            <input type="hidden" name="action" value="move_activity">
                            <input type="hidden" name="lesson_id" value="<?= (int)$activity['lesson_id'] ?>">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <input type="hidden" name="direction" value="down">
                            <button type="submit" class="lai-link lai-icon-btn" title="Move down">↓</button>
                        </form>
                        <?php endif; ?>

                        <a
                            class="lai-link"
                            href="../../student/student-runtime/index.php?activity_id=<?= (int)$activity['id'] ?>&amp;preview=1"
                            target="_blank"
                            rel="noopener"
                        >
                            Preview
                        </a>

                        <a
                            class="lai-link"
                            href="../activity-settings/index.php?activity_id=<?= (int)$activity['id'] ?>"
                        >
                            Settings
                        </a>

                        <button
                            type="button"
                            class="lai-link"
                            data-edit-activity
                            data-id="<?= (int)$activity['id'] ?>"
                            data-lesson-id="<?= (int)$activity['lesson_id'] ?>"
                            data-title="<?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?>"
                            data-type="<?= htmlspecialchars((string)$activity['activity_type'], ENT_QUOTES, 'UTF-8') ?>"
                            data-description="<?= htmlspecialchars((string)$activity['activity_description'], ENT_QUOTES, 'UTF-8') ?>"
                            data-set-id="<?= (int)($activity['flashcard_set_id'] ?? 0) ?>"
                            data-xp="<?= (int)$activity['xp_reward'] ?>"
                            data-pass="<?= (int)$activity['passing_score'] ?>"
                        >
                            Edit
                        </button>

                        <form method="post">
                            <input type="hidden" name="action" value="duplicate_activity">
                            <input type="hidden" name="lesson_id" value="<?= (int)$activity['lesson_id'] ?>">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <button type="submit" class="lai-link" title="Duplicate">⧉</button>
                        </form>

                        <?php if (isset($activityColumns['status'])): ?>
                        <form method="post">
                            <input type="hidden" name="action" value="toggle_activity">
                            <input type="hidden" name="lesson_id" value="<?= (int)$activity['lesson_id'] ?>">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <button type="submit" class="lai-link">
                                <?= $isActive ? 'Hide' : 'Show' ?>
                            </button>
                        </form>
                        <?php endif; ?>

                        <form
                            method="post"
                            onsubmit="return confirm('Delete this Activity?');"
                        >
                            <input type="hidden" name="action" value="delete_activity">
                            <input type="hidden" name="lesson_id" value="<?= (int)$activity['lesson_id'] ?>">
                            <input type="hidden" name="activity_id" value="<?= (int)$activity['id'] ?>">
                            <button type="submit" class="lai-link lai-danger">Delete</button>
                        </form>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>


<div class="lai-modal-overlay" id="activityModal">
    <div class="lai-modal">
        <div class="lai-modal-head">
            <div>
                <span class="lai-kicker">Activity Builder</span>
                <h3 id="activityModalTitle">Add Activity</h3>
            </div>
            <button type="button" class="lai-modal-close" data-close-activity-modal>×</button>
        </div>

        <form method="post" id="activityForm">
            <input type="hidden" name="action" id="activityAction" value="create_activity">
            <input
                type="hidden"
                name="lesson_id"
                id="activityLessonId"
                value="<?= $lesson ? (int)$lesson['id'] : 0 ?>"
            >
            <input type="hidden" name="activity_id" id="activityId">

            <div class="lai-form-grid">
                <label>
                    <span>Game Template *</span>
                    <select class="lai-select" name="activity_type" id="activityType">
                        <?php foreach ($gameTemplates as $templateKey => $template): ?>
                        <option
                            value="<?= htmlspecialchars($templateKey, ENT_QUOTES, 'UTF-8') ?>"
                            data-title="<?= htmlspecialchars((string)$template['label'], ENT_QUOTES, 'UTF-8') ?>"
                            data-description="<?= htmlspecialchars((string)$template['description'], ENT_QUOTES, 'UTF-8') ?>"
                            data-uses-set="<?= !empty($template['uses_word_set']) ? '1' : '0' ?>"
                        >
                            <?= htmlspecialchars(
                                (string)$template['icon'] . ' ' . (string)$template['label'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label>
                    <span>Activity title</span>
                    <input
                        class="lai-input"
                        type="text"
                        name="title"
                        id="activityTitle"
                        placeholder="Automatically uses the Game Template name"
                    >
                </label>
            </div>

            <label class="lai-field">
                <span>Instructions</span>
                <textarea class="lai-input lai-textarea" name="description" id="activityDescription"></textarea>
            </label>

            <?php if ($hasSetLink): ?>
            <label class="lai-field" id="activitySetField">
                <span>Learning Content · Flashcard Set</span>
                <select class="lai-select" name="flashcard_set_id" id="activitySetId">
                    <option value="0">Not selected</option>
                    <?php foreach ($flashcardSets as $set): ?>
                    <option value="<?= (int)$set['id'] ?>">
                        <?= htmlspecialchars((string)$set['set_label'], ENT_QUOTES, 'UTF-8') ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </label>
            <?php endif; ?>

            <div class="lai-form-grid">
                <?php if (isset($activityColumns['xp_reward'])): ?>
                <label>
                    <span>XP reward</span>
                    <input class="lai-input" type="number" min="0" name="xp_reward" id="activityXp" value="10">
                </label>
                <?php endif; ?>

                <?php if (isset($activityColumns['passing_score'])): ?>
                <label>
                    <span>Passing score (%)</span>
                    <input class="lai-input" type="number" min="0" max="100" name="passing_score" id="activityPass" value="80">
                </label>
                <?php endif; ?>
            </div>

            <div class="lai-planner-note">
                After creating the Activity, use <strong>Settings</strong> to choose
                Items per session, Shuffle, IPA, Meaning, Replay and other game options.
            </div>

            <div class="lai-modal-actions">
                <button type="button" class="button button-secondary" data-close-activity-modal>
                    Cancel
                </button>
                <button type="submit" class="button button-primary" id="activitySubmit">
                    Create Activity
                </button>
            </div>
        </form>
    </div>
</div>

<script>
(function () {
    var modal = document.getElementById('activityModal');

    function selectedTemplateOption() {
        var select = document.getElementById('activityType');
        return select ? select.options[select.selectedIndex] : null;
    }

    function updateSetVisibility() {
        var field = document.getElementById('activitySetField');
        var option = selectedTemplateOption();

        if (!field) return;

        field.style.display =
            option && option.dataset.usesSet === '1'
                ? ''
                : 'none';
    }

    function applyTemplateDefaults(force) {
        var option = selectedTemplateOption();
        var titleInput = document.getElementById('activityTitle');
        var descriptionInput = document.getElementById('activityDescription');

        if (!option || !titleInput || !descriptionInput) return;

        if (force || titleInput.value.trim() === '') {
            titleInput.value = option.dataset.title || '';
        }

        if (force || descriptionInput.value.trim() === '') {
            descriptionInput.value = option.dataset.description || '';
        }
    }

    function openActivityModal(mode, data) {
        if (!modal) return;

        var isEdit = mode === 'edit';

        document.getElementById('activityModalTitle').textContent =
            isEdit ? 'Edit Activity' : 'Add Activity';

        document.getElementById('activityAction').value =
            isEdit ? 'update_activity' : 'create_activity';

        document.getElementById('activityId').value =
            isEdit ? (data.id || '') : '';

        var lessonInput = document.getElementById('activityLessonId');

        if (lessonInput) {
            lessonInput.value = isEdit
                ? String(data.lessonId || 0)
                : String(lessonInput.value || 0);
        }

        document.getElementById('activityType').value =
            isEdit ? (data.type || 'flashcards') : 'flashcards';

        document.getElementById('activityTitle').value =
            isEdit ? (data.title || '') : '';

        document.getElementById('activityDescription').value =
            isEdit ? (data.description || '') : '';

        if (!isEdit) {
            applyTemplateDefaults(true);
        }

        var setSelect = document.getElementById('activitySetId');
        if (setSelect) {
            setSelect.value = isEdit ? String(data.setId || 0) : '0';
        }

        var xpInput = document.getElementById('activityXp');
        if (xpInput) {
            xpInput.value = isEdit ? String(data.xp || 0) : '10';
        }

        var passInput = document.getElementById('activityPass');
        if (passInput) {
            passInput.value = isEdit ? String(data.pass || 0) : '80';
        }

        document.getElementById('activitySubmit').textContent =
            isEdit ? 'Save Changes' : 'Create Activity';

        updateSetVisibility();
        modal.classList.add('is-open');
    }

    function closeActivityModal() {
        if (modal) {
            modal.classList.remove('is-open');
        }
    }

    /*
     * Event delegation:
     * Các nút vẫn hoạt động ngay cả khi danh sách Activity được render lại.
     */
    document.addEventListener('click', function (event) {
        var openButton = event.target.closest('[data-open-activity-modal]');

        if (openButton) {
            event.preventDefault();

            var defaultLessonId = document.getElementById('activityLessonId');

            if (!defaultLessonId || Number(defaultLessonId.value || 0) <= 0) {
                return;
            }

            openActivityModal('create', {});
            return;
        }

        var editButton = event.target.closest('[data-edit-activity]');

        if (editButton) {
            event.preventDefault();

            openActivityModal('edit', {
                id: editButton.dataset.id,
                lessonId: editButton.dataset.lessonId,
                title: editButton.dataset.title,
                type: editButton.dataset.type,
                description: editButton.dataset.description,
                setId: editButton.dataset.setId,
                xp: editButton.dataset.xp,
                pass: editButton.dataset.pass
            });

            return;
        }

        var closeButton = event.target.closest('[data-close-activity-modal]');

        if (closeButton) {
            event.preventDefault();
            closeActivityModal();
        }
    });

    if (modal) {
        modal.addEventListener('click', function (event) {
            if (event.target === modal) {
                closeActivityModal();
            }
        });
    }

    var activityTypeSelect = document.getElementById('activityType');

    if (activityTypeSelect) {
        activityTypeSelect.addEventListener(
            'change',
            function () {
                updateSetVisibility();
                applyTemplateDefaults(true);
            }
        );
    }
})();
</script>


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