<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * Teacher > Lessons > Activity Editor
 *
 * Architecture:
 * Word Library -> Flashcard Set -> Lesson Activity -> Student Game
 *
 * Supports:
 * - Create Activity from lesson_id + type
 * - Edit Activity by id
 * - Select one Flashcard Set
 * - Preview words from the selected set
 * - Dynamic compatibility with existing table columns
 */

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

$pdo = getDbConnection();

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

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

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

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

    return null;
}

function safeActivityType(string $type): string
{
    $allowed = [
        'flashcards',
        'listen_repeat',
        'pronunciation',
        'matching',
        'memory',
        'quiz',
        'speaking',
        'worksheet',
        'game',
        'vocabulary',
        'typing',
        'word_search',
        'sentence_builder',
        'dialogue',
        'ask_answer',
        'word_builder',
        'word_unscramble',
        'find_word',
        'fix_word',
        'activity',
    ];

    return in_array($type, $allowed, true) ? $type : 'activity';
}

function defaultActivityTitle(string $type): string
{
    return match ($type) {
        'flashcards' => 'Flashcards',
        'listen_repeat', 'pronunciation' => 'Listen & Repeat',
        'matching' => 'Matching',
        'memory' => 'Memory',
        'quiz' => 'Quiz',
        'speaking' => 'Speaking',
        'worksheet' => 'Worksheet',
        'game' => 'Game',
        'vocabulary' => 'Word List',
        'typing' => 'Typing',
        'word_search' => 'Word Search',
        'sentence_builder' => 'Sentence Builder',
        'dialogue' => 'Dialogue',
        'ask_answer' => 'Ask & Answer',
        'word_builder' => 'Word Builder',
        'word_unscramble' => 'Word Unscramble',
        'find_word' => 'Find the Word',
        'fix_word' => 'Fix the Word',
        default => 'Activity',
    };
}

function activityIcon(string $type): string
{
    return match ($type) {
        'flashcards' => '🃏',
        'listen_repeat', 'pronunciation' => '🔊',
        'matching' => '🧩',
        'memory' => '🧠',
        'quiz' => '🎯',
        'speaking' => '🎤',
        'worksheet' => '📄',
        'game' => '🎮',
        'vocabulary' => '🔤',
        'typing' => '⌨️',
        'word_search' => '🔎',
        'sentence_builder' => '🧱',
        'dialogue', 'ask_answer' => '💬',
        'word_builder' => '🔤',
        'word_unscramble' => '🔀',
        'find_word' => '🖼️',
        'fix_word' => '✏️',
        default => '🎯',
    };
}

$activityColumns = tableColumns($pdo, 'activities');
$lessonColumns = tableColumns($pdo, 'lessons');
$unitColumns = tableColumns($pdo, 'units');
$setColumns = tableColumns($pdo, 'flashcard_sets');
$sentenceSetColumns = tableColumns($pdo, 'sentence_sets');
$dialogueSetColumns = tableColumns($pdo, 'dialogue_sets');
$dialogueItemColumns = tableColumns($pdo, 'dialogue_items');

$hasFlashcardSets = $setColumns !== [];
$hasSentenceSets = $sentenceSetColumns !== [];
$hasSentenceSetLink = isset($activityColumns['sentence_set_id']);
$hasDialogueSets = $dialogueSetColumns !== [] && $dialogueItemColumns !== [];
$hasActivitySetLink = isset($activityColumns['flashcard_set_id']);
$hasDialogueSetLink = isset($activityColumns['dialogue_set_id']);

$activityId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$lessonId = filter_input(INPUT_GET, 'lesson_id', FILTER_VALIDATE_INT);
$typeFromUrl = safeActivityType(trim((string)($_GET['type'] ?? 'activity')));

$isNew = !$activityId;
$activity = null;
$error = '';
$success = isset($_GET['saved']);

if (!$isNew) {
    $titleSelect = isset($activityColumns['title'])
        ? 'a.title'
        : (isset($activityColumns['name']) ? 'a.name' : "'Activity'");

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

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

    $xpSelect = isset($activityColumns['xp_reward']) ? 'a.xp_reward' : '0';
    $statusSelect = isset($activityColumns['status']) ? 'a.status' : "'active'";
    $sortSelect = isset($activityColumns['sort_order']) ? 'a.sort_order' : '0';
    $setSelect = $hasActivitySetLink ? 'a.flashcard_set_id' : 'NULL';
    $sentenceSetSelect = $hasSentenceSetLink ? 'a.sentence_set_id' : 'NULL';
    $dialogueSetSelect = $hasDialogueSetLink ? 'a.dialogue_set_id' : 'NULL';

    $stmt = $pdo->prepare("
        SELECT
            a.id,
            a.lesson_id,
            {$titleSelect} AS activity_title,
            {$typeSelect} AS activity_type,
            {$descriptionSelect} AS activity_description,
            {$xpSelect} AS xp_reward,
            {$statusSelect} AS activity_status,
            {$sortSelect} AS sort_order,
            {$setSelect} AS flashcard_set_id,
            {$sentenceSetSelect} AS sentence_set_id,
            {$dialogueSetSelect} AS dialogue_set_id
        FROM activities a
        WHERE a.id = ?
        LIMIT 1
    ");
    $stmt->execute([$activityId]);
    $activity = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$activity) {
        http_response_code(404);
        exit('Activity not found.');
    }

    $lessonId = (int)$activity['lesson_id'];
} elseif (!$lessonId) {
    header('Location: ../books/index.php');
    exit;
}

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

$unitLevelSelect = isset($unitColumns['level_id']) ? 'u.level_id' : 'NULL';

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

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

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

if (!$canManageLesson) {
    $_SESSION['lessons_message'] = 'You do not have permission to edit Activities in this Lesson.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location: detail.php?id=' . (int)$lesson['id']);
    exit;
}

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

    if (!$bookAccessStmt->fetchColumn()) {
        http_response_code(403);
        exit('You are not allowed to manage Activities in this Book.');
    }
}

/* ---------- Flashcard Sets ---------- */

$flashcardSets = [];
$setPreviewMap = [];

if ($hasFlashcardSets) {
    $setLabelColumn = firstExistingColumn(
        $setColumns,
        ['title', 'name', 'set_name', 'label']
    ) ?? 'id';

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

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

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

    // Detect common many-to-many relation table.
    $relationTable = null;
    foreach (['flashcard_set_words', 'flashcard_set_items', 'set_words'] as $candidate) {
        if (tableExists($pdo, $candidate)) {
            $relationTable = $candidate;
            break;
        }
    }

    if ($relationTable !== null && tableExists($pdo, 'words')) {
        $relationColumns = tableColumns($pdo, $relationTable);
        $wordColumns = tableColumns($pdo, 'words');

        $setFk = firstExistingColumn(
            $relationColumns,
            ['flashcard_set_id', 'set_id']
        );
        $wordFk = firstExistingColumn(
            $relationColumns,
            ['word_id', 'vocabulary_id']
        );
        $wordLabel = firstExistingColumn(
            $wordColumns,
            ['word', 'term', 'english', 'text', 'title', 'name']
        );
        $wordImage = firstExistingColumn(
            $wordColumns,
            ['image', 'image_path', 'image_url', 'thumbnail']
        );

        if ($setFk && $wordFk && $wordLabel) {
            $imageSelect = $wordImage
                ? "w.`{$wordImage}` AS word_image"
                : 'NULL AS word_image';

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

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

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


/* ---------- Sentence Sets ---------- */
$sentenceSets = [];
$sentencePreviewMap = [];

if ($hasSentenceSets) {
    $sentenceLabelColumn = firstExistingColumn(
        $sentenceSetColumns,
        ['title', 'name', 'set_name', 'label']
    ) ?? 'id';

    $lessonBookId = (int)($lesson['book_id'] ?? 0);
    $lessonLevelId = (int)($lesson['level_id'] ?? 0);

    /*
     * Sentence Builder + Speaking use Sentence Sets.
     * Only Sets explicitly linked to BOTH the current Lesson Book and Level
     * are selectable. Unlinked legacy Sets are intentionally excluded here.
     */
    if (
        $lessonBookId > 0
        && $lessonLevelId > 0
        && tableExists($pdo, 'sentence_set_books')
        && tableExists($pdo, 'sentence_set_levels')
    ) {
        $sentenceStatusSql = isset($sentenceSetColumns['status'])
            ? " AND ss.status = 'active'"
            : '';

        $stmt = $pdo->prepare("
            SELECT
                ss.id,
                ss.`{$sentenceLabelColumn}` AS set_label
            FROM sentence_sets ss
            WHERE EXISTS (
                SELECT 1
                FROM sentence_set_books ssb
                WHERE ssb.sentence_set_id = ss.id
                  AND ssb.book_id = ?
            )
              AND EXISTS (
                SELECT 1
                FROM sentence_set_levels sslev
                WHERE sslev.sentence_set_id = ss.id
                  AND sslev.level_id = ?
            )
              {$sentenceStatusSql}
            ORDER BY ss.`{$sentenceLabelColumn}` ASC, ss.id ASC
        ");
        $stmt->execute([$lessonBookId, $lessonLevelId]);
        $sentenceSets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /*
     * Real Sentence Set relation in this project:
     * sentence_set_sentences(sentence_set_id, sentence_id, ...)
     */
    if (tableExists($pdo, 'sentence_set_sentences')) {
        $itemCols = tableColumns($pdo, 'sentence_set_sentences');
        $setFk = firstExistingColumn($itemCols, ['sentence_set_id', 'set_id']);
        $sentenceFk = firstExistingColumn($itemCols, ['sentence_id']);

        $sentenceSourceTable = null;
        foreach (['sentences', 'sentence_library', 'sentence_items'] as $candidate) {
            if (tableExists($pdo, $candidate)) {
                $candidateCols = tableColumns($pdo, $candidate);
                if (isset($candidateCols['id'])) {
                    $sentenceSourceTable = $candidate;
                    break;
                }
            }
        }

        if ($setFk && $sentenceFk && $sentenceSourceTable !== null) {
            $sentenceCols = tableColumns($pdo, $sentenceSourceTable);
            $textCol = firstExistingColumn(
                $sentenceCols,
                ['sentence', 'sentence_text', 'text', 'english', 'content', 'title']
            );

            if ($textCol) {
                $order = isset($itemCols['sort_order'])
                    ? 'sss.sort_order ASC, sss.id ASC'
                    : 'sss.id ASC';

                $rows = $pdo->query("
                    SELECT
                        sss.`{$setFk}` AS set_id,
                        s.id AS sentence_id,
                        s.`{$textCol}` AS sentence_text
                    FROM sentence_set_sentences sss
                    INNER JOIN `{$sentenceSourceTable}` s
                            ON s.id = sss.`{$sentenceFk}`
                    ORDER BY sss.`{$setFk}` ASC, {$order}
                ")->fetchAll(PDO::FETCH_ASSOC);

                foreach ($rows as $row) {
                    $sentencePreviewMap[(int)$row['set_id']][] = [
                        'id' => (int)$row['sentence_id'],
                        'text' => (string)$row['sentence_text'],
                    ];
                }
            }
        }
    }
}


/* ---------- Dialogue Sets ---------- */

$dialogueSets = [];
$dialoguePreviewMap = [];

if ($hasDialogueSets) {
    $dialogueSets = $pdo->query("
        SELECT id, title AS set_label
        FROM dialogue_sets
        WHERE status = 'active'
        ORDER BY title ASC, id ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

    $dialogueRows = $pdo->query("
        SELECT
            id,
            dialogue_set_id,
            sort_order,
            speaker_name,
            prompt_text,
            correct_response,
            image_path
        FROM dialogue_items
        WHERE status = 'active'
        ORDER BY dialogue_set_id ASC, sort_order ASC, id ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($dialogueRows as $row) {
        $dialoguePreviewMap[(int)$row['dialogue_set_id']][] = [
            'id' => (int)$row['id'],
            'speaker' => (string)$row['speaker_name'],
            'prompt' => (string)$row['prompt_text'],
            'response' => (string)$row['correct_response'],
            'image' => (string)($row['image_path'] ?? ''),
        ];
    }
}


/*
 * Keep Dialogue Set in Activity Editor and Activity Settings synchronized.
 * Runtime/Settings may read a separate activity_settings row, so saving the
 * Activity must update that link too. This removes the need to open Settings
 * and press Save Settings a second time.
 */
function syncDialogueSetToActivitySettings(PDO $pdo, int $activityId, int $dialogueSetId): void
{
    if ($activityId <= 0 || $dialogueSetId <= 0 || !tableExists($pdo, 'activity_settings')) {
        return;
    }

    $columns = tableColumns($pdo, 'activity_settings');
    if (!isset($columns['activity_id'])) {
        return;
    }

    $dialogueColumn = firstExistingColumn(
        $columns,
        ['dialogue_set_id', 'content_set_id', 'set_id']
    );

    if ($dialogueColumn === null) {
        return;
    }

    $check = $pdo->prepare("SELECT 1 FROM activity_settings WHERE activity_id = ? LIMIT 1");
    $check->execute([$activityId]);

    if ($check->fetchColumn()) {
        $assignments = ["`{$dialogueColumn}` = ?"];
        $values = [$dialogueSetId];

        if (isset($columns['updated_at'])) {
            $assignments[] = 'updated_at = NOW()';
        }

        $values[] = $activityId;
        $stmt = $pdo->prepare(
            "UPDATE activity_settings SET " . implode(', ', $assignments) . " WHERE activity_id = ?"
        );
        $stmt->execute($values);
        return;
    }

    $fields = ['activity_id', $dialogueColumn];
    $placeholders = ['?', '?'];
    $values = [$activityId, $dialogueSetId];

    if (isset($columns['created_at'])) {
        $fields[] = 'created_at';
        $placeholders[] = 'NOW()';
    }
    if (isset($columns['updated_at'])) {
        $fields[] = 'updated_at';
        $placeholders[] = 'NOW()';
    }

    $sql = "INSERT INTO activity_settings (`"
         . implode('`,`', $fields)
         . "`) VALUES ("
         . implode(',', $placeholders)
         . ")";

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

$formTitle = $isNew
    ? defaultActivityTitle($typeFromUrl)
    : (string)$activity['activity_title'];

$formType = $isNew
    ? $typeFromUrl
    : safeActivityType((string)$activity['activity_type']);

$formDescription = $isNew ? '' : (string)$activity['activity_description'];
$formXp = $isNew ? 10 : (int)$activity['xp_reward'];
$formStatus = $isNew ? 'active' : (string)$activity['activity_status'];
$formSortOrder = $isNew ? 1 : (int)$activity['sort_order'];
$formFlashcardSetId = $isNew ? 0 : (int)($activity['flashcard_set_id'] ?? 0);
$formSentenceSetId = $isNew ? 0 : (int)($activity['sentence_set_id'] ?? 0);
$formDialogueSetId = $isNew ? 0 : (int)($activity['dialogue_set_id'] ?? 0);

// For a new Dialogue activity, preselect the first active Dialogue Set.
// This makes the visible default a real submitted value instead of showing
// a set in another screen while saving NULL into activities.dialogue_set_id.
if ($isNew
    && in_array($formType, ['dialogue', 'ask_answer'], true)
    && $formDialogueSetId <= 0
    && !empty($dialogueSets)
) {
    $formDialogueSetId = (int)$dialogueSets[0]['id'];
}

// For a new Sentence Builder / Speaking activity, preselect the first
// Sentence Set that belongs to this Lesson's Book + Level.
if ($isNew
    && in_array($formType, ['sentence_builder', 'speaking'], true)
    && $formSentenceSetId <= 0
    && !empty($sentenceSets)
) {
    $formSentenceSetId = (int)$sentenceSets[0]['id'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formTitle = trim((string)($_POST['title'] ?? ''));
    $formType = safeActivityType(trim((string)($_POST['activity_type'] ?? 'activity')));
    $formDescription = trim((string)($_POST['description'] ?? ''));
    $formXp = max(0, (int)($_POST['xp_reward'] ?? 0));
    $formStatus = ($_POST['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active';
    $formSortOrder = max(0, (int)($_POST['sort_order'] ?? 0));
    $formFlashcardSetId = max(0, (int)($_POST['flashcard_set_id'] ?? 0));
    $formSentenceSetId = max(0, (int)($_POST['sentence_set_id'] ?? 0));
    $formDialogueSetId = max(0, (int)($_POST['dialogue_set_id'] ?? 0));

    if ($formTitle === '') {
        $error = 'Please enter an activity title.';
    } elseif (in_array($formType, ['sentence_builder', 'speaking'], true) && $formSentenceSetId <= 0) {
        $error = 'Please select a Sentence Set.';
    } elseif (in_array($formType, ['sentence_builder', 'speaking'], true) && $formSentenceSetId > 0) {
        if (!$hasSentenceSetLink) {
            $error = 'Bảng activities chưa có cột sentence_set_id.';
        } else {
            $setCheck = $pdo->prepare("
                SELECT ss.id
                FROM sentence_sets ss
                WHERE ss.id = ?
                  AND " . (isset($sentenceSetColumns['status']) ? "ss.status = 'active' AND " : "") . "
                      EXISTS (
                          SELECT 1
                          FROM sentence_set_books ssb
                          WHERE ssb.sentence_set_id = ss.id
                            AND ssb.book_id = ?
                      )
                  AND EXISTS (
                          SELECT 1
                          FROM sentence_set_levels sslev
                          WHERE sslev.sentence_set_id = ss.id
                            AND sslev.level_id = ?
                      )
                LIMIT 1
            ");
            $setCheck->execute([
                $formSentenceSetId,
                (int)($lesson['book_id'] ?? 0),
                (int)($lesson['level_id'] ?? 0),
            ]);

            if (!$setCheck->fetchColumn()) {
                $error = 'Sentence Set không thuộc đúng Book + Level của Lesson này.';
            }
        }
    } elseif (in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId <= 0) {
        $error = 'Please select a Dialogue Set.';
    } elseif (in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId > 0) {
        $setCheck = $pdo->prepare("SELECT id FROM dialogue_sets WHERE id = ? AND status = 'active' LIMIT 1");
        $setCheck->execute([$formDialogueSetId]);
        if (!$setCheck->fetchColumn()) {
            $error = 'The selected Dialogue Set does not exist.';
        } elseif (!$hasDialogueSetLink) {
            $error = 'Bảng activities chưa có cột dialogue_set_id.';
        }
    } elseif (!in_array($formType, ['dialogue', 'ask_answer', 'sentence_builder', 'speaking'], true) && $hasActivitySetLink && $formFlashcardSetId > 0) {
        $setCheck = $pdo->prepare("SELECT id FROM flashcard_sets WHERE id = ? LIMIT 1");
        $setCheck->execute([$formFlashcardSetId]);
        if (!$setCheck->fetchColumn()) {
            $error = 'The selected Flashcard Set does not exist.';
        }
    }

    if ($error === '') {
        try {
            if ($isNew) {
                $fields = ['lesson_id'];
                $values = [$lessonId];
                $placeholders = ['?'];

                if (isset($activityColumns['title'])) {
                    $fields[] = 'title';
                    $values[] = $formTitle;
                    $placeholders[] = '?';
                } elseif (isset($activityColumns['name'])) {
                    $fields[] = 'name';
                    $values[] = $formTitle;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['activity_type'])) {
                    $fields[] = 'activity_type';
                    $values[] = $formType;
                    $placeholders[] = '?';
                } elseif (isset($activityColumns['type'])) {
                    $fields[] = 'type';
                    $values[] = $formType;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['description'])) {
                    $fields[] = 'description';
                    $values[] = $formDescription !== '' ? $formDescription : null;
                    $placeholders[] = '?';
                } elseif (isset($activityColumns['instructions'])) {
                    $fields[] = 'instructions';
                    $values[] = $formDescription !== '' ? $formDescription : null;
                    $placeholders[] = '?';
                }

                if ($hasActivitySetLink) {
                    $fields[] = 'flashcard_set_id';
                    $values[] = $formFlashcardSetId > 0 ? $formFlashcardSetId : null;
                    $placeholders[] = '?';
                }

                if ($hasSentenceSetLink) {
                    $fields[] = 'sentence_set_id';
                    $values[] = in_array($formType, ['sentence_builder', 'speaking'], true) && $formSentenceSetId > 0 ? $formSentenceSetId : null;
                    $placeholders[] = '?';
                }

                if ($hasDialogueSetLink) {
                    $fields[] = 'dialogue_set_id';
                    $values[] = in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId > 0 ? $formDialogueSetId : null;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['xp_reward'])) {
                    $fields[] = 'xp_reward';
                    $values[] = $formXp;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['status'])) {
                    $fields[] = 'status';
                    $values[] = $formStatus;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['sort_order'])) {
                    $fields[] = 'sort_order';
                    $values[] = $formSortOrder;
                    $placeholders[] = '?';
                }

                if (isset($activityColumns['created_at'])) {
                    $fields[] = 'created_at';
                    $placeholders[] = 'NOW()';
                }

                if (isset($activityColumns['updated_at'])) {
                    $fields[] = 'updated_at';
                    $placeholders[] = 'NOW()';
                }

                $sql = "
                    INSERT INTO activities
                    (`" . implode('`,`', $fields) . "`)
                    VALUES (" . implode(',', $placeholders) . ")
                ";

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

                $newId = (int)$pdo->lastInsertId();

                if (in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId > 0) {
                    syncDialogueSetToActivitySettings($pdo, $newId, $formDialogueSetId);
                }

                header('Location: activity.php?id=' . $newId . '&saved=1');
                exit;
            }

            $assignments = [];
            $values = [];

            if (isset($activityColumns['title'])) {
                $assignments[] = 'title = ?';
                $values[] = $formTitle;
            } elseif (isset($activityColumns['name'])) {
                $assignments[] = 'name = ?';
                $values[] = $formTitle;
            }

            if (isset($activityColumns['activity_type'])) {
                $assignments[] = 'activity_type = ?';
                $values[] = $formType;
            } elseif (isset($activityColumns['type'])) {
                $assignments[] = 'type = ?';
                $values[] = $formType;
            }

            if (isset($activityColumns['description'])) {
                $assignments[] = 'description = ?';
                $values[] = $formDescription !== '' ? $formDescription : null;
            } elseif (isset($activityColumns['instructions'])) {
                $assignments[] = 'instructions = ?';
                $values[] = $formDescription !== '' ? $formDescription : null;
            }

            if ($hasActivitySetLink) {
                $assignments[] = 'flashcard_set_id = ?';
                $values[] = $formFlashcardSetId > 0 ? $formFlashcardSetId : null;
            }

            if ($hasSentenceSetLink) {
                $assignments[] = 'sentence_set_id = ?';
                $values[] = in_array($formType, ['sentence_builder', 'speaking'], true) && $formSentenceSetId > 0 ? $formSentenceSetId : null;
            }

            if ($hasDialogueSetLink) {
                $assignments[] = 'dialogue_set_id = ?';
                $values[] = in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId > 0 ? $formDialogueSetId : null;
            }

            if (isset($activityColumns['xp_reward'])) {
                $assignments[] = 'xp_reward = ?';
                $values[] = $formXp;
            }

            if (isset($activityColumns['status'])) {
                $assignments[] = 'status = ?';
                $values[] = $formStatus;
            }

            if (isset($activityColumns['sort_order'])) {
                $assignments[] = 'sort_order = ?';
                $values[] = $formSortOrder;
            }

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

            $values[] = $activityId;

            $stmt = $pdo->prepare("
                UPDATE activities
                SET " . implode(', ', $assignments) . "
                WHERE id = ?
            ");
            $stmt->execute($values);

            if (in_array($formType, ['dialogue', 'ask_answer'], true) && $formDialogueSetId > 0) {
                syncDialogueSetToActivitySettings($pdo, (int)$activityId, $formDialogueSetId);
            }

            header('Location: activity.php?id=' . (int)$activityId . '&saved=1');
            exit;
        } catch (Throwable $e) {
            error_log('EnglishSpeak activity.php: ' . $e->getMessage());
            $error = 'Unable to save the Activity.';
        }
    }
}

$pageTitle = $isNew ? 'New ' . defaultActivityTitle($formType) : 'Edit Activity';
$pageSubtitle = (string)$lesson['lesson_title'];
$activeTeacherNav = 'content';

$activityTypes = [
    'flashcards' => ['icon' => '🃏', 'label' => 'Flashcards'],
    'listen_repeat' => ['icon' => '🔊', 'label' => 'Listen & Repeat'],
    'matching' => ['icon' => '🧩', 'label' => 'Matching'],
    'memory' => ['icon' => '🧠', 'label' => 'Memory'],
    'quiz' => ['icon' => '🎯', 'label' => 'Quiz'],
    'speaking' => ['icon' => '🎤', 'label' => 'Speaking'],
    'typing' => ['icon' => '⌨️', 'label' => 'Typing'],
    'word_search' => ['icon' => '🔎', 'label' => 'Word Search'],
    'sentence_builder' => ['icon' => '🧱', 'label' => 'Sentence Builder'],
    'dialogue' => ['icon' => '💬', 'label' => 'Dialogue'],
    'ask_answer' => ['icon' => '❓', 'label' => 'Ask & Answer'],
    'word_builder' => ['icon' => '🔤', 'label' => 'Word Builder'],
    'word_unscramble' => ['icon' => '🔀', 'label' => 'Word Unscramble'],
    'find_word' => ['icon' => '🖼️', 'label' => 'Find the Word'],
    'fix_word' => ['icon' => '✏️', 'label' => 'Fix the Word'],
    'worksheet' => ['icon' => '📄', 'label' => 'Worksheet'],
    'game' => ['icon' => '🎮', 'label' => 'Game'],
    'vocabulary' => ['icon' => '🔤', 'label' => 'Word List'],
];

ob_start();
?>

<style>
.ae-page{display:grid;gap:18px}
.ae-head{display:flex;justify-content:space-between;align-items:flex-start;gap:18px}
.ae-breadcrumb{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:8px;color:var(--muted);font-size:12px}
.ae-breadcrumb a{color:inherit;text-decoration:none}
.ae-title{display:flex;align-items:center;gap:12px}
.ae-icon{display:grid;width:48px;height:48px;place-items:center;border-radius:14px;background:#eef4ff;font-size:24px}
.ae-title h2{margin:0}
.ae-layout{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:18px;align-items:start}
.ae-card{padding:20px;border:1px solid var(--border);border-radius:16px;background:var(--surface)}
.ae-grid{display:grid;grid-template-columns:1fr 1fr;gap:15px}
.ae-full{grid-column:1/-1}
.ae-save{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}
.ae-notice{padding:13px 15px;border-radius:12px}
.ae-success{background:#ecfdf3;border:1px solid #bbf7d0;color:#166534}
.ae-error{background:#fef2f2;border:1px solid #fecaca;color:#991b1b}
.ae-warning{background:#fffbeb;border:1px solid #fde68a;color:#92400e;margin-bottom:15px}
.ae-preview-head{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:12px}
.ae-preview-count{padding:5px 9px;border-radius:999px;background:#eef4ff;color:#2563eb;font-size:12px;font-weight:750}
.ae-word-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;max-height:330px;overflow:auto}
.ae-word{display:flex;align-items:center;gap:9px;padding:9px;border:1px solid var(--border);border-radius:11px;background:#fff}
.ae-word-image{display:grid;place-items:center;width:38px;height:38px;flex:0 0 38px;border-radius:9px;background:#f1f5f9;overflow:hidden}
.ae-word-image img{width:100%;height:100%;object-fit:cover}
.ae-word strong{font-size:13px}
.ae-empty{padding:28px 12px;text-align:center;color:var(--muted);border:1px dashed var(--border);border-radius:12px}
@media(max-width:900px){.ae-layout,.ae-grid{grid-template-columns:1fr}.ae-full{grid-column:auto}.ae-head{flex-direction:column}}
@media(max-width:520px){.ae-word-grid{grid-template-columns:1fr}}
</style>

<div class="ae-page">
    <div class="ae-head">
        <div>
            <div class="ae-breadcrumb">
                <a href="../books/index.php?book_id=<?= (int)$lesson['book_id'] ?>">
                    <?= htmlspecialchars((string)$lesson['book_name']) ?>
                </a>
                <span>›</span>
                <span><?= htmlspecialchars((string)$lesson['unit_number']) ?></span>
                <span>›</span>
                <a href="detail.php?id=<?= (int)$lessonId ?>">
                    <?= htmlspecialchars((string)$lesson['lesson_title']) ?>
                </a>
                <span>›</span>
                <strong><?= htmlspecialchars($formTitle) ?></strong>
            </div>

            <div class="ae-title">
                <div class="ae-icon"><?= activityIcon($formType) ?></div>
                <div>
                    <span class="section-kicker"><?= $isNew ? 'New '.htmlspecialchars(defaultActivityTitle($formType)) : 'Activity Editor' ?></span>
                    <h2><?= htmlspecialchars($formTitle) ?></h2>
                </div>
            </div>
        </div>

        <a href="detail.php?id=<?= (int)$lessonId ?>" class="button button-secondary">
            ← Back to Lesson
        </a>
    </div>

    <?php if ($success): ?>
        <div class="ae-notice ae-success">Activity saved successfully.</div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
        <div class="ae-notice ae-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="ae-layout">
        <form method="post" class="ae-card">
            <?php if (!$hasActivitySetLink): ?>
                <div class="ae-notice ae-warning">
                    Bảng <strong>activities</strong> chưa có cột
                    <strong>flashcard_set_id</strong>. Form vẫn hoạt động, nhưng chưa thể lưu bộ từ.
                </div>
            <?php endif; ?>

            <?php if (in_array($formType, ['sentence_builder', 'speaking'], true) && (int)($lesson['level_id'] ?? 0) <= 0): ?>
                <div class="ae-notice ae-warning">
                    Không xác định được <strong>Level</strong> của Unit này. Sentence Set cần đúng Book + Level.
                </div>
            <?php endif; ?>

            <?php if (in_array($formType, ['dialogue', 'ask_answer'], true) && !$hasDialogueSetLink): ?>
                <div class="ae-notice ae-warning">
                    Bảng <strong>activities</strong> chưa có cột <strong>dialogue_set_id</strong>. Hãy thêm cột này trước khi lưu Dialogue.
                </div>
            <?php endif; ?>

            <div class="ae-grid">
                <div class="form-group ae-full">
                    <label class="form-label" for="title">Activity Name</label>
                    <input
                        class="form-control"
                        id="title"
                        name="title"
                        maxlength="255"
                        required
                        value="<?= htmlspecialchars($formTitle) ?>"
                    >
                </div>

                <div class="form-group">
<?php if($isNew): ?>
                    <input type="hidden" name="activity_type" value="<?= htmlspecialchars($formType) ?>">
                    <?php endif; ?>
                    <label class="form-label" for="activity_type">Game Template</label>
                    <select class="form-control" id="activity_type" name="activity_type" <?= $isNew ? "disabled" : "" ?>>
                        <?php foreach ($activityTypes as $value => $meta): ?>
                            <option value="<?= htmlspecialchars($value) ?>" <?= $formType === $value ? 'selected' : '' ?>>
                                <?= $meta['icon'] ?> <?= htmlspecialchars($meta['label']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

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

                <?php if (in_array($formType, ['sentence_builder', 'speaking'], true)): ?>
                    <div class="form-group ae-full">
                        <label class="form-label" for="sentence_set_id">Sentence Set</label>
                        <select class="form-control" id="sentence_set_id" name="sentence_set_id" <?= !$hasSentenceSetLink ? 'disabled' : '' ?>>
                            <option value="">No Sentence Set</option>
                            <?php foreach ($sentenceSets as $set): ?>
                                <option value="<?= (int)$set['id'] ?>" <?= $formSentenceSetId === (int)$set['id'] ? 'selected' : '' ?>><?= htmlspecialchars((string)$set['set_label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small style="color:var(--muted)">Chọn bộ câu đã tạo trong Sentence Sets.</small>
                    </div>
                <?php elseif (in_array($formType, ['dialogue', 'ask_answer'], true)): ?>
                    <div class="form-group ae-full">
                        <label class="form-label" for="dialogue_set_id">Dialogue Set</label>
                        <select class="form-control" id="dialogue_set_id" name="dialogue_set_id" <?= !$hasDialogueSetLink ? 'disabled' : '' ?>>
                            <option value="">No Dialogue Set</option>
                            <?php foreach ($dialogueSets as $set): ?>
                                <option value="<?= (int)$set['id'] ?>" <?= $formDialogueSetId === (int)$set['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars((string)$set['set_label']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small style="color:var(--muted)">Chọn bộ hội thoại đã tạo trong Dialogue Sets.</small>
                    </div>
                <?php else: ?>
                    <div class="form-group ae-full">
                        <label class="form-label" for="flashcard_set_id">Flashcard Set</label>
                        <select class="form-control" id="flashcard_set_id" name="flashcard_set_id" <?= !$hasActivitySetLink ? 'disabled' : '' ?>>
                            <option value="">No Flashcard Set</option>
                            <?php foreach ($flashcardSets as $set): ?>
                                <option value="<?= (int)$set['id'] ?>" <?= $formFlashcardSetId === (int)$set['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars((string)$set['set_label']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small style="color:var(--muted)">Activity chỉ tham chiếu tới một bộ từ; không lưu từ trực tiếp.</small>
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['xp_reward'])): ?>
                    <div class="form-group">
                        <label class="form-label" for="xp_reward">XP Reward</label>
                        <input class="form-control" id="xp_reward" name="xp_reward" type="number" min="0" value="<?= $formXp ?>">
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['sort_order'])): ?>
                    <div class="form-group">
                        <label class="form-label" for="sort_order">Display Order</label>
                        <input class="form-control" id="sort_order" name="sort_order" type="number" min="0" value="<?= $formSortOrder ?>">
                    </div>
                <?php endif; ?>

                <?php if (isset($activityColumns['description']) || isset($activityColumns['instructions'])): ?>
                    <div class="form-group ae-full">
                        <label class="form-label" for="description">Instructions</label>
                        <textarea
                            class="form-control"
                            id="description"
                            name="description"
                            rows="5"
                            placeholder="Optional instruction shown before students start..."
                        ><?= htmlspecialchars($formDescription) ?></textarea>
                    </div>
                <?php endif; ?>
            </div>

            <div class="ae-save">
                <a href="detail.php?id=<?= (int)$lessonId ?>" class="button button-secondary">Cancel</a>
                <button type="submit" class="button button-primary">
                    <?= $isNew ? 'Create Activity' : 'Save Changes' ?>
                </button>
            </div>
        </form>

        <aside class="ae-card">
            <?php if (in_array($formType, ['sentence_builder', 'speaking'], true)): ?>
                <div class="ae-preview-head"><div><span class="section-kicker">Sentence Preview</span><h3 style="margin:3px 0 0">Sentence Set</h3></div><span class="ae-preview-count" id="sentenceCount">0 sentences</span></div>
                <div id="sentencePreview" class="ae-empty">Choose a Sentence Set to preview its sentences.</div>
            <?php elseif (in_array($formType, ['dialogue', 'ask_answer'], true)): ?>
                <div class="ae-preview-head">
                    <div>
                        <span class="section-kicker">Dialogue Preview</span>
                        <h3 style="margin:3px 0 0">Dialogue Set</h3>
                    </div>
                    <span class="ae-preview-count" id="dialogueCount">0 turns</span>
                </div>
                <div id="dialoguePreview" class="ae-empty">Choose a Dialogue Set to preview its turns.</div>
            <?php else: ?>
                <div class="ae-preview-head">
                    <div>
                        <span class="section-kicker">Word Preview</span>
                        <h3 style="margin:3px 0 0">Flashcard Set</h3>
                    </div>
                    <span class="ae-preview-count" id="wordCount">0 words</span>
                </div>
                <div id="wordPreview" class="ae-empty">Choose a Flashcard Set to preview its words.</div>
            <?php endif; ?>
        </aside>
    </div>
</div>

<script>
(function () {
    const setSelect = document.getElementById('flashcard_set_id');
    const preview = document.getElementById('wordPreview');
    const count = document.getElementById('wordCount');

    const setWords = <?= json_encode(
        $setPreviewMap,
        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 renderWords() {
        if (!setSelect || setSelect.disabled) {
            if (count) count.textContent = '0 words';
            if (preview) preview.className = 'ae-empty';
            if (preview) preview.textContent = 'Flashcard Set link is not available in the database yet.';
            return;
        }

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

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

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

        if (!words.length) {
            if (preview) preview.className = 'ae-empty';
            if (preview) preview.textContent = 'This Flashcard Set has no words, or its word relationship table has not been connected yet.';
            return;
        }

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

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

    setSelect?.addEventListener('change', renderWords);
    renderWords();


    const sentenceSelect = document.getElementById('sentence_set_id');
    const sentencePreview = document.getElementById('sentencePreview');
    const sentenceCount = document.getElementById('sentenceCount');
    const setSentences = <?= json_encode($sentencePreviewMap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    function renderSentences() {
        if (!sentenceSelect || !sentencePreview || !sentenceCount) return;
        const setId = sentenceSelect.value;
        const rows = setSentences[setId] || [];
        sentenceCount.textContent = rows.length + (rows.length === 1 ? ' sentence' : ' sentences');
        if (!setId) { sentencePreview.className='ae-empty'; sentencePreview.textContent='Choose a Sentence Set to preview its sentences.'; return; }
        if (!rows.length) { sentencePreview.className='ae-empty'; sentencePreview.textContent='This Sentence Set has no sentences, or its item relationship table has not been detected.'; return; }
        sentencePreview.className='';
        sentencePreview.innerHTML = rows.map((r,i) => '<div class="ae-word" style="margin-bottom:8px"><strong>'+(i+1)+'. '+escapeHtml(r.text)+'</strong></div>').join('');
    }
    sentenceSelect?.addEventListener('change', renderSentences);
    renderSentences();

    const dialogueSelect = document.getElementById('dialogue_set_id');
    const dialoguePreview = document.getElementById('dialoguePreview');
    const dialogueCount = document.getElementById('dialogueCount');
    const dialogueTurns = <?= json_encode(
        $dialoguePreviewMap,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
    ) ?>;

    function renderDialogue() {
        if (!dialogueSelect || !dialoguePreview || !dialogueCount) return;
        const setId = dialogueSelect.value;
        const turns = dialogueTurns[setId] || [];
        dialogueCount.textContent = turns.length + (turns.length === 1 ? ' turn' : ' turns');

        if (!setId) {
            dialoguePreview.className = 'ae-empty';
            dialoguePreview.textContent = 'Choose a Dialogue Set to preview its turns.';
            return;
        }
        if (!turns.length) {
            dialoguePreview.className = 'ae-empty';
            dialoguePreview.textContent = 'This Dialogue Set has no active turns.';
            return;
        }

        dialoguePreview.className = '';
        dialoguePreview.innerHTML = turns.map(function (turn) {
            const image = turn.image
                ? '<div class="ae-word-image"><img src="/EnglishSpeak/' + escapeHtml(turn.image.replace(/^\/+/, '')) + '" alt=""></div>'
                : '';
            return '<div class="ae-word" style="margin-bottom:8px;align-items:flex-start">'
                + image
                + '<div><strong>' + escapeHtml(turn.speaker || 'A') + ': ' + escapeHtml(turn.prompt) + '</strong>'
                + '<div style="font-size:12px;color:var(--muted);margin-top:4px">Answer: ' + escapeHtml(turn.response) + '</div></div>'
                + '</div>';
        }).join('');
    }

    dialogueSelect?.addEventListener('change', renderDialogue);
    renderDialogue();

    const typeSelect = document.getElementById('activity_type');
    const titleInput = document.getElementById('title');

    const defaultTitles = {
        flashcards: 'Flashcards',
        listen_repeat: 'Listen & Repeat',
        matching: 'Matching',
        memory: 'Memory',
        quiz: 'Quiz',
        speaking: 'Speaking',
        typing: 'Typing',
        word_search: 'Word Search',
        sentence_builder: 'Sentence Builder',
        dialogue: 'Dialogue',
        ask_answer: 'Ask & Answer',
        word_builder: 'Word Builder',
        word_unscramble: 'Word Unscramble',
        find_word: 'Find the Word',
        fix_word: 'Fix the Word',
        worksheet: 'Worksheet',
        game: 'Game',
        vocabulary: 'Word List'
    };

    typeSelect?.addEventListener('change', function () {
        const currentTitle = titleInput.value.trim();

        if (currentTitle === '' || Object.values(defaultTitles).includes(currentTitle)) {
            titleInput.value = defaultTitles[this.value] || 'Activity';
        }
    });
})();
</script>

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