<?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');
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['remove_topic_word_id'])) {

    $stmt = $pdo->prepare("
        DELETE tw FROM topic_words tw JOIN topics t ON t.id = tw.topic_id
        WHERE tw.id = ? AND (? = 1 OR t.created_by_teacher_id = ?)
    ");

    $stmt->execute([
        (int)$_POST['remove_topic_word_id'], $isAdmin ? 1 : 0, $currentUserId
    ]);

    header(
        'Location: detail.php?id=' .
        (int)($_GET['id'] ?? 0)
    );

    exit;
}

$id = (int)($_GET['id'] ?? 0);

$pageTitle = 'Topic';
$pageSubtitle = '';
$activeTeacherNav = 'topic-library';

$stmt = $pdo->prepare("
SELECT *
FROM topics
WHERE id = ?
LIMIT 1
");

$stmt->execute([$id]);

$topic = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$topic) {
    die('Topic not found');
}

$stmt = $pdo->prepare("
SELECT
    tw.id AS topic_word_id,
    w.id,
    w.word,
    w.phonetic,
    w.meaning_vi,
    w.image_path,
    w.audio_us_path
FROM topic_words tw
JOIN words w ON w.id = tw.word_id
WHERE tw.topic_id = ?
ORDER BY w.word
");

$stmt->execute([$id]);

$words = $stmt->fetchAll(PDO::FETCH_ASSOC);
$canManageTopic = $isAdmin || ($topic['created_by_teacher_id'] !== null && (int)$topic['created_by_teacher_id'] === $currentUserId);

ob_start();
?>

<div class="wl-page-header">
    <div>
        <span class="section-kicker">Topic</span>
        <h2><?= htmlspecialchars($topic['name']) ?></h2>
    </div>

    <a href="index.php" class="button button-secondary">
        ← Back
    </a>
<?php if ($canManageTopic): ?><a href="add-words.php?topic=<?= (int)$topic['id'] ?>" class="button">+ Add Words</a><?php endif; ?>
</div>

<div class="table-shell">

<table class="data-table">

<thead>
<tr>
    <th></th>
    <th>Word</th>
    <th>IPA</th>
    <th>Meaning</th>
    <th style="width:120px;">Audio</th>
    <th style="width:120px;">Action</th>
</tr>
</thead>

<tbody>

<?php foreach($words as $word): ?>

<tr>

<td style="width:70px;">

<?php if(!empty($word['image_path'])): ?>

<img
src="<?= es_url($word['image_path']) ?>"
style="
width:48px;
height:48px;
object-fit:contain;
">

<?php endif; ?>

</td>

<td>

<strong>

<?= htmlspecialchars($word['word']) ?>

</strong>

</td>

<td>

<?= htmlspecialchars($word['phonetic']) ?>

</td>

<td>

<?= htmlspecialchars($word['meaning_vi']) ?>

</td>

<td>

<?php if(!empty($word['audio_us_path'])): ?>

<button
class="icon-button play-audio"
data-audio="<?= es_url($word['audio_us_path']) ?>"
>

🔊

</button>

<?php endif; ?>

</td>

<td>

<?php if ($canManageTopic): ?>
<form method="post" onsubmit="return confirm('Remove this word from this Topic?');">

    <input
        type="hidden"
        name="remove_topic_word_id"
        value="<?= (int)$word['topic_word_id'] ?>">

    <button
        type="submit"
        class="icon-button"
        title="Remove from Topic">

        ❌

    </button>

</form>
<?php else: ?>—<?php endif; ?>
</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>
<script>
document.addEventListener('click', function (event) {
    const button = event.target.closest('.play-audio');

    if (!button) {
        return;
    }

    const audioPath = button.dataset.audio;

    if (!audioPath) {
        return;
    }

    const audio = new Audio(audioPath);

    audio.play().catch(function () {
        alert('Không thể phát âm thanh.');
    });
});
</script>
<?php

$content = ob_get_clean();

require __DIR__ . '/../layouts/app.php';