<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Activity Settings
 * File: teacher/activity-settings/index.php
 *
 * Book -> Level -> Unit -> Lesson -> Activity -> Settings
 */

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

$pdo = getDbConnection();

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

if (!$isAdmin && $teacherId <= 0) {
    http_response_code(403);
    exit('Teacher account not found.');
}

$pageTitle = 'Activity Settings';
$pageSubtitle = 'Configure learning activity behaviour';
$activeTeacherNav = 'content';

$activityId = max(0, (int)($_GET['activity_id'] ?? $_POST['activity_id'] ?? 0));

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

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

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

    return null;
}

function easTypeLabel(string $type): string
{
    return match ($type) {
        'flashcards' => 'Flashcards',
        'listen_repeat', 'pronunciation' => 'Listen & Repeat',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'word_builder' => 'Word Builder',
        'word_unscramble' => 'Word Unscramble',
        'find_word' => 'Find the Word',
        'find_the_word' => 'Find the Word',
        'fix_word' => 'Fix the Word',
        'fix_the_word' => 'Fix the Word',
        'quiz' => 'Quiz',
        'speaking' => 'Speaking',
        'dialogue', 'ask_answer' => 'Dialogue',
        'reading' => 'Reading',
        'writing' => 'Writing',
        'worksheet' => 'Worksheet',
        'vocabulary', 'word_list' => 'Word List',
        default => ucwords(str_replace(['_', '-'], ' ', $type ?: 'Activity')),
    };
}

function easTypeIcon(string $type): string
{
    return match ($type) {
        'flashcards' => '🃏',
        'listen_repeat', 'pronunciation' => '🔊',
        'memory' => '🧠',
        'matching' => '🧩',
        'word_builder' => '🔤',
        'word_unscramble' => '🔀',
        'find_word', 'find_the_word' => '🔎',
        'fix_word', 'fix_the_word' => '✏️',
        'quiz' => '🎯',
        'speaking' => '🎤',
        'dialogue', 'ask_answer' => '💬',
        'reading' => '📚',
        'writing' => '✏️',
        'worksheet' => '📄',
        'vocabulary', 'word_list' => '📄',
        default => '🎮',
    };
}


function easResourceTypeForActivity(string $activityType): string
{
    return match ($activityType) {
        'flashcards',
        'listen_repeat',
        'pronunciation',
        'memory',
        'matching',
        'word_builder',
        'word_unscramble',
        'find_word',
        'find_the_word',
        'fix_word',
        'fix_the_word',
        'vocabulary',
        'word_list' => 'flashcard_set',

        // Quiz is still a Quiz Activity; its vocabulary source is a Flashcard Set.
        'quiz' => 'flashcard_set',

        'speaking',
        'sentence_builder' => 'sentence_set',

        'dialogue',
        'ask_answer' => 'dialogue_set',

        default => '',
    };
}

function easResourceLabel(string $resourceType): string
{
    return match ($resourceType) {
        'flashcard_set' => 'Flashcard Set',
        'quiz_set' => 'Quiz Set',
        'sentence_set' => 'Sentence Set',
        'dialogue_set' => 'Dialogue Set',
        default => 'No content source required',
    };
}

function easBool(array $source, string $key, bool $default = false): bool
{
    if (!array_key_exists($key, $source)) {
        return $default;
    }

    return in_array((string)$source[$key], ['1', 'true', 'on', 'yes'], true);
}

function easInt(array $source, string $key, int $default, int $min, int $max): int
{
    $value = isset($source[$key]) ? (int)$source[$key] : $default;
    return min($max, max($min, $value));
}

function easString(array $source, string $key, string $default = ''): string
{
    return trim((string)($source[$key] ?? $default));
}

if (!easTableExists($pdo, 'activity_settings')) {
    $pdo->exec(
        "CREATE TABLE activity_settings (
            id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            activity_id BIGINT UNSIGNED NOT NULL,
            settings_json LONGTEXT NOT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_activity_settings_activity (activity_id),
            KEY idx_activity_settings_activity (activity_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );
}

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

$pronunciationFocusFile = __DIR__
    . '/../../student/student-runtime/engines/pronunciation_focus.php';

$pronunciationFocuses = is_file($pronunciationFocusFile)
    ? require $pronunciationFocusFile
    : [
        'none' => [
            'label' => 'No specific focus',
            'type' => 'none',
            'sounds' => [],
        ],
    ];

$flashcardSetColumns = easColumns($pdo, 'flashcard_sets');
$quizSetColumns = easColumns($pdo, 'quiz_sets');
$sentenceSetColumns = easColumns($pdo, 'sentence_sets');
$dialogueSetColumns = easColumns($pdo, 'dialogue_sets');

function easLoadResourceOptions(PDO $pdo, string $table, array $columns): array
{
    if ($columns === []) {
        return [];
    }

    $labelColumn = easFirstColumn($columns, ['title', 'name', 'set_name', 'label']);

    if ($labelColumn === null) {
        return [];
    }

    $hasUnitId = isset($columns['unit_id']);
    $where = isset($columns['status']) ? " WHERE s.status = 'active'" : '';
    $order = isset($columns['sort_order'])
        ? ' ORDER BY s.sort_order, s.id'
        : " ORDER BY s.`{$labelColumn}`, s.id";

    $unitSelect = $hasUnitId
        ? ",
            s.unit_id,
            u.unit_number AS resource_unit_number,
            u.title AS resource_unit_title"
        : ",
            0 AS unit_id,
            NULL AS resource_unit_number,
            NULL AS resource_unit_title";

    $unitJoin = $hasUnitId
        ? ' LEFT JOIN units u ON u.id = s.unit_id'
        : '';

    return $pdo->query(
        "SELECT
            s.id,
            s.`{$labelColumn}` AS resource_label
            {$unitSelect}
         FROM `{$table}` s
         {$unitJoin}
         {$where}
         {$order}"
    )->fetchAll(PDO::FETCH_ASSOC);
}

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

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

$dialogueSetExpression = isset($activityColumns['dialogue_set_id'])
    ? 'a.dialogue_set_id'
    : '0';

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

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

$pronunciationFocusExpression = isset($activityColumns['pronunciation_focus'])
    ? "COALESCE(NULLIF(TRIM(a.pronunciation_focus), ''), 'none')"
    : "'none'";

$activity = null;

if ($activityId > 0) {
    $titleExpression = $titleColumn ? "a.`{$titleColumn}`" : "'Activity'";
    $typeExpression = $typeColumn ? "a.`{$typeColumn}`" : "'activity'";
    $descriptionExpression = $descriptionColumn ? "a.`{$descriptionColumn}`" : "''";

    $stmt = $pdo->prepare(
        "SELECT
            a.id,
            a.lesson_id,
            {$titleExpression} AS activity_title,
            {$typeExpression} AS activity_type,
            {$descriptionExpression} AS activity_description,
            
            {$flashcardSetExpression} AS flashcard_set_id,
            0 AS quiz_set_id,
            0 AS sentence_set_id,
            {$dialogueSetExpression} AS dialogue_set_id,
            {$xpRewardExpression} AS activity_xp_reward,
            {$passingScoreExpression} AS activity_passing_score,
            {$pronunciationFocusExpression} AS pronunciation_focus,
            l.lesson_number,
            l.created_by_teacher_id,
            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 activities a
         INNER JOIN lessons l ON l.id = a.lesson_id
         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 a.id = ?
         LIMIT 1"
    );
    $stmt->execute([$activityId]);
    $activity = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$activity) {
    $_SESSION['activities_message'] = 'Activity not found.';
    $_SESSION['activities_message_type'] = 'error';
    header('Location: ../lesson-activities/index.php');
    exit;
}

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

if (!$canManageActivitySettings) {
    http_response_code(403);
    $_SESSION['activities_message'] = 'You do not have permission to change Settings for this Lesson.';
    $_SESSION['activities_message_type'] = 'error';
    header('Location: ../lesson-activities/index.php?lesson_id=' . (int)$activity['lesson_id']);
    exit;
}

$activityType = (string)$activity['activity_type'];

$fixedResourceType = easResourceTypeForActivity($activityType);
$fixedResourceLabel = easResourceLabel($fixedResourceType);

if (in_array($activityType, ['listen_repeat', 'pronunciation'], true)) {
    $fixedResourceLabel = 'Word Set';
}


$flashcardSets = easLoadResourceOptions($pdo, 'flashcard_sets', $flashcardSetColumns);
$quizSets = easLoadResourceOptions($pdo, 'quiz_sets', $quizSetColumns);
$sentenceSets = easLoadResourceOptions($pdo, 'sentence_sets', $sentenceSetColumns);
$dialogueSets = easLoadResourceOptions($pdo, 'dialogue_sets', $dialogueSetColumns);

$currentUnitId = (int)$activity['unit_id'];

$decorateResourceLabel = static function (array $set): string {
    $base = trim((string)($set['resource_label'] ?? 'Untitled Set'));
    $unitNumber = trim((string)($set['resource_unit_number'] ?? ''));
    $unitTitle = trim((string)($set['resource_unit_title'] ?? ''));

    if ($unitNumber !== '' || $unitTitle !== '') {
        $unitText = trim($unitNumber . ($unitTitle !== '' ? ' - ' . $unitTitle : ''));

        $genericPatterns = [
            '/^unit\s*\d+$/i',
            '/^unit\s*\d+\s+vocabulary$/i',
            '/^vocabulary$/i',
        ];

        foreach ($genericPatterns as $pattern) {
            if (preg_match($pattern, $base)) {
                return $unitText;
            }
        }

        return $unitText . ' • ' . $base;
    }

    if (preg_match('/^unit\s*(\d+)$/i', $base, $matches)) {
        return 'Unit ' . $matches[1] . ' Vocabulary';
    }

    return $base;
};

$currentUnitDisplay = trim(
    (string)$activity['unit_number']
    . ((string)$activity['unit_title'] !== ''
        ? ' - ' . (string)$activity['unit_title']
        : '')
);

foreach ($flashcardSets as &$set) {
    $displayLabel = $decorateResourceLabel($set);
    $baseLabel = trim((string)($set['resource_label'] ?? ''));

    $genericPatterns = [
        '/^unit\s*\d+$/i',
        '/^unit\s*\d+\s+vocabulary$/i',
        '/^vocabulary$/i',
    ];

    foreach ($genericPatterns as $pattern) {
        if (preg_match($pattern, $baseLabel)) {
            $displayLabel = $currentUnitDisplay;
            break;
        }
    }

    $set['display_label'] = $displayLabel;
    $set['is_current_unit'] = (int)($set['unit_id'] ?? 0) === $currentUnitId;
}
unset($set);

foreach ($quizSets as &$set) {
    $set['display_label'] = $decorateResourceLabel($set);
    $set['is_current_unit'] = (int)($set['unit_id'] ?? 0) === $currentUnitId;
}
unset($set);

foreach ($sentenceSets as &$set) {
    $set['display_label'] = $decorateResourceLabel($set);
    $set['is_current_unit'] = (int)($set['unit_id'] ?? 0) === $currentUnitId;
}
unset($set);

foreach ($dialogueSets as &$set) {
    $set['display_label'] = trim((string)($set['resource_label'] ?? 'Dialogue Set'));
    $set['is_current_unit'] = false;
}
unset($set);

$settingsStmt = $pdo->prepare(
    'SELECT settings_json FROM activity_settings WHERE activity_id = ? LIMIT 1'
);
$settingsStmt->execute([$activityId]);
$settingsJson = $settingsStmt->fetchColumn();

$settings = [];
if (is_string($settingsJson) && $settingsJson !== '') {
    $decoded = json_decode($settingsJson, true);
    if (is_array($decoded)) {
        $settings = $decoded;
    }
}

$defaults = [
    'cards_per_session' => 8,
    'shuffle' => true,
    'auto_play' => false,
    'audio_source' => 'auto',
                'auto_next' => false,
    'show_listen_button' => true,
    'sentences_per_session' => 10,
    'passing_score' => 80,
    'ai_feedback' => true,
    'pairs' => 6,
    'word_count' => 6,
    'sentence_count' => 6,
    'show_image' => true,
    'show_word' => true,
        'show_sentence' => false,
    'word_audio_on_tap' => false,
    'shuffle_words' => true,
    'letter_voice' => true,
    'timer_enabled' => false,
    'time_limit' => 60,
    'question_count' => 10,
    'dialogue_turns' => 6,
    'shuffle_answers' => true,
    'auto_play_prompt' => true,
    'speak_correct_response' => true,
    'answer_time' => 30,
    'layout' => 'auto',
    'show_progress' => true,
    'allow_retry' => true,
    'allow_replay' => true,
    'unlimited_practice' => true,
    'student_instructions' => '',
    'resource_type' => '',
    'resource_id' => 0,
    'xp_reward' => (int)($activity['activity_xp_reward'] ?? 10),
    'practice_xp' => 2,
    'reward_passing_score' => (int)($activity['activity_passing_score'] ?? 80),
];

$settings = array_merge($defaults, $settings);

// Dialogue/Ask & Answer: inherit the Dialogue Set selected when the Activity was created.
// This makes Activity Settings and Student Runtime use the same content immediately,
// without requiring the teacher to touch the dropdown and save it again.
if (in_array($activityType, ['dialogue', 'ask_answer'], true)
    && (int)($settings['resource_id'] ?? 0) <= 0
    && (int)($activity['dialogue_set_id'] ?? 0) > 0
) {
    $settings['resource_type'] = 'dialogue_set';
    $settings['resource_id'] = (int)$activity['dialogue_set_id'];
}

$currentPronunciationFocus = trim(
    (string)($activity['pronunciation_focus'] ?? $settings['pronunciation_focus'] ?? 'none')
);

if (
    $currentPronunciationFocus === ''
    || !array_key_exists($currentPronunciationFocus, $pronunciationFocuses)
) {
    $currentPronunciationFocus = 'none';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'save_settings') {
        /*
         * Preserve the linked learning content explicitly.
         * Put resource_type/resource_id first so phpMyAdmin shows them even
         * when the LONGTEXT preview is truncated.
         */
        $postedResourceId = easInt($_POST, 'resource_id', 0, 0, 2147483647);
        $existingResourceId = max(0, (int)($settings['resource_id'] ?? 0));

        // Learning Content đang hiển thị trên form phải được xem là dữ liệu thật.
        // Nếu giáo viên chỉ mở trang rồi bấm Save Settings, Set đang hiển thị
        // vẫn được lưu vào activity_settings mà không cần đổi dropdown trước.
        if ($postedResourceId <= 0) {
            $postedResourceId = $existingResourceId;
        }

        /*
         * Nếu giáo viên chưa từng bấm chọn dropdown thì giao diện vẫn đang
         * hiển thị một Set mặc định. Set đó cũng phải được xem là lựa chọn thật
         * khi bấm Save Settings.
         *
         * Ưu tiên:
         * 1) resource_id thật sự POST lên
         * 2) resource_id đã lưu trước đó
         * 3) Set thuộc Unit hiện tại
         * 4) Set đầu tiên còn lại
         */
        $defaultResourceOptions = match ($fixedResourceType) {
            'flashcard_set' => $flashcardSets,
            'quiz_set' => $quizSets,
            'sentence_set' => $sentenceSets,
            'dialogue_set' => $dialogueSets,
            default => [],
        };

        // Sắp xếp giống hệt dropdown bên dưới để giá trị server lưu
        // luôn đúng với Set mà giáo viên đang nhìn thấy trên màn hình.
        usort($defaultResourceOptions, static function (array $a, array $b): int {
            $currentCompare = (int)($b['is_current_unit'] ?? false)
                <=> (int)($a['is_current_unit'] ?? false);

            if ($currentCompare !== 0) {
                return $currentCompare;
            }

            return strcasecmp(
                (string)($a['display_label'] ?? ''),
                (string)($b['display_label'] ?? '')
            );
        });

        $defaultResourceId = $defaultResourceOptions !== []
            ? (int)($defaultResourceOptions[0]['id'] ?? 0)
            : 0;

        $resolvedResourceId = $postedResourceId > 0
            ? $postedResourceId
            : (
                $existingResourceId > 0
                    ? $existingResourceId
                    : $defaultResourceId
            );

        $saved = [
            'resource_type' => $fixedResourceType,
            'resource_id' => $resolvedResourceId,
            'cards_per_session' => easInt($_POST, 'cards_per_session', 8, 1, 100),
            'shuffle' => easBool($_POST, 'shuffle'),
            'auto_play' => easBool($_POST, 'auto_play'),
            'audio_source' => in_array(easString($_POST, 'audio_source', 'auto'), ['auto', 'speech_synthesis', 'tts_file'], true)
                ? easString($_POST, 'audio_source', 'auto')
                : 'auto',
            'show_ipa' => easBool($_POST, 'show_ipa'),
            'show_meaning' => easBool($_POST, 'show_meaning'),
            'click_image_listen' => easBool($_POST, 'click_image_listen'),
            'auto_next' => easBool($_POST, 'auto_next'),
            'allow_replay' => easBool($_POST, 'allow_replay'),
            'unlimited_practice' => true,
            'attempts' => 0,
            'passing_score' => easInt($_POST, 'passing_score', 80, 0, 100),
            'ai_feedback' => easBool($_POST, 'ai_feedback'),
            'pairs' => easInt($_POST, 'pairs', 6, 2, 100),
            'word_count' => easInt($_POST, 'word_count', 6, 1, 100),
            'sentence_count' => easInt($_POST, 'sentence_count', 6, 1, 20),
            'show_image' => easBool($_POST, 'show_image'),
            'show_word' => easBool($_POST, 'show_word'),
            'show_listen' => easBool($_POST, 'show_listen'),
            'show_listen_button' => easBool($_POST, 'show_listen_button'),
            'show_sentence' => easBool($_POST, 'show_sentence'),
            'word_audio_on_tap' => easBool($_POST, 'word_audio_on_tap'),
            'shuffle_words' => easBool($_POST, 'shuffle_words'),
            'letter_voice' => easBool($_POST, 'letter_voice'),
            'timer_enabled' => easBool($_POST, 'timer_enabled'),
            'time_limit' => easInt($_POST, 'time_limit', 60, 10, 600),
            'question_count' => easInt($_POST, 'question_count', 10, 1, 100),
            'dialogue_turns' => easInt($_POST, 'dialogue_turns', 6, 1, 50),
            'shuffle_answers' => easBool($_POST, 'shuffle_answers', true),
            'auto_play_prompt' => easBool($_POST, 'auto_play_prompt', true),
            'speak_correct_response' => easBool($_POST, 'speak_correct_response', true),
            'answer_time' => easInt($_POST, 'answer_time', 30, 5, 300),
            'layout' => easString($_POST, 'layout', 'auto'),
            'show_progress' => easBool($_POST, 'show_progress'),
            'allow_retry' => easBool($_POST, 'allow_retry'),
            'student_instructions' => easString($_POST, 'student_instructions'),
            'xp_reward' => easInt($_POST, 'xp_reward', 10, 0, 10000),
            'practice_xp' => easInt($_POST, 'practice_xp', 2, 0, 100),
            'reward_passing_score' => easInt($_POST, 'passing_score', (int)($settings['passing_score'] ?? 80), 0, 100),
            'pronunciation_focus' => easString($_POST, 'pronunciation_focus', 'none'),
        ];

        if (in_array($activityType, ['listen_repeat', 'pronunciation'], true)) {
            $saved['reward_passing_score'] = (int)$saved['passing_score'];
        }

        if ($fixedResourceType !== '' && (int)$saved['resource_id'] <= 0) {
            $_SESSION['activity_settings_message'] = 'Please select learning content before saving.';
            $_SESSION['activity_settings_message_type'] = 'error';
            header('Location: index.php?activity_id=' . $activityId);
            exit;
        }

        if (!array_key_exists($saved['pronunciation_focus'], $pronunciationFocuses)) {
            $saved['pronunciation_focus'] = 'none';
        }

        $json = json_encode($saved, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        if ($json === false) {
            $_SESSION['activity_settings_message'] = 'Could not encode Activity settings.';
            $_SESSION['activity_settings_message_type'] = 'error';
        } else {
            $stmt = $pdo->prepare(
                "INSERT INTO activity_settings (activity_id, settings_json)
                 VALUES (?, ?)
                 ON DUPLICATE KEY UPDATE
                    settings_json = VALUES(settings_json),
                    updated_at = NOW()"
            );
            $stmt->execute([$activityId, $json]);

            $activityUpdates = [];
            $activityParams = [];

            if (isset($activityColumns['flashcard_set_id'])) {
                $resourceId = (int)$saved['resource_id'];

                $activityUpdates[] = '`flashcard_set_id` = ?';
                $activityParams[] =
                    $fixedResourceType === 'flashcard_set' && $resourceId > 0
                        ? $resourceId
                        : null;
            }

            if (isset($activityColumns['dialogue_set_id']) && $fixedResourceType === 'dialogue_set') {
                $activityUpdates[] = '`dialogue_set_id` = ?';
                $activityParams[] = (int)$saved['resource_id'] > 0 ? (int)$saved['resource_id'] : null;
            }

            if (isset($activityColumns['xp_reward'])) {
                $activityUpdates[] = '`xp_reward` = ?';
                $activityParams[] = (int)$saved['xp_reward'];
            }

            if (isset($activityColumns['passing_score'])) {
                $activityUpdates[] = '`passing_score` = ?';
                $activityParams[] = (int)$saved['reward_passing_score'];
            }

            if (isset($activityColumns['pronunciation_focus'])) {
                $activityUpdates[] = '`pronunciation_focus` = ?';
                $activityParams[] = (string)$saved['pronunciation_focus'];
            }

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

                $activityParams[] = $activityId;

                $updateActivityStmt = $pdo->prepare(
                    'UPDATE activities SET ' . implode(', ', $activityUpdates) . ' WHERE id = ?'
                );
                $updateActivityStmt->execute($activityParams);
            }

            $_SESSION['activity_settings_message'] = 'Content linked successfully. Activity settings saved.';
            $_SESSION['activity_settings_message_type'] = 'success';
        }

        header('Location: index.php?activity_id=' . $activityId);
        exit;
    }
}

$message = (string)($_SESSION['activity_settings_message'] ?? '');
$messageType = (string)($_SESSION['activity_settings_message_type'] ?? 'success');
unset($_SESSION['activity_settings_message'], $_SESSION['activity_settings_message_type']);

ob_start();
?>

<style>
.eas-page{display:grid;gap:18px}
.eas-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.eas-kicker{display:block;color:#ea580c;font-size:12px;font-weight:850;letter-spacing:.09em;text-transform:uppercase}
.eas-head h2{margin:4px 0 0;font-size:28px;color:#0f172a}
.eas-path{margin:8px 0 0;color:#64748b;line-height:1.6}
.eas-actions{display:flex;gap:9px;flex-wrap:wrap}
.eas-hero{display:grid;grid-template-columns:64px minmax(0,1fr) auto;align-items:center;gap:15px;padding:18px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.eas-icon{display:grid;place-items:center;width:58px;height:58px;border-radius:16px;background:#fff7ed;font-size:28px}
.eas-hero h3{margin:0;color:#0f172a;font-size:18px}
.eas-type{display:inline-flex;margin-top:7px;padding:5px 9px;border-radius:999px;background:#f1f5f9;color:#475569;font-size:12px;font-weight:750}
.eas-form{display:grid;gap:16px}
.eas-section{padding:20px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.eas-section h3{margin:0 0 5px;color:#0f172a;font-size:17px}
.eas-section-desc{margin:0 0 16px;color:#64748b;font-size:13px}
.eas-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.eas-field{display:grid;gap:7px}
.eas-field>span{color:#334155;font-size:13px;font-weight:750}
.eas-input,.eas-select,.eas-textarea{width:100%;min-height:42px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.eas-textarea{min-height:100px;padding-top:10px;resize:vertical}
.eas-checks{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
.eas-check{display:flex;align-items:center;gap:9px;padding:12px;border:1px solid #e5e7eb;border-radius:12px;background:#f8fafc;color:#334155;font-size:13px;font-weight:700}
.eas-check input{width:17px;height:17px}
.eas-footer{display:flex;justify-content:flex-end;gap:9px;padding:16px;border:1px solid #e5e7eb;border-radius:16px;background:#fff;position:sticky;bottom:14px;z-index:4;box-shadow:0 10px 30px rgba(15,23,42,.08)}
.eas-flash{padding:12px 15px;border-radius:12px;font-weight:700}
.eas-success{border:1px solid #bbf7d0;background:#ecfdf3;color:#166534}
.eas-error{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
.eas-note{padding:12px 14px;border:1px solid #dbeafe;border-radius:12px;background:#eff6ff;color:#1d4ed8;font-size:13px;line-height:1.55}
.eas-info-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.eas-info-item{padding:14px;border:1px solid #e5e7eb;border-radius:13px;background:#f8fafc}
.eas-info-item span{display:block;color:#64748b;font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.06em}
.eas-info-item strong{display:block;margin-top:6px;color:#0f172a;font-size:15px}
.eas-resource-row{display:grid;grid-template-columns:minmax(170px,.8fr) minmax(260px,1.6fr);gap:14px}
.eas-resource-fixed{display:grid;grid-template-columns:minmax(190px,.7fr) minmax(280px,1.5fr);gap:14px;align-items:end}
.eas-source-warning{margin-top:12px;padding:11px 13px;border:1px solid #fde68a;border-radius:11px;background:#fffbeb;color:#92400e;font-size:13px}
.eas-help{display:block;margin-top:2px;color:#64748b;font-size:12px;line-height:1.45}
.eas-learning-content-single{display:grid;grid-template-columns:1fr}
.eas-resource-actions{display:flex;gap:9px;flex-wrap:wrap;margin-top:12px}
.eas-resource-actions .button[aria-disabled="true"]{pointer-events:none;opacity:.55;cursor:not-allowed}
.eas-content-source-row{display:grid;grid-template-columns:minmax(180px,.65fr) minmax(320px,1.8fr);gap:14px;align-items:end}
.eas-source-label{padding:14px;border:1px solid #e5e7eb;border-radius:13px;background:#f8fafc}
.eas-source-label span{display:block;color:#64748b;font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.06em}
.eas-source-label strong{display:block;margin-top:6px;color:#0f172a;font-size:15px}
.eas-info-grid-expanded{grid-template-columns:repeat(3,minmax(0,1fr))}
.eas-source-type-card{max-width:360px}
.eas-reward-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.eas-compact-path{display:grid;grid-template-columns:repeat(5,minmax(0,auto));justify-content:start;gap:6px 12px;margin-top:9px;color:#64748b;font-size:13px}
.eas-compact-path span{white-space:nowrap}
@media(max-width:960px){.eas-info-grid-expanded{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:760px){.eas-info-grid,.eas-info-grid-expanded,.eas-resource-row,.eas-resource-fixed,.eas-content-source-row,.eas-learning-content-single,.eas-reward-grid{grid-template-columns:1fr}.eas-compact-path{grid-template-columns:1fr}}
@media(max-width:760px){.eas-head{flex-direction:column}.eas-hero{grid-template-columns:52px minmax(0,1fr)}.eas-hero .button{grid-column:1/-1}.eas-grid,.eas-checks{grid-template-columns:1fr}}
</style>

<div class="eas-page">
    <div class="eas-head">
        <div>
            <span class="eas-kicker">Activity Settings</span>
            <h2>Configure Activity</h2>
            <div class="eas-compact-path">
                <span><strong><?= htmlspecialchars((string)$activity['book_name'], ENT_QUOTES, 'UTF-8') ?></strong></span>
                <span><?= htmlspecialchars((string)$activity['level_name'], ENT_QUOTES, 'UTF-8') ?></span>
                <span><?= htmlspecialchars((string)$activity['unit_number'], ENT_QUOTES, 'UTF-8') ?></span>
                <span>Lesson: <?= htmlspecialchars((string)$activity['lesson_title'], ENT_QUOTES, 'UTF-8') ?></span>
                <span>Activity: <?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?></span>
            </div>
        </div>

        <div class="eas-actions">
            <a class="button button-secondary" href="../lessons/detail.php?id=<?= (int)$activity['lesson_id'] ?>">
                ← Back
            </a>
            <a class="button button-secondary" href="../activity-preview/index.php?activity_id=<?= (int)$activity['id'] ?>">
                Preview
            </a>
        </div>
    </div>

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

    <section class="eas-section">
        <h3>Activity Information</h3>
        <p class="eas-section-desc">Basic information for the selected learning Activity.</p>

        <div class="eas-info-grid eas-info-grid-expanded">
            <div class="eas-info-item">
                <span>Book</span>
                <strong><?= htmlspecialchars((string)$activity['book_name'], ENT_QUOTES, 'UTF-8') ?></strong>
            </div>

            <div class="eas-info-item">
                <span>Level</span>
                <strong><?= htmlspecialchars((string)$activity['level_name'], ENT_QUOTES, 'UTF-8') ?></strong>
            </div>

            <div class="eas-info-item">
                <span>Unit</span>
                <strong><?= htmlspecialchars(
                    trim((string)$activity['unit_number'] . ' - ' . (string)$activity['unit_title']),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?></strong>
            </div>

            <div class="eas-info-item">
                <span>Lesson</span>
                <strong><?= htmlspecialchars((string)$activity['lesson_title'], ENT_QUOTES, 'UTF-8') ?></strong>
            </div>

            <div class="eas-info-item">
                <span>Activity Name</span>
                <strong><?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?></strong>
            </div>

            <div class="eas-info-item">
                <span>Activity Type</span>
                <strong><?= easTypeIcon($activityType) ?> <?= htmlspecialchars(easTypeLabel($activityType), ENT_QUOTES, 'UTF-8') ?></strong>
            </div>
        </div>
    </section>

    <form method="post" class="eas-form">
        <input type="hidden" name="action" value="save_settings">
        <input type="hidden" name="activity_id" value="<?= (int)$activityId ?>">


        <section class="eas-section">
            <h3>Learning Content</h3>
            <p class="eas-section-desc">
                Select the learning content used by this Activity.
            </p>

            <?php
            $resourceType = $fixedResourceType;
            $resourceId = (int)($settings['resource_id'] ?? 0);

            // Backward compatibility: older Quiz settings incorrectly used quiz_set.
            // Quiz runtime already uses Flashcard Set, so recover the Activity's
            // flashcard_set_id instead of carrying an obsolete Quiz Set id forward.
            if (
                $activityType === 'quiz'
                && (string)($settings['resource_type'] ?? '') === 'quiz_set'
            ) {
                $resourceId = (int)($activity['flashcard_set_id'] ?? 0);
            }

            if (
                $resourceType === 'dialogue_set'
                && $resourceId === 0
                && (int)($activity['dialogue_set_id'] ?? 0) > 0
            ) {
                $resourceId = (int)$activity['dialogue_set_id'];
            }

            if (
                $resourceType === 'flashcard_set'
                && $resourceId === 0
                && (int)($activity['flashcard_set_id'] ?? 0) > 0
            ) {
                $resourceId = (int)$activity['flashcard_set_id'];
            }

            $resourceOptions = match ($resourceType) {
                'flashcard_set' => $flashcardSets,
                'quiz_set' => $quizSets,
                'sentence_set' => $sentenceSets,
                'dialogue_set' => $dialogueSets,
                default => [],
            };

            usort($resourceOptions, static function (array $a, array $b): int {
                $currentCompare = (int)($b['is_current_unit'] ?? false)
                    <=> (int)($a['is_current_unit'] ?? false);

                if ($currentCompare !== 0) {
                    return $currentCompare;
                }

                return strcasecmp(
                    (string)($a['display_label'] ?? ''),
                    (string)($b['display_label'] ?? '')
                );
            });

            if ($resourceId === 0 && $resourceOptions !== []) {
                // Set đầu tiên đang được UI tự chọn chính là giá trị mặc định của Activity.
                $resourceId = (int)$resourceOptions[0]['id'];
            }
            ?>

            <?php if ($resourceType !== ''): ?>
                <input
                    type="hidden"
                    name="resource_type"
                    value="<?= htmlspecialchars($resourceType, ENT_QUOTES, 'UTF-8') ?>"
                >

                <div class="eas-learning-content-single">
                    <label class="eas-field">
                        <span><?= htmlspecialchars($fixedResourceLabel, ENT_QUOTES, 'UTF-8') ?></span>
                        <select
                            class="eas-select"
                            name="resource_id"
                            id="contentSelect"
                            <?= $resourceOptions !== [] ? 'required' : '' ?>
                        >
                            <?php foreach ($resourceOptions as $set): ?>
                            <option
                                value="<?= (int)$set['id'] ?>"
                                <?= $resourceId === (int)$set['id'] ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars((string)$set['display_label'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                            <?php endforeach; ?>
                        </select>

                        <small class="eas-help">
                            Select the <?= htmlspecialchars($fixedResourceLabel, ENT_QUOTES, 'UTF-8') ?> used by this Activity.
                        </small>
                    </label>
                </div>

                <?php if ($resourceType === 'sentence_set'): ?>
                <div class="eas-resource-actions">
                    <a
                        class="button button-primary"
                        href="../sentence-sets/create.php?return_activity_id=<?= (int)$activityId ?>"
                    >
                        + New Sentence Set
                    </a>

                    <a
                        class="button button-secondary"
                        href="../sentence-sets/index.php?return_activity_id=<?= (int)$activityId ?>"
                    >
                        Manage Sets
                    </a>

                    <a
                        class="button button-secondary"
                        id="editSentenceSetButton"
                        href="<?= $resourceId > 0
                            ? '../sentence-sets/create.php?id=' . (int)$resourceId
                                . '&return_activity_id=' . (int)$activityId
                            : '#' ?>"
                        aria-disabled="<?= $resourceId > 0 ? 'false' : 'true' ?>"
                    >
                        Edit Set
                    </a>

                    <a
                        class="button button-secondary"
                        id="previewSentenceSetButton"
                        href="<?= $resourceId > 0
                            ? '../sentence-sets/detail.php?id=' . (int)$resourceId
                                . '&return_activity_id=' . (int)$activityId
                            : '#' ?>"
                        aria-disabled="<?= $resourceId > 0 ? 'false' : 'true' ?>"
                    >
                        Preview
                    </a>
                </div>
                <?php endif; ?>

                <?php if ($resourceType === 'dialogue_set'): ?>
                <div class="eas-resource-actions">
                    <a
                        class="button button-primary"
                        href="../dialogue-sets/index.php?return_activity_id=<?= (int)$activityId ?>"
                    >
                        + New Dialogue Set
                    </a>

                    <a
                        class="button button-secondary"
                        href="../dialogue-sets/index.php?return_activity_id=<?= (int)$activityId ?>"
                    >
                        Manage Sets
                    </a>

                    <a
                        class="button button-secondary"
                        id="editDialogueSetButton"
                        href="<?= $resourceId > 0
                            ? '../dialogue-sets/index.php?id=' . (int)$resourceId
                                . '&return_activity_id=' . (int)$activityId
                            : '#' ?>"
                        aria-disabled="<?= $resourceId > 0 ? 'false' : 'true' ?>"
                    >
                        Edit Set
                    </a>
                </div>
                <?php endif; ?>

                <?php if ($resourceOptions === []): ?>
                <div class="eas-source-warning">
                    No <?= htmlspecialchars($fixedResourceLabel, ENT_QUOTES, 'UTF-8') ?> is available yet.
                    Create the content set first, then return to this page.
                </div>
                <?php endif; ?>
            <?php else: ?>
                <input type="hidden" name="resource_type" value="">
                <input type="hidden" name="resource_id" value="0">

                <div class="eas-info-item">
                    <span>Learning Content</span>
                    <strong>No separate content set is required for this Activity Type.</strong>
                </div>
            <?php endif; ?>
        </section>

        <?php if ($activityType === 'flashcards'): ?>
        <section class="eas-section">
            <h3>Learning Session</h3>
            <p class="eas-section-desc">
                Choose how many learning items students practise and how Flashcards behave.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Cards per Session</span>
                    <select class="eas-select" name="cards_per_session">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $count): ?>
                        <option
                            value="<?= $count ?>"
                            <?= (int)$settings['cards_per_session'] === $count ? 'selected' : '' ?>
                        >
                            <?= $count === 100 ? 'All' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Choose 4–10 cards or All for one Flashcards session.
                    </small>
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="shuffle" value="1" <?= !empty($settings['shuffle']) ? 'checked' : '' ?>> Shuffle Cards</label>
                <label class="eas-check"><input type="checkbox" name="show_ipa" value="1" <?= !empty($settings['show_ipa']) ? 'checked' : '' ?>> Show IPA</label>
                <label class="eas-check"><input type="checkbox" name="auto_play" value="1" <?= !empty($settings['auto_play']) ? 'checked' : '' ?>> Auto Play Audio</label>
                <label class="eas-check"><input type="checkbox" name="click_image_listen" value="1" <?= !empty($settings['click_image_listen']) ? 'checked' : '' ?>> Tap Image to Play Audio</label>
                <label class="eas-check"><input type="checkbox" name="show_meaning" value="1" <?= !empty($settings['show_meaning']) ? 'checked' : '' ?>> Show Vietnamese Meaning</label>
            </div>
        </section>

        <?php elseif (in_array($activityType, ['listen_repeat', 'pronunciation'], true)): ?>
        <section class="eas-section">
            <h3>Learning Session</h3>
            <p class="eas-section-desc">
                Choose how many words students practise and how Listen &amp; Repeat behaves.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Words per Session</span>
                    <select class="eas-select" name="cards_per_session">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $count): ?>
                        <option
                            value="<?= $count ?>"
                            <?= (int)$settings['cards_per_session'] === $count ? 'selected' : '' ?>
                        >
                            <?= $count === 100 ? 'All' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Choose 4–10 words or All for one Listen &amp; Repeat session.
                    </small>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input class="eas-input" type="number" name="passing_score" min="0" max="100" value="<?= (int)$settings['passing_score'] ?>">
                </label>

                <label class="eas-field">
                    <span>🎯 Pronunciation Focus</span>
                    <select class="eas-select" name="pronunciation_focus">
                        <?php
                        $focusGroups = [
                            'initial' => 'Initial consonants',
                            'final' => 'Final consonants',
                            'vowel' => 'Vowels',
                            'other' => 'Other',
                        ];

                        $hiddenFocusKeys = [
                            'initial_consonants',
                            'final_consonants',
                        ];

                        $groupedFocuses = [];

                        foreach ($pronunciationFocuses as $focusKey => $focusConfig) {
                            if (
                                $focusKey === 'none'
                                || in_array($focusKey, $hiddenFocusKeys, true)
                            ) {
                                continue;
                            }

                            $focusType = (string)($focusConfig['type'] ?? 'other');
                            $groupKey = array_key_exists($focusType, $focusGroups)
                                ? $focusType
                                : 'other';

                            $groupedFocuses[$groupKey][$focusKey] = $focusConfig;
                        }
                        ?>

                        <option value="none" <?= $currentPronunciationFocus === 'none' ? 'selected' : '' ?>>
                            No specific focus
                        </option>

                        <?php foreach ($focusGroups as $groupKey => $groupLabel): ?>
                            <?php if (empty($groupedFocuses[$groupKey])): ?>
                                <?php continue; ?>
                            <?php endif; ?>

                            <optgroup label="<?= htmlspecialchars($groupLabel, ENT_QUOTES, 'UTF-8') ?>">
                                <?php foreach ($groupedFocuses[$groupKey] as $focusKey => $focusConfig): ?>
                                    <option
                                        value="<?= htmlspecialchars((string)$focusKey, ENT_QUOTES, 'UTF-8') ?>"
                                        <?= $currentPronunciationFocus === (string)$focusKey ? 'selected' : '' ?>
                                    >
                                        <?= htmlspecialchars(
                                            (string)($focusConfig['label'] ?? $focusKey),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Choose one lesson goal. AI will prioritize only this pronunciation target.
                    </small>
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="show_image" value="1" <?= !empty($settings['show_image']) ? 'checked' : '' ?>> Show Image</label>
                <label class="eas-check"><input type="checkbox" name="show_ipa" value="1" <?= !empty($settings['show_ipa']) ? 'checked' : '' ?>> Show IPA</label>
                <label class="eas-check"><input type="checkbox" name="auto_play" value="1" <?= !empty($settings['auto_play']) ? 'checked' : '' ?>> Play Audio Automatically</label>
                <label class="eas-check"><input type="checkbox" name="show_listen_button" value="1" <?= !empty($settings['show_listen_button']) ? 'checked' : '' ?>> Listen Button</label>
                <label class="eas-check"><input type="checkbox" name="auto_next" value="1" <?= !empty($settings['auto_next']) ? 'checked' : '' ?>> Auto Next</label>
                <label class="eas-check"><input type="checkbox" name="allow_replay" value="1" <?= !empty($settings['allow_replay']) ? 'checked' : '' ?>> Allow Replay</label>
            </div>
        </section>

        <?php elseif ($activityType === 'speaking'): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">Set speaking attempts, pass requirements and feedback.</p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Passing score (%)</span>
                    <input class="eas-input" type="number" name="passing_score" min="0" max="100" value="<?= (int)$settings['passing_score'] ?>">
                </label>

                <label class="eas-field">
                    <span>🎯 Pronunciation Focus</span>
                    <select class="eas-select" name="pronunciation_focus">
                        <?php
                        $focusGroups = [
                            'initial' => 'Initial consonants',
                            'final' => 'Final consonants',
                            'vowel' => 'Vowels',
                            'other' => 'Other',
                        ];

                        $hiddenFocusKeys = [
                            'initial_consonants',
                            'final_consonants',
                        ];

                        $groupedFocuses = [];

                        foreach ($pronunciationFocuses as $focusKey => $focusConfig) {
                            if (
                                $focusKey === 'none'
                                || in_array($focusKey, $hiddenFocusKeys, true)
                            ) {
                                continue;
                            }

                            $focusType = (string)($focusConfig['type'] ?? 'other');
                            $groupKey = array_key_exists($focusType, $focusGroups)
                                ? $focusType
                                : 'other';

                            $groupedFocuses[$groupKey][$focusKey] = $focusConfig;
                        }
                        ?>

                        <option value="none" <?= $currentPronunciationFocus === 'none' ? 'selected' : '' ?>>
                            No specific focus
                        </option>

                        <?php foreach ($focusGroups as $groupKey => $groupLabel): ?>
                            <?php if (empty($groupedFocuses[$groupKey])): ?>
                                <?php continue; ?>
                            <?php endif; ?>

                            <optgroup label="<?= htmlspecialchars($groupLabel, ENT_QUOTES, 'UTF-8') ?>">
                                <?php foreach ($groupedFocuses[$groupKey] as $focusKey => $focusConfig): ?>
                                    <option
                                        value="<?= htmlspecialchars((string)$focusKey, ENT_QUOTES, 'UTF-8') ?>"
                                        <?= $currentPronunciationFocus === (string)$focusKey ? 'selected' : '' ?>
                                    >
                                        <?= htmlspecialchars(
                                            (string)($focusConfig['label'] ?? $focusKey),
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Choose one lesson goal. AI will prioritize only this pronunciation target.
                    </small>
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="show_image" value="1" <?= !empty($settings['show_image']) ? 'checked' : '' ?>> Show Image</label>
                <label class="eas-check"><input type="checkbox" name="show_listen_button" value="1" <?= !empty($settings['show_listen_button']) ? 'checked' : '' ?>> Show Listen Button</label>
                <label class="eas-check"><input type="checkbox" name="auto_play" value="1" <?= !empty($settings['auto_play']) ? 'checked' : '' ?>> Auto Play Sentence Audio</label>
                <label class="eas-check"><input type="checkbox" name="auto_next" value="1" <?= !empty($settings['auto_next']) ? 'checked' : '' ?>> Auto Next</label>
            </div>

            <div class="eas-grid" style="margin-top:14px">
                <label class="eas-field">
                    <span>Audio Source</span>
                    <select class="eas-select" name="audio_source">
                        <option value="auto" <?= ($settings['audio_source'] ?? 'auto') === 'auto' ? 'selected' : '' ?>>Auto — use TTS file, fallback to SpeechSynthesis</option>
                        <option value="speech_synthesis" <?= ($settings['audio_source'] ?? 'auto') === 'speech_synthesis' ? 'selected' : '' ?>>Browser SpeechSynthesis</option>
                        <option value="tts_file" <?= ($settings['audio_source'] ?? 'auto') === 'tts_file' ? 'selected' : '' ?>>Recorded TTS audio file</option>
                    </select>
                    <small class="eas-help">
                        Auto is recommended: play the saved audio file when available; otherwise use the browser's English voice.
                    </small>
                </label>
            </div>
        </section>

        <?php elseif (in_array($activityType, ['dialogue', 'ask_answer'], true)): ?>
        <section class="eas-section">
            <h3><?= $activityType === 'ask_answer' ? 'Ask &amp; Answer Settings' : 'Dialogue Settings' ?></h3>
            <p class="eas-section-desc">
                <?= $activityType === 'ask_answer'
                    ? 'Students listen to the machine question and answer aloud.'
                    : 'Students listen to each prompt and choose the best response. Wrong choices disappear so they can try again.' ?>
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Turns per Session</span>
                    <select class="eas-select" name="dialogue_turns">
                        <?php foreach ([2, 3, 4, 5, 6, 8, 10, 50] as $count): ?>
                        <option value="<?= $count ?>" <?= (int)($settings['dialogue_turns'] ?? 6) === $count ? 'selected' : '' ?>>
                            <?= $count === 50 ? 'All' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="passing_score"
                        min="0"
                        max="100"
                        value="<?= (int)$settings['passing_score'] ?>"
                    >
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <?php if ($activityType === 'dialogue'): ?>
                <label class="eas-check">
                    <input type="checkbox" name="shuffle_answers" value="1" <?= !empty($settings['shuffle_answers']) ? 'checked' : '' ?>>
                    Shuffle Answer Choices
                </label>
                <?php endif; ?>
                <label class="eas-check">
                    <input type="checkbox" name="auto_play_prompt" value="1" <?= !empty($settings['auto_play_prompt']) ? 'checked' : '' ?>>
                    Auto Play Question
                </label>
                <label class="eas-check">
                    <input type="checkbox" name="speak_correct_response" value="1" <?= !empty($settings['speak_correct_response']) ? 'checked' : '' ?>>
                    Read Correct Response
                </label>
                <label class="eas-check">
                    <input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>>
                    Show Progress
                </label>
            </div>

            <div class="eas-note" style="margin-top:14px">
                <?php if ($activityType === 'ask_answer'): ?>
                    Score is based on the student's spoken answer for each turn. Passing Score controls completion and XP.
                <?php else: ?>
                    Score is based on the student's <strong>first choice</strong> for each turn.
                    A wrong choice disappears and the student can keep trying without negative wording.
                <?php endif; ?>
            </div>
        </section>

        <?php elseif ($activityType === 'sentence_builder'): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">
                Choose how many sentences students practise and how the game behaves.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Sentences per Session</span>
                    <select class="eas-select" name="sentence_count">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $count): ?>
                        <option
                            value="<?= $count ?>"
                            <?= (int)($settings['sentence_count'] ?? 6) === $count ? 'selected' : '' ?>
                        >
                            <?= $count === 20 ? 'All / Up to 20' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="passing_score"
                        min="0"
                        max="100"
                        value="<?= (int)$settings['passing_score'] ?>"
                    >
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check">
                    <input type="checkbox" name="show_image" value="1" <?= !empty($settings['show_image']) ? 'checked' : '' ?>>
                    Show Image
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_listen" value="1" <?= !empty($settings['show_listen']) ? 'checked' : '' ?>>
                    Show Listen Button
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_sentence" value="1" <?= !empty($settings['show_sentence']) ? 'checked' : '' ?>>
                    Show Sentence Model
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="word_audio_on_tap" value="1" <?= !empty($settings['word_audio_on_tap']) ? 'checked' : '' ?>>
                    Word Audio on Tap
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="shuffle_words" value="1" <?= !empty($settings['shuffle_words']) ? 'checked' : '' ?>>
                    Shuffle Words
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="auto_next" value="1" <?= !empty($settings['auto_next']) ? 'checked' : '' ?>>
                    Auto Next after correct answer
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>>
                    Show Progress
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>>
                    Allow Try Again
                </label>
            </div>

            <div class="eas-note" style="margin-top:14px">
                Recommended listening mode: keep <strong>Show Listen Button</strong>
                and <strong>Shuffle Words</strong> on. Leave
                <strong>Show Sentence Model</strong> and
                <strong>Word Audio on Tap</strong> off so students listen to the
                complete sentence instead of finding the answer word by word.
            </div>
        </section>

        <?php elseif (in_array($activityType, ['find_word', 'find_the_word', 'fix_word', 'fix_the_word'], true)): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">
                Choose how many words students practise and the passing score for this vocabulary game.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Words per Session</span>
                    <select class="eas-select" name="word_count">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $count): ?>
                        <option value="<?= $count ?>" <?= (int)$settings['word_count'] === $count ? 'selected' : '' ?>>
                            <?= $count === 100 ? 'All' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">Select how many words students practise in one session.</small>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input class="eas-input" type="number" name="passing_score" min="0" max="100" value="<?= (int)$settings['passing_score'] ?>">
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="show_image" value="1" <?= !empty($settings['show_image']) ? 'checked' : '' ?>> Show Image</label>
                <label class="eas-check"><input type="checkbox" name="letter_voice" value="1" <?= !empty($settings['letter_voice']) ? 'checked' : '' ?>> Play Word / Letter Audio</label>
                <label class="eas-check"><input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>> Show Progress</label>
                <label class="eas-check"><input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>> Allow Try Again</label>
            </div>

            <div class="eas-note" style="margin-top:14px">
                <?= in_array($activityType, ['find_word', 'find_the_word'], true)
                    ? 'Students look at the picture and choose the correct word from several options.'
                    : 'Students see an incorrect spelling and remove the extra/wrong letter to make the correct word.' ?>
            </div>
        </section>

        <?php elseif (in_array($activityType, ['word_builder', 'word_unscramble'], true)): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">
                Choose how many words students practise and how letters behave.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Words per Session</span>
                    <select class="eas-select" name="word_count">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $count): ?>
                        <option
                            value="<?= $count ?>"
                            <?= (int)$settings['word_count'] === $count ? 'selected' : '' ?>
                        >
                            <?= $count === 100 ? 'All' : $count ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Select how many words students complete in one session.
                    </small>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="passing_score"
                        min="0"
                        max="100"
                        value="<?= (int)$settings['passing_score'] ?>"
                    >
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check">
                    <input
                        type="checkbox"
                        name="shuffle"
                        value="1"
                        <?= !empty($settings['shuffle']) ? 'checked' : '' ?>
                    >
                    Shuffle Letters
                </label>

                <label class="eas-check">
                    <input
                        type="checkbox"
                        name="show_image"
                        value="1"
                        <?= !empty($settings['show_image']) ? 'checked' : '' ?>
                    >
                    Show Image
                </label>

                <label class="eas-check">
                    <input
                        type="checkbox"
                        name="letter_voice"
                        value="1"
                        <?= !empty($settings['letter_voice']) ? 'checked' : '' ?>
                    >
                    Speak Letter Names
                </label>

                <label class="eas-check">
                    <input
                        type="checkbox"
                        name="allow_retry"
                        value="1"
                        <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>
                    >
                    Allow Try Again
                </label>

                <label class="eas-check">
                    <input
                        type="checkbox"
                        name="show_progress"
                        value="1"
                        <?= !empty($settings['show_progress']) ? 'checked' : '' ?>
                    >
                    Show Progress
                </label>
            </div>

            <div class="eas-note" style="margin-top:14px">
                <?= $activityType === 'word_builder'
                    ? 'Students tap letters to build the word. Tapping a letter can play its English letter name.'
                    : 'Students rearrange shuffled letters to form the correct word.' ?>
            </div>
        </section>

        <?php elseif ($activityType === 'memory'): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">Choose the number of pairs, layout and timing.</p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Items / Pairs</span>
                    <select class="eas-select" name="pairs">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $pairs): ?>
                        <option
                            value="<?= $pairs ?>"
                            <?= (int)$settings['pairs'] === $pairs ? 'selected' : '' ?>
                        >
                            <?= $pairs === 100 ? 'All' : $pairs ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </label>

                <label class="eas-field">
                    <span>Layout</span>
                    <select class="eas-select" name="layout">
                        <option value="auto" <?= $settings['layout'] === 'auto' ? 'selected' : '' ?>>Auto</option>
                        <option value="2-columns" <?= $settings['layout'] === '2-columns' ? 'selected' : '' ?>>2 columns</option>
                        <option value="3-columns" <?= $settings['layout'] === '3-columns' ? 'selected' : '' ?>>3 columns</option>
                    </select>
                </label>

                <label class="eas-field">
                    <span>Time limit (seconds)</span>
                    <input class="eas-input" type="number" name="time_limit" min="10" max="600" value="<?= (int)$settings['time_limit'] ?>">
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="shuffle" value="1" <?= !empty($settings['shuffle']) ? 'checked' : '' ?>> Shuffle</label>
                <label class="eas-check"><input type="checkbox" name="timer_enabled" value="1" <?= !empty($settings['timer_enabled']) ? 'checked' : '' ?>> Enable timer</label>
                <label class="eas-check"><input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>> Allow replay</label>
            </div>
        </section>

        <?php elseif ($activityType === 'matching'): ?>
        <section class="eas-section">
            <h3>Matching Settings</h3>
            <p class="eas-section-desc">
                Choose how many pairs students match and how Matching behaves.
            </p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Pairs per Session</span>
                    <select class="eas-select" name="pairs">
                        <?php foreach ([4, 5, 6, 7, 8, 9, 10, 100] as $pairs): ?>
                        <option
                            value="<?= $pairs ?>"
                            <?= (int)$settings['pairs'] === $pairs ? 'selected' : '' ?>
                        >
                            <?= $pairs === 100 ? 'All' : $pairs ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="eas-help">
                        Choose 4–10 pairs or All for one Matching session.
                    </small>
                </label>

                <label class="eas-field">
                    <span>Passing Score (%)</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="passing_score"
                        min="0"
                        max="100"
                        value="<?= (int)$settings['passing_score'] ?>"
                    >
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check">
                    <input type="checkbox" name="shuffle" value="1" <?= !empty($settings['shuffle']) ? 'checked' : '' ?>>
                    Shuffle Cards
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="word_audio_on_tap" value="1" <?= !empty($settings['word_audio_on_tap']) ? 'checked' : '' ?>>
                    Listen when tapping a Word
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_image" value="1" <?= !empty($settings['show_image']) ? 'checked' : '' ?>>
                    Show Images
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_word" value="1" <?= !empty($settings['show_word']) ? 'checked' : '' ?>>
                    Show Words
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="auto_next" value="1" <?= !empty($settings['auto_next']) ? 'checked' : '' ?>>
                    Auto Next
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>>
                    Show Progress
                </label>

                <label class="eas-check">
                    <input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>>
                    Allow Try Again
                </label>
            </div>
        </section>

        <?php elseif ($activityType === 'quiz'): ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">Configure question count, answer time and pass requirements.</p>

            <div class="eas-grid">
                <label class="eas-field">
                    <span>Questions</span>
                    <input class="eas-input" type="number" name="question_count" min="1" max="100" value="<?= (int)$settings['question_count'] ?>">
                </label>
                <label class="eas-field">
                    <span>Passing score (%)</span>
                    <input class="eas-input" type="number" name="passing_score" min="0" max="100" value="<?= (int)$settings['passing_score'] ?>">
                </label>
                <label class="eas-field">
                    <span>Answer time (seconds)</span>
                    <input class="eas-input" type="number" name="answer_time" min="5" max="300" value="<?= (int)$settings['answer_time'] ?>">
                </label>
            </div>

            <div class="eas-checks" style="margin-top:14px">
                <label class="eas-check"><input type="checkbox" name="shuffle" value="1" <?= !empty($settings['shuffle']) ? 'checked' : '' ?>> Shuffle questions</label>
                <label class="eas-check"><input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>> Show progress</label>
                <label class="eas-check"><input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>> Allow Try Again</label>
            </div>
        </section>

        <?php else: ?>
        <section class="eas-section">
            <h3>Activity Settings</h3>
            <p class="eas-section-desc">General behaviour for this Activity.</p>

            <div class="eas-checks">
                <label class="eas-check"><input type="checkbox" name="show_progress" value="1" <?= !empty($settings['show_progress']) ? 'checked' : '' ?>> Show progress</label>
                <label class="eas-check"><input type="checkbox" name="allow_retry" value="1" <?= !empty($settings['allow_retry']) ? 'checked' : '' ?>> Allow Try Again</label>
            </div>
        </section>
        <?php endif; ?>


        <section class="eas-section">
            <h3>Completion &amp; Rewards</h3>
            <p class="eas-section-desc">
                Set the reward for the first completion and the smaller reward for eligible practice sessions.
                The Passing Score is configured only once in Activity Settings above.
            </p>

            <div class="eas-reward-grid">
                <label class="eas-field">
                    <span>Completion XP</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="xp_reward"
                        min="0"
                        max="10000"
                        value="<?= (int)$settings['xp_reward'] ?>"
                    >
                    <small class="eas-help">Awarded only on the first successful completion.</small>
                </label>

                <label class="eas-field">
                    <span>Practice XP</span>
                    <input
                        class="eas-input"
                        type="number"
                        name="practice_xp"
                        min="0"
                        max="100"
                        value="<?= (int)$settings['practice_xp'] ?>"
                    >
                    <small class="eas-help">A small reward for eligible review attempts after completion.</small>
                </label>
            </div>
        </section>

        <section class="eas-section">
            <h3>Student Instructions</h3>
            <p class="eas-section-desc">Optional instructions shown before students start this Activity.</p>
            <label class="eas-field">
                <span>Instructions</span>
                <textarea class="eas-textarea" name="student_instructions" placeholder="<?= in_array($activityType, ['listen_repeat', 'pronunciation'], true)
                    ? 'Example: Listen carefully and repeat each word clearly.'
                    : 'Example: Tap the picture to listen. Repeat after the audio.' ?>"><?= htmlspecialchars((string)$settings['student_instructions'], ENT_QUOTES, 'UTF-8') ?></textarea>
            </label>
        </section>

        <div class="eas-note">
            Các cài đặt được lưu riêng cho Activity này. Chúng không thay đổi Game Template hoặc nội dung của Flashcard Set dùng chung.
        </div>

        <div class="eas-footer">
            <a class="button button-secondary" href="../lesson-activities/index.php?lesson_id=<?= (int)$activity['lesson_id'] ?>">Cancel</a>
            <button type="submit" class="button button-primary">Save Settings</button>
        </div>
    </form>
</div>


<script>
(function () {
    function hideGlobalAddButton() {
        document.querySelectorAll('button, a').forEach(function (element) {
            var label = (element.textContent || '').replace(/\s+/g, ' ').trim();

            if (label === 'Add' || label === '+ Add') {
                element.style.setProperty('display', 'none', 'important');
            }
        });
    }

    hideGlobalAddButton();

    const contentSelect = document.getElementById('contentSelect');
    const editSentenceSetButton = document.getElementById('editSentenceSetButton');
    const previewSentenceSetButton = document.getElementById('previewSentenceSetButton');
    const editDialogueSetButton = document.getElementById('editDialogueSetButton');
    const activityId = <?= (int)$activityId ?>;

    function updateSentenceSetButtons() {
        if (!contentSelect) {
            return;
        }

        const setId = parseInt(contentSelect.value || '0', 10);
        const hasSet = Number.isInteger(setId) && setId > 0;

        if (editSentenceSetButton) {
            editSentenceSetButton.href = hasSet
                ? '../sentence-sets/create.php?id=' + setId
                    + '&return_activity_id=' + activityId
                : '#';
            editSentenceSetButton.setAttribute(
                'aria-disabled',
                hasSet ? 'false' : 'true'
            );
        }

        if (previewSentenceSetButton) {
            previewSentenceSetButton.href = hasSet
                ? '../sentence-sets/detail.php?id=' + setId
                    + '&return_activity_id=' + activityId
                : '#';
            previewSentenceSetButton.setAttribute(
                'aria-disabled',
                hasSet ? 'false' : 'true'
            );
        }
    }

    contentSelect?.addEventListener('change', updateSentenceSetButtons);
    updateSentenceSetButtons();

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', hideGlobalAddButton);
    }

    window.addEventListener('load', hideGlobalAddButton);
    setTimeout(hideGlobalAddButton, 250);
})();
</script>



<script>
document.addEventListener('DOMContentLoaded', function () {
});
</script>

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