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

$pageTitle = 'Topic Library';
$pageSubtitle = 'Manage vocabulary topics';
$activeTeacherNav = 'topic-library';

// Lấy danh sách Topic và số từ trong từng Topic
$stmt = $pdo->query(
    '
    SELECT
        t.id,
        t.name,
        t.slug,
        t.status,
        t.updated_at,
        t.created_by_teacher_id,
        COUNT(DISTINCT tw.word_id) AS word_count
    FROM topics t
    LEFT JOIN topic_words tw ON tw.topic_id = t.id
    WHERE t.status = "active"
    GROUP BY t.id, t.name, t.slug, t.status, t.updated_at, t.created_by_teacher_id
    ORDER BY t.name ASC
    '
);

$topics = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>

<div class="wl-page-header">
    <div>
        <span class="section-kicker">Content</span>
        <h2>Topic Library</h2>
    </div>

    <a
    href="create.php"
    class="button button-primary">

    + Add Topic

</a>
</div>

<div class="table-shell">
    <table class="data-table">
        <thead>
            <tr>
                <th>Topic</th>
                <th style="width:120px;">Words</th>
                <th style="width:150px;">Updated</th>
                <th style="width:140px;">Actions</th>
            </tr>
        </thead>

        <tbody>
            <?php if (empty($topics)): ?>
                <tr>
                    <td colspan="4">
                        <div style="padding:32px;text-align:center;">
                            <h3>No topics yet</h3>
                            <p style="color:var(--muted);">
                                Create your first topic or import an image folder.
                            </p>
                        </div>
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($topics as $topic): ?>
                    <tr>
                        <td>
                            <strong>
                                <?= htmlspecialchars($topic['name']) ?>
                            </strong>
                        </td>

                        <td>
                            <?= (int)$topic['word_count'] ?>
                        </td>

                        <td style="color:var(--muted);font-size:12px;">
                            <?= !empty($topic['updated_at'])
                                ? htmlspecialchars(date('d/m/Y', strtotime($topic['updated_at'])))
                                : '—' ?>
                        </td>

                        <td>
                            <div class="wl-action-group">
                                <a
                                    href="detail.php?id=<?= (int)$topic['id'] ?>"
                                    class="icon-button"
                                    title="View Topic"
                                >
                                    👁
                                </a>

<?php $canManageTopic = $isAdmin || ($topic['created_by_teacher_id'] !== null && (int)$topic['created_by_teacher_id'] === $currentUserId); ?>
<?php if ($canManageTopic): ?>
<a href="edit.php?id=<?= (int)$topic['id'] ?>" class="icon-button" title="Edit Topic">✏️</a>
<a href="delete.php?id=<?= (int)$topic['id'] ?>" class="icon-button" title="Archive Topic" style="color:var(--danger);" onclick="return confirm('Archive this topic?');">🗑</a>
<?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

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