<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Lesson Activities
 * File: teacher/lesson-activities/create.php
 *
 * Word Library -> Flashcard Set -> Lesson Activity -> Student Game
 */

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

$pdo = getDbConnection();

$pageTitle = 'Add Activity';
$pageSubtitle = 'Create a Practice inside a Lesson';
$activeTeacherNav = 'content';

$lessonId = max(
    0,
    (int)($_GET['lesson_id'] ?? ($_SESSION['activities_old']['lesson_id'] ?? 0))
);

if ($lessonId <= 0) {
    $_SESSION['lessons_message'] = 'Please choose a Lesson first.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location: ../lessons/index.php');
    exit;
}

function lacTableExists(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 lacColumns(PDO $pdo, string $table): array
{
    if (!lacTableExists($pdo, $table)) {
        return [];
    }

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

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

    return null;
}

function lacOld(array $old, string $key, string $default = ''): string
{
    return htmlspecialchars((string)($old[$key] ?? $default), ENT_QUOTES, 'UTF-8');
}

$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,
        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"
);
$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;
}

$activityColumns = lacColumns($pdo, 'activities');
$setColumns = lacColumns($pdo, 'flashcard_sets');
$wordColumns = lacColumns($pdo, 'words');

$hasFlashcardSetId = isset($activityColumns['flashcard_set_id']);
$hasLearningGoal = isset($activityColumns['learning_goal']);
$hasDifficulty = isset($activityColumns['difficulty']);
$hasIcon = isset($activityColumns['icon']);

$flashcardSets = [];
$setWords = [];

if ($hasFlashcardSetId && $setColumns !== []) {
    $setLabelColumn = lacFirstColumn(
        $setColumns,
        ['title', 'name', 'set_name', 'label']
    ) ?? 'id';

    $setStatusSql = isset($setColumns['status'])
        ? "WHERE status = 'active'"
        : '';

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

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

    $relationTable = null;

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

    if ($relationTable !== null && $wordColumns !== []) {
        $relationColumns = lacColumns($pdo, $relationTable);

        $setFk = lacFirstColumn(
            $relationColumns,
            ['flashcard_set_id', 'set_id']
        );

        $wordFk = lacFirstColumn(
            $relationColumns,
            ['word_id', 'vocabulary_id']
        );

        $wordLabel = lacFirstColumn(
            $wordColumns,
            ['word', 'term', 'english', 'text', 'title', 'name']
        );

        $wordMeaning = lacFirstColumn(
            $wordColumns,
            ['meaning', 'vietnamese', 'translation', 'definition']
        );

        $wordImage = lacFirstColumn(
            $wordColumns,
            ['image', 'image_path', 'image_url', 'thumbnail']
        );

        if ($setFk && $wordFk && $wordLabel) {
            $meaningSelect = $wordMeaning
                ? "w.`{$wordMeaning}` AS word_meaning"
                : "'' AS word_meaning";

            $imageSelect = $wordImage
                ? "w.`{$wordImage}` AS word_image"
                : "'' AS word_image";

            $orderSql = isset($relationColumns['sort_order'])
                ? 'r.sort_order ASC, r.id ASC'
                : 'r.id ASC';

            $rows = $pdo->query(
                "SELECT
                    r.`{$setFk}` AS set_id,
                    w.id AS word_id,
                    w.`{$wordLabel}` AS word_label,
                    {$meaningSelect},
                    {$imageSelect}
                 FROM `{$relationTable}` r
                 INNER JOIN words w ON w.id = r.`{$wordFk}`
                 ORDER BY r.`{$setFk}` ASC, {$orderSql}"
            )->fetchAll(PDO::FETCH_ASSOC);

            foreach ($rows as $row) {
                $setWords[(int)$row['set_id']][] = [
                    'id' => (int)$row['word_id'],
                    'label' => (string)$row['word_label'],
                    'meaning' => (string)($row['word_meaning'] ?? ''),
                    'image' => (string)($row['word_image'] ?? ''),
                ];
            }
        }
    }
}

$old = is_array($_SESSION['activities_old'] ?? null)
    ? $_SESSION['activities_old']
    : [];

$errors = is_array($_SESSION['activities_errors'] ?? null)
    ? $_SESSION['activities_errors']
    : [];

unset($_SESSION['activities_old'], $_SESSION['activities_errors']);

$oldType = (string)($old['activity_type'] ?? 'flashcards');
$oldStatus = (string)($old['status'] ?? 'active');
$oldDifficulty = (string)($old['difficulty'] ?? 'easy');
$oldSetId = max(0, (int)($old['flashcard_set_id'] ?? 0));

$activityTypes = [
    'flashcards' => ['🃏', 'Flashcards'],
    'listen_repeat' => ['🔊', 'Listen & Repeat'],
    'speaking' => ['🎤', 'Speaking'],
    'memory' => ['🧠', 'Memory'],
    'matching' => ['🧩', 'Matching'],
    'quiz' => ['🎯', 'Quiz'],
    'typing' => ['⌨️', 'Typing'],
    'word_search' => ['🔎', 'Word Search'],
    'sentence_builder' => ['🧱', 'Sentence Builder'],
    'vocabulary' => ['🔤', 'Word List'],
];

ob_start();
?>

<style>
.lac-page{display:grid;gap:18px;max-width:1120px}
.lac-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.lac-head h2{margin:4px 0 0;font-size:28px}
.lac-kicker{display:block;color:#ea580c;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.lac-path{margin:7px 0 0;color:#64748b;line-height:1.55}
.lac-layout{display:grid;grid-template-columns:minmax(0,1fr) 360px;gap:18px;align-items:start}
.lac-card{padding:22px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.lac-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}
.lac-field{display:grid;gap:8px}
.lac-full{grid-column:1/-1}
.lac-label{color:#0f172a;font-size:13px;font-weight:750}
.lac-help{color:#64748b;font-size:12px;line-height:1.45}
.lac-input,.lac-select,.lac-textarea{
 width:100%;border:1px solid #dbe2ea;border-radius:11px;background:#fff;color:#0f172a;font:inherit
}
.lac-input,.lac-select{min-height:44px;padding:0 13px}
.lac-textarea{min-height:116px;padding:12px 13px;resize:vertical}
.lac-input:focus,.lac-select:focus,.lac-textarea:focus{
 outline:3px solid rgba(234,88,12,.12);border-color:#ea580c
}
.lac-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:18px;border-top:1px solid #eef2f7}
.lac-errors{padding:14px 16px;border:1px solid #fecaca;border-radius:13px;background:#fef2f2;color:#991b1b}
.lac-errors strong{display:block;margin-bottom:6px}
.lac-errors ul{margin:0;padding-left:20px}
.lac-warning{padding:13px 15px;border:1px solid #fde68a;border-radius:12px;background:#fffbeb;color:#92400e;margin-bottom:16px}
.lac-preview-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px}
.lac-preview-head h3{margin:3px 0 0}
.lac-count{padding:5px 9px;border-radius:999px;background:#eef4ff;color:#2563eb;font-size:12px;font-weight:750}
.lac-summary{display:flex;align-items:center;gap:12px;padding:13px;border:1px dashed #fdba74;border-radius:13px;background:#fff7ed;margin-bottom:14px}
.lac-summary-icon{display:grid;place-items:center;width:48px;height:48px;border-radius:13px;background:#ffedd5;font-size:23px}
.lac-summary strong{display:block}
.lac-summary small{display:block;margin-top:3px;color:#64748b}
.lac-word-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;max-height:420px;overflow:auto}
.lac-word{display:flex;align-items:center;gap:9px;padding:9px;border:1px solid #e5e7eb;border-radius:11px;background:#fff}
.lac-word-image{display:grid;place-items:center;width:38px;height:38px;flex:0 0 38px;border-radius:9px;background:#f1f5f9;overflow:hidden}
.lac-word-image img{width:100%;height:100%;object-fit:cover}
.lac-word strong{display:block;font-size:13px}
.lac-word small{display:block;color:#64748b;font-size:11px;margin-top:2px}
.lac-empty{padding:34px 14px;text-align:center;color:#64748b;border:1px dashed #cbd5e1;border-radius:13px}
@media(max-width:920px){.lac-layout,.lac-grid{grid-template-columns:1fr}.lac-full{grid-column:auto}.lac-head{flex-direction:column}}
@media(max-width:520px){.lac-word-grid{grid-template-columns:1fr}.lac-actions{flex-direction:column-reverse}.lac-actions .button{width:100%}}
</style>

<div class="lac-page">
    <div class="lac-head">
        <div>
            <span class="lac-kicker">Activity Builder</span>
            <h2>Add Activity</h2>
            <p class="lac-path">
                <?= htmlspecialchars((string)$lesson['book_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>
            </p>
        </div>

        <a href="index.php?lesson_id=<?= $lessonId ?>" class="button button-secondary">
            ← Back to Activities
        </a>
    </div>

    <?php if ($errors !== []): ?>
        <div class="lac-errors">
            <strong>Please check the following:</strong>
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?= htmlspecialchars((string)$error, ENT_QUOTES, 'UTF-8') ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="lac-layout">
        <form class="lac-card" action="store.php" method="post">
            <input type="hidden" name="lesson_id" value="<?= $lessonId ?>">

            <?php if (!$hasFlashcardSetId): ?>
                <div class="lac-warning">
                    Bảng activities chưa có cột flashcard_set_id, nên chưa thể lưu Flashcard Set.
                </div>
            <?php endif; ?>

            <div class="lac-grid">
                <div class="lac-field lac-full">
                    <label class="lac-label" for="title">Activity Name *</label>
                    <input
                        class="lac-input"
                        id="title"
                        name="title"
                        type="text"
                        maxlength="150"
                        value="<?= lacOld($old, 'title') ?>"
                        placeholder="New Words"
                        required
                    >
                    <div class="lac-help">Tên học sinh sẽ nhìn thấy trong Lesson.</div>
                </div>

                <div class="lac-field">
                    <label class="lac-label" for="activity_type">Game Template *</label>
                    <select class="lac-select" id="activity_type" name="activity_type" required>
                        <?php foreach ($activityTypes as $value => [$icon, $label]): ?>
                            <option value="<?= $value ?>" <?= $oldType === $value ? 'selected' : '' ?>>
                                <?= $icon ?> <?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="lac-help">Template quyết định cách Activity được trình bày.</div>
                </div>

                <div class="lac-field">
                    <label class="lac-label" for="flashcard_set_id">Flashcard Set</label>
                    <select
                        class="lac-select"
                        id="flashcard_set_id"
                        name="flashcard_set_id"
                        <?= !$hasFlashcardSetId ? 'disabled' : '' ?>
                    >
                        <option value="">No Flashcard Set</option>
                        <?php foreach ($flashcardSets as $set): ?>
                            <option
                                value="<?= (int)$set['id'] ?>"
                                <?= $oldSetId === (int)$set['id'] ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars((string)$set['set_label'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="lac-help">Activity chỉ tham chiếu bộ từ, không lưu từ trực tiếp.</div>
                </div>

                <?php if ($hasLearningGoal): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="learning_goal">Learning Goal</label>
                        <?php $oldGoal = (string)($old['learning_goal'] ?? 'vocabulary'); ?>
                        <select class="lac-select" id="learning_goal" name="learning_goal">
                            <?php foreach ([
                                'vocabulary' => 'Vocabulary',
                                'listening' => 'Listening',
                                'speaking' => 'Speaking',
                                'pronunciation' => 'Pronunciation',
                                'reading' => 'Reading',
                                'writing' => 'Writing',
                                'review' => 'Review',
                                'challenge' => 'Challenge',
                            ] as $value => $label): ?>
                                <option value="<?= $value ?>" <?= $oldGoal === $value ? 'selected' : '' ?>>
                                    <?= $label ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endif; ?>

                <?php if ($hasDifficulty): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="difficulty">Difficulty</label>
                        <select class="lac-select" id="difficulty" name="difficulty">
                            <option value="easy" <?= $oldDifficulty === 'easy' ? 'selected' : '' ?>>Easy</option>
                            <option value="medium" <?= $oldDifficulty === 'medium' ? 'selected' : '' ?>>Medium</option>
                            <option value="hard" <?= $oldDifficulty === 'hard' ? 'selected' : '' ?>>Hard</option>
                        </select>
                    </div>
                <?php endif; ?>

                <?php if ($hasIcon): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="icon">Icon</label>
                        <input
                            class="lac-input"
                            id="icon"
                            name="icon"
                            maxlength="100"
                            value="<?= lacOld($old, 'icon') ?>"
                            placeholder="🎯"
                        >
                    </div>
                <?php endif; ?>

                <div class="lac-field lac-full">
                    <label class="lac-label" for="instructions">Instructions</label>
                    <textarea
                        class="lac-textarea"
                        id="instructions"
                        name="instructions"
                        placeholder="Optional instruction shown before students start..."
                    ><?= lacOld($old, 'instructions') ?></textarea>
                </div>

                <?php if (isset($activityColumns['xp_reward'])): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="xp_reward">XP Reward</label>
                        <input
                            class="lac-input"
                            id="xp_reward"
                            name="xp_reward"
                            type="number"
                            min="0"
                            value="<?= lacOld($old, 'xp_reward', '10') ?>"
                        >
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['passing_score'])): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="passing_score">Passing Score (%)</label>
                        <input
                            class="lac-input"
                            id="passing_score"
                            name="passing_score"
                            type="number"
                            min="0"
                            max="100"
                            value="<?= lacOld($old, 'passing_score', '70') ?>"
                        >
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['required_xp'])): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="required_xp">Required XP</label>
                        <input
                            class="lac-input"
                            id="required_xp"
                            name="required_xp"
                            type="number"
                            min="0"
                            value="<?= lacOld($old, 'required_xp', '0') ?>"
                        >
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['sort_order'])): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="sort_order">Display Order</label>
                        <input
                            class="lac-input"
                            id="sort_order"
                            name="sort_order"
                            type="number"
                            min="0"
                            value="<?= lacOld($old, 'sort_order', '1') ?>"
                        >
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['status'])): ?>
                    <div class="lac-field">
                        <label class="lac-label" for="status">Status</label>
                        <select class="lac-select" id="status" name="status">
                            <option value="active" <?= $oldStatus === 'active' ? 'selected' : '' ?>>Active</option>
                            <option value="inactive" <?= $oldStatus === 'inactive' ? 'selected' : '' ?>>Hidden</option>
                        </select>
                    </div>
                <?php endif; ?>
            </div>

            <div class="lac-actions">
                <a href="index.php?lesson_id=<?= $lessonId ?>" class="button button-secondary">
                    Cancel
                </a>
                <button type="submit" class="button button-primary">
                    Save Activity
                </button>
            </div>
        </form>

        <aside class="lac-card">
            <div class="lac-preview-head">
                <div>
                    <span class="lac-kicker">Preview</span>
                    <h3>Flashcard Set</h3>
                </div>
                <span class="lac-count" id="wordCount">0 words</span>
            </div>

            <div class="lac-summary">
                <div class="lac-summary-icon" id="activityIcon">🃏</div>
                <div>
                    <strong id="activityTitle">New Activity</strong>
                    <small id="activityTypeLabel">Flashcards</small>
                </div>
            </div>

            <div id="wordPreview" class="lac-empty">
                Choose a Flashcard Set to preview its words.
            </div>
        </aside>
    </div>
</div>

<script>
(function () {
    const title = document.getElementById('title');
    const type = document.getElementById('activity_type');
    const setSelect = document.getElementById('flashcard_set_id');
    const activityIcon = document.getElementById('activityIcon');
    const activityTitle = document.getElementById('activityTitle');
    const activityTypeLabel = document.getElementById('activityTypeLabel');
    const wordPreview = document.getElementById('wordPreview');
    const wordCount = document.getElementById('wordCount');

    const icons = {
        flashcards: '🃏',
        listen_repeat: '🔊',
        speaking: '🎤',
        memory: '🧠',
        matching: '🧩',
        quiz: '🎯',
        typing: '⌨️',
        word_search: '🔎',
        sentence_builder: '🧱',
        vocabulary: '🔤'
    };

    const setWords = <?= json_encode(
        $setWords,
        JSON_UNESCAPED_UNICODE
        | JSON_UNESCAPED_SLASHES
        | JSON_HEX_TAG
        | JSON_HEX_AMP
        | JSON_HEX_APOS
        | JSON_HEX_QUOT
    ) ?>;

    function escapeHtml(value) {
        return String(value).replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function updateActivityPreview() {
        const selected = type.options[type.selectedIndex];

        activityIcon.textContent = icons[type.value] || '🎮';
        activityTitle.textContent = (title.value || '').trim() || 'New Activity';
        activityTypeLabel.textContent = selected
            ? selected.text.replace(/^[^\w]+/, '').trim()
            : 'Activity';
    }

    function updateWordPreview() {
        if (!setSelect || setSelect.disabled) {
            wordCount.textContent = '0 words';
            wordPreview.className = 'lac-empty';
            wordPreview.textContent = 'Flashcard Set is not available in the database.';
            return;
        }

        const setId = setSelect.value;
        const words = setWords[setId] || [];

        wordCount.textContent = words.length + (words.length === 1 ? ' word' : ' words');

        if (!setId) {
            wordPreview.className = 'lac-empty';
            wordPreview.textContent = 'Choose a Flashcard Set to preview its words.';
            return;
        }

        if (!words.length) {
            wordPreview.className = 'lac-empty';
            wordPreview.textContent = 'This Flashcard Set has no words, or its word relation table is not connected.';
            return;
        }

        wordPreview.className = 'lac-word-grid';

        wordPreview.innerHTML = words.map(function (word) {
            const image = word.image
                ? '<img src="/EnglishSpeak/' + escapeHtml(word.image.replace(/^\/+/, '')) + '" alt="">'
                : '🔤';

            const meaning = word.meaning
                ? '<small>' + escapeHtml(word.meaning) + '</small>'
                : '';

            return '<div class="lac-word">'
                + '<div class="lac-word-image">' + image + '</div>'
                + '<div><strong>' + escapeHtml(word.label) + '</strong>' + meaning + '</div>'
                + '</div>';
        }).join('');
    }

    title.addEventListener('input', updateActivityPreview);
    type.addEventListener('change', updateActivityPreview);
    setSelect?.addEventListener('change', updateWordPreview);

    updateActivityPreview();
    updateWordPreview();
})();
</script>

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