<?php
declare(strict_types=1);

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

$pdo = getDbConnection();
$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$isAdmin = ($currentUserRole === 'admin');

$topicId = (int)($_GET['topic'] ?? $_POST['topic_id'] ?? 0);

$pageTitle = 'Add Words';
$pageSubtitle = '';
$activeTeacherNav = 'topic-library';

$stmt = $pdo->prepare("SELECT id, name, created_by_teacher_id FROM topics WHERE id = ? LIMIT 1");
$stmt->execute([$topicId]);
$topic = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$topic) { http_response_code(404); die('Topic not found'); }
if (!$isAdmin && ($topic['created_by_teacher_id'] === null || (int)$topic['created_by_teacher_id'] !== $currentUserId)) {
    http_response_code(403); die('Bạn không có quyền thêm từ vào Topic này.');
}

$formError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $wordIds = $_POST['word_ids'] ?? [];
    $wordIds = array_values(array_unique(array_filter(array_map('intval', (array)$wordIds))));

    if (empty($wordIds)) {
        $formError = 'Please select at least one word.';
    } else {
        $checkWord = $pdo->prepare("SELECT id FROM words WHERE id = ? AND status = 'active' LIMIT 1");
        $checkLink = $pdo->prepare("SELECT id FROM topic_words WHERE topic_id = ? AND word_id = ? LIMIT 1");
        $insertLink = $pdo->prepare("INSERT INTO topic_words (topic_id, word_id, sort_order) VALUES (?, ?, 0)");

        try {
            $pdo->beginTransaction();

            foreach ($wordIds as $wordId) {
                $checkWord->execute([$wordId]);
                if (!$checkWord->fetchColumn()) continue;

                $checkLink->execute([$topicId, $wordId]);
                if ($checkLink->fetchColumn()) continue;

                $insertLink->execute([$topicId, $wordId]);
            }

            $pdo->commit();
            header('Location: detail.php?id=' . $topicId);
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $formError = 'Could not add the selected words. Please try again.';
        }
    }
}

$search = trim((string)($_GET['search'] ?? ''));
$partOfSpeech = trim((string)($_GET['part_of_speech'] ?? ''));

$where = [
    "w.status = 'active'",
    "NOT EXISTS (SELECT 1 FROM topic_words tw WHERE tw.topic_id = ? AND tw.word_id = w.id)"
];
$params = [$topicId];

if ($search !== '') {
    $where[] = "(w.word LIKE ? OR w.meaning_vi LIKE ? OR w.phonetic LIKE ?)";
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($partOfSpeech !== '') {
    $where[] = "w.part_of_speech = ?";
    $params[] = $partOfSpeech;
}

$sql = "
    SELECT w.id, w.word, w.phonetic, w.part_of_speech, w.meaning_vi, w.image_path, w.audio_us_path
    FROM words w
    WHERE " . implode(' AND ', $where) . "
    ORDER BY w.word ASC
";

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

$posList = ['noun','verb','adjective','adverb','pronoun','preposition','conjunction','interjection','determiner','article'];

ob_start();
?>

<div class="wl-page-header">
    <div>
        <span class="section-kicker">Topic</span>
        <h2>Add Words to <?= htmlspecialchars($topic['name']) ?></h2>
    </div>
    <a href="detail.php?id=<?= $topicId ?>" class="button button-secondary">← Back</a>
</div>

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

<div class="wl-toolbar" style="margin-bottom:16px;">
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;width:100%;">
        <input type="hidden" name="topic" value="<?= $topicId ?>">
        <input type="text" name="search" class="form-control" value="<?= htmlspecialchars($search) ?>" placeholder="Search word, meaning, IPA..." style="min-width:260px;flex:1;">
        <select name="part_of_speech" class="form-control" style="width:auto;min-width:160px;">
            <option value="">All Part of Speech</option>
            <?php foreach ($posList as $pos): ?>
                <option value="<?= htmlspecialchars($pos) ?>" <?= $partOfSpeech === $pos ? 'selected' : '' ?>><?= htmlspecialchars(ucfirst($pos)) ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="button button-primary">Search</button>
    </form>
</div>

<form method="post" id="addWordsForm">
    <input type="hidden" name="topic_id" value="<?= $topicId ?>">

    <div class="wl-toolbar" style="position:sticky;top:0;z-index:5;margin-bottom:12px;">
        <div><strong id="selectedCount">0 selected</strong></div>
        <div class="button-group">
            <button type="button" class="button button-sm button-secondary" id="selectAllBtn">Select All</button>
            <button type="button" class="button button-sm button-secondary" id="clearBtn">Clear</button>
            <button type="submit" class="button button-sm button-primary">Add Selected Words</button>
        </div>
    </div>

    <div class="table-shell">
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width:42px;"><input type="checkbox" id="checkAll"></th>
                    <th style="width:70px;"></th>
                    <th>Word</th>
                    <th>IPA</th>
                    <th>Meaning</th>
                    <th>Part of Speech</th>
                    <th style="width:90px;">Audio</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($words)): ?>
                    <tr>
                        <td colspan="7">
                            <div style="padding:32px;text-align:center;">
                                <h3>No available words</h3>
                                <p style="color:var(--muted);">All matching words are already in this Topic.</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($words as $word): ?>
                        <tr>
                            <td><input type="checkbox" class="word-checkbox" name="word_ids[]" value="<?= (int)$word['id'] ?>"></td>
                            <td>
                                <?php if (!empty($word['image_path'])): ?>
                                    <img src="<?= htmlspecialchars(es_url($word['image_path'])) ?>" alt="" style="width:48px;height:48px;object-fit:contain;" loading="lazy">
                                <?php else: ?>
                                    <div class="wl-word-thumb-placeholder" style="width:48px;height:48px;"><?= htmlspecialchars(mb_strtoupper(mb_substr($word['word'], 0, 1))) ?></div>
                                <?php endif; ?>
                            </td>
                            <td><strong><?= htmlspecialchars($word['word']) ?></strong></td>
                            <td><?= htmlspecialchars($word['phonetic'] ?: '—') ?></td>
                            <td><?= htmlspecialchars($word['meaning_vi'] ?: '—') ?></td>
                            <td><?= htmlspecialchars($word['part_of_speech'] ?: '—') ?></td>
                            <td>
                                <button type="button" class="icon-button play-word" data-word="<?= htmlspecialchars($word['word']) ?>" data-audio="<?= !empty($word['audio_us_path']) ? htmlspecialchars(es_url($word['audio_us_path'])) : '' ?>" title="Play pronunciation">🔊</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</form>

<script>
(function () {
    'use strict';

    const checkboxes = Array.from(document.querySelectorAll('.word-checkbox'));
    const checkAll = document.getElementById('checkAll');
    const selectAllBtn = document.getElementById('selectAllBtn');
    const clearBtn = document.getElementById('clearBtn');
    const selectedCount = document.getElementById('selectedCount');

    function updateCount() {
        const count = checkboxes.filter(function (checkbox) { return checkbox.checked; }).length;
        selectedCount.textContent = count + ' selected';
        if (checkAll) {
            checkAll.checked = checkboxes.length > 0 && count === checkboxes.length;
            checkAll.indeterminate = count > 0 && count < checkboxes.length;
        }
    }

    function setAll(checked) {
        checkboxes.forEach(function (checkbox) { checkbox.checked = checked; });
        updateCount();
    }

    checkboxes.forEach(function (checkbox) { checkbox.addEventListener('change', updateCount); });
    if (checkAll) checkAll.addEventListener('change', function () { setAll(this.checked); });
    if (selectAllBtn) selectAllBtn.addEventListener('click', function () { setAll(true); });
    if (clearBtn) clearBtn.addEventListener('click', function () { setAll(false); });

    document.addEventListener('click', function (event) {
        const button = event.target.closest('.play-word');
        if (!button) return;

        const audioPath = (button.dataset.audio || '').trim();
        const word = (button.dataset.word || '').trim();

        if (audioPath) {
            const audio = new Audio(audioPath);
            audio.play().catch(function () { speakWord(word); });
            return;
        }

        speakWord(word);
    });

    function speakWord(word) {
        if (!word || !('speechSynthesis' in window)) return;
        window.speechSynthesis.cancel();
        const speech = new SpeechSynthesisUtterance(word);
        speech.lang = 'en-US';
        speech.rate = 0.9;
        speech.pitch = 1;
        window.speechSynthesis.speak(speech);
    }

    updateCount();
})();
</script>

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