<?php
declare(strict_types=1);
require __DIR__ . '/../partials/auth.php';

$pageTitle = 'Word Detail';
$pageSubtitle = 'Vocabulary details and usage across the system';
$activeTeacherNav = 'word-library';

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');

$wordId = (int)($_GET['id'] ?? 0);
if ($wordId <= 0) {
    header('Location: index.php');
    exit;
}

// ─── Fetch word ────────────────────────
$stmt = $pdo->prepare("SELECT * FROM words WHERE id = ?");
$stmt->execute([$wordId]);
$word = $stmt->fetch(PDO::FETCH_ASSOC);
$canManageWord = $word && ($isAdmin || ((int)($word['created_by_teacher_id'] ?? 0) > 0 && (int)$word['created_by_teacher_id'] === $currentUserId));

if (!$word) {
    header('Location: index.php');
    exit;
}

// ─── Fetch example ─────────────────────
$exStmt = $pdo->prepare("SELECT * FROM word_examples WHERE word_id = ? AND status = 'active' ORDER BY sort_order LIMIT 1");
$exStmt->execute([$wordId]);
$example = $exStmt->fetch(PDO::FETCH_ASSOC);

// ─── Fetch topics ──────────────────────
$topicsStmt = $pdo->prepare("
    SELECT t.id, t.name, t.slug
    FROM topic_words tw
    JOIN topics t ON tw.topic_id = t.id
    WHERE tw.word_id = ? AND t.status = 'active'
    ORDER BY t.name
");
$topicsStmt->execute([$wordId]);
$wordTopics = $topicsStmt->fetchAll(PDO::FETCH_ASSOC);

// ─── Detect existing relationship tables ──
$allTables = array_column($pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_NUM), 0);
$hasLessonWords   = in_array('lesson_words', $allTables);
$hasActivityWords  = in_array('activity_words', $allTables);
$hasLessons        = in_array('lessons', $allTables);
$hasActivities     = in_array('activities', $allTables);
$hasUnits          = in_array('units', $allTables);
$hasBookLevels     = in_array('book_levels', $allTables);
$hasBooks          = in_array('books', $allTables);

// ─── Fetch lesson usage (only if all required tables exist) ──
$lessonUsages = [];
$lessonRelationshipConfigured = $hasLessonWords && $hasLessons && $hasUnits && $hasBookLevels && $hasBooks;

if ($lessonRelationshipConfigured) {
    try {
        $lessonUsageStmt = $pdo->prepare("
            SELECT
                l.id AS lesson_id,
                l.title AS lesson_title,
                l.lesson_number,
                l.lesson_type,
                u.id AS unit_id,
                u.title AS unit_title,
                u.unit_number,
                bl.id AS book_level_id,
                bl.title AS book_level_title,
                b.id AS book_id,
                b.name AS book_name
            FROM lesson_words lw
            JOIN lessons l ON lw.lesson_id = l.id
            JOIN units u ON l.unit_id = u.id
            JOIN book_levels bl ON u.book_level_id = bl.id
            JOIN books b ON bl.book_id = b.id
            WHERE lw.word_id = ?
            ORDER BY b.sort_order, bl.sort_order, u.sort_order, l.sort_order
        ");
        $lessonUsageStmt->execute([$wordId]);
        $lessonUsages = $lessonUsageStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // silently ignore - lesson relationship not fully configured
        $lessonRelationshipConfigured = false;
        $lessonUsages = [];
    }
}

// ─── Fetch activity usage (only if all required tables exist) ──
$activityUsages = [];
$activityRelationshipConfigured = $hasActivityWords && $hasActivities && $hasLessons && $hasUnits && $hasBookLevels && $hasBooks;

if ($activityRelationshipConfigured) {
    try {
        $activityUsageStmt = $pdo->prepare("
            SELECT
                a.id AS activity_id,
                a.title AS activity_title,
                a.activity_type,
                l.id AS lesson_id,
                l.title AS lesson_title,
                l.lesson_number,
                u.id AS unit_id,
                u.title AS unit_title,
                u.unit_number,
                b.name AS book_name
            FROM activity_words aw
            JOIN activities a ON aw.activity_id = a.id
            JOIN lessons l ON a.lesson_id = l.id
            JOIN units u ON l.unit_id = u.id
            JOIN book_levels bl ON u.book_level_id = bl.id
            JOIN books b ON bl.book_id = b.id
            WHERE aw.word_id = ?
            ORDER BY b.sort_order, l.sort_order
        ");
        $activityUsageStmt->execute([$wordId]);
        $activityUsages = $activityUsageStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // silently ignore - activity relationship not fully configured
        $activityRelationshipConfigured = false;
        $activityUsages = [];
    }
}

// ─── Helpers ───────────────────────────
function posLabel(string $pos): string {
    return match($pos) {
        'noun' => 'Noun', 'verb' => 'Verb', 'adjective' => 'Adjective',
        'adverb' => 'Adverb', 'pronoun' => 'Pronoun', 'preposition' => 'Preposition',
        'conjunction' => 'Conjunction', 'interjection' => 'Interjection',
        'determiner' => 'Determiner', 'article' => 'Article',
        default => ucfirst($pos)
    };
}

ob_start();
?>

<div class="wl-page-header">
    <div>
        <span class="section-kicker">Word Library</span>
        <h2>Word Detail</h2>
    </div>
    <div class="button-group">
        <a href="index.php" class="button button-sm button-secondary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="m19 12H5m7-7-7 7 7 7"/></svg>
            Back to Library
        </a>
        <?php if ($canManageWord): ?>
        <a href="index.php?edit=<?= $word['id'] ?>" class="button button-sm button-primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
            Edit Word
        </a>
        <?php endif; ?>
    </div>
</div>

<div class="wl-detail-grid">
    <!-- Left Column -->
    <div class="wl-detail-main">
        <!-- Basic Information -->
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
                Basic Information
            </h3>

            <div class="wl-word-hero">
                <?php if (!empty($word['image_path'])): ?>
                <img src="<?= htmlspecialchars(es_url($word['image_path'])) ?>" alt="<?= htmlspecialchars($word['word']) ?>" class="wl-word-hero-img">
                <?php else: ?>
                <div class="wl-word-hero-img-placeholder"><?= htmlspecialchars(mb_strtoupper(mb_substr($word['word'], 0, 1))) ?></div>
                <?php endif; ?>
                <div class="wl-word-hero-info">
                    <h2><?= htmlspecialchars($word['word']) ?></h2>
                    <?php if (!empty($word['phonetic'])): ?>
                    <div class="wl-word-hero-ipa"><?= htmlspecialchars($word['phonetic']) ?></div>
                    <?php endif; ?>
                    <?php if (!empty($word['meaning_vi'])): ?>
                    <div class="wl-word-hero-meaning"><?= htmlspecialchars($word['meaning_vi']) ?></div>
                    <?php endif; ?>
                </div>
            </div>

            <div style="margin-top:16px;">
                <div class="wl-detail-row">
                    <span class="wl-detail-label">Part of Speech</span>
                    <span class="wl-detail-value">
                        <?php if (!empty($word['part_of_speech'])): ?>
                        <span class="wl-pos-badge wl-pos-<?= htmlspecialchars($word['part_of_speech']) ?>"><?= posLabel($word['part_of_speech']) ?></span>
                        <?php else: ?>—<?php endif; ?>
                    </span>
                </div>
                <div class="wl-detail-row">
                    <span class="wl-detail-label">Difficulty</span>
                    <span class="wl-detail-value">Level <?= (int)($word['difficulty_level'] ?? 1) ?></span>
                </div>
                <div class="wl-detail-row">
                    <span class="wl-detail-label">Status</span>
                    <span class="wl-detail-value">
                        <span class="wl-status-badge <?= $word['status'] === 'active' ? 'wl-status-active' : 'wl-status-archived' ?>">
                            <?= $word['status'] === 'active' ? 'Active' : 'Archived' ?>
                        </span>
                    </span>
                </div>
                <div class="wl-detail-row">
                    <span class="wl-detail-label">Created</span>
                    <span class="wl-detail-value"><?= date('M j, Y', strtotime($word['created_at'])) ?></span>
                </div>
                <div class="wl-detail-row">
                    <span class="wl-detail-label">Updated</span>
                    <span class="wl-detail-value"><?= date('M j, Y', strtotime($word['updated_at'])) ?></span>
                </div>
                <?php if (!empty($word['notes'])): ?>
                <div class="wl-detail-row" style="flex-direction:column;align-items:flex-start;">
                    <span class="wl-detail-label">Notes</span>
                    <span class="wl-detail-value" style="text-align:left;"><?= nl2br(htmlspecialchars($word['notes'])) ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Example Sentence -->
        <?php if ($example): ?>
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></svg>
                Example Sentence
            </h3>
            <div class="wl-detail-row">
                <span class="wl-detail-label">English</span>
                <span class="wl-detail-value" style="font-style:italic;"><?= htmlspecialchars($example['example_en']) ?></span>
            </div>
            <?php if (!empty($example['example_vi'])): ?>
            <div class="wl-detail-row">
                <span class="wl-detail-label">Meaning</span>
                <span class="wl-detail-value"><?= htmlspecialchars($example['example_vi']) ?></span>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Topics -->
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2M9 5v2"/></svg>
                Topics (<?= count($wordTopics) ?>)
            </h3>
            <?php if (!empty($wordTopics)): ?>
            <div class="wl-topic-tags">
                <?php foreach ($wordTopics as $t): ?>
                <span class="wl-topic-tag"><?= htmlspecialchars($t['name']) ?></span>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p style="color:var(--muted);font-size:12px;">No topics assigned.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Column: Usage -->
    <div class="wl-detail-main">
        <!-- Audio Preview -->
        <?php if (!empty($word['audio_us_path'])): ?>
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                Audio
            </h3>
            <audio controls src="<?= htmlspecialchars(es_url($word['audio_us_path'])) ?>" style="width:100%;height:36px;"></audio>
        </div>
        <?php endif; ?>

        <!-- Lesson Usage -->
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
                Used in Lessons
            </h3>
            <?php if (!$lessonRelationshipConfigured): ?>
            <div class="wl-placeholder-section">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="32" height="32" style="color:var(--muted);opacity:0.5;"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
                <p style="color:var(--muted);font-size:13px;margin-top:8px;">No lesson relationship configured yet.</p>
            </div>
            <?php elseif (!empty($lessonUsages)): ?>
            <div class="wl-usage-list">
                <?php foreach ($lessonUsages as $lu): ?>
                <div class="wl-usage-item">
                    <div style="flex:1;min-width:0;">
                        <div class="wl-usage-breadcrumb">
                            <?= htmlspecialchars($lu['book_name']) ?> &rsaquo;
                            <?= htmlspecialchars($lu['book_level_title']) ?> &rsaquo;
                            <span><?= htmlspecialchars($lu['unit_number'] . ': ' . $lu['unit_title']) ?></span>
                        </div>
                        <div style="font-weight:600;font-size:13px;margin-top:2px;">
                            <?= htmlspecialchars($lu['lesson_number'] . ': ' . $lu['lesson_title']) ?>
                        </div>
                    </div>
                    <span class="wl-usage-type">Lesson</span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p style="color:var(--muted);font-size:12px;">Not used in any lessons.</p>
            <?php endif; ?>
        </div>

        <!-- Activity Usage -->
        <div class="wl-detail-card">
            <h3>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
                Used in Activities
            </h3>
            <?php if (!$activityRelationshipConfigured): ?>
            <div class="wl-placeholder-section">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="32" height="32" style="color:var(--muted);opacity:0.5;"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
                <p style="color:var(--muted);font-size:13px;margin-top:8px;">No activity relationship configured yet.</p>
            </div>
            <?php elseif (!empty($activityUsages)): ?>
            <div class="wl-usage-list">
                <?php foreach ($activityUsages as $au): ?>
                <div class="wl-usage-item">
                    <div style="flex:1;min-width:0;">
                        <div class="wl-usage-breadcrumb">
                            <?= htmlspecialchars($au['book_name']) ?> &rsaquo;
                            <span><?= htmlspecialchars($au['unit_number'] . ': ' . $au['unit_title']) ?></span>
                        </div>
                        <div style="font-weight:600;font-size:13px;margin-top:2px;">
                            <?= htmlspecialchars($au['activity_title']) ?>
                        </div>
                    </div>
                    <span class="wl-usage-type"><?= htmlspecialchars(ucfirst($au['activity_type'] ?? 'Activity')) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p style="color:var(--muted);font-size:12px;">Not used in any activities.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

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