<?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['id'] ?? $_POST['topic_id'] ?? 0);

$pageTitle = 'Edit Topic';
$pageSubtitle = 'Update vocabulary topic';
$activeTeacherNav = 'topic-library';

$stmt = $pdo->prepare("
    SELECT id, name, slug, status, 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 sửa Topic này.');
}

$formError = '';
$name = (string)$topic['name'];

function topicEditSlug(string $name): string
{
    $slug = strtolower(
        trim(
            (string)preg_replace('/[^a-zA-Z0-9]+/', '-', $name),
            '-'
        )
    );

    return $slug !== '' ? $slug : 'topic-' . time();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string)($_POST['name'] ?? ''));

    if ($name === '') {
        $formError = 'Please enter a Topic name.';
    } else {
        $check = $pdo->prepare("
            SELECT id
            FROM topics
            WHERE LOWER(TRIM(name)) = LOWER(TRIM(?))
              AND id <> ?
            LIMIT 1
        ");
        $check->execute([$name, $topicId]);

        if ($check->fetchColumn()) {
            $formError = 'This Topic name already exists.';
        } else {
            $slug = topicEditSlug($name);

            $slugCheck = $pdo->prepare("
                SELECT id
                FROM topics
                WHERE slug = ?
                  AND id <> ?
                LIMIT 1
            ");
            $slugCheck->execute([$slug, $topicId]);

            if ($slugCheck->fetchColumn()) {
                $slug .= '-' . substr(md5($name . microtime(true)), 0, 5);
            }

            try {
                $stmt = $pdo->prepare("
                    UPDATE topics
                    SET
                        name = ?,
                        slug = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");

                $stmt->execute([
                    $name,
                    $slug,
                    $topicId
                ]);

                header('Location: index.php');
                exit;
            } catch (Throwable $e) {
                $formError = 'Could not update the Topic. Please try again.';
            }
        }
    }
}

ob_start();
?>

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

    <a href="index.php" class="button button-secondary">
        ← Back
    </a>
</div>

<div class="table-shell" style="max-width:680px;">
    <div style="padding:24px;">
        <?php if ($formError !== ''): ?>
            <div class="wl-duplicate-alert" style="margin-bottom:18px;">
                <?= htmlspecialchars($formError) ?>
            </div>
        <?php endif; ?>

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

            <div class="form-group">
                <label class="form-label">
                    Topic Name <span class="required">*</span>
                </label>

                <input
                    type="text"
                    name="name"
                    class="form-control"
                    value="<?= htmlspecialchars($name) ?>"
                    placeholder="e.g. Animals"
                    required
                    autofocus
                >

                <p class="form-helper">
                    Topic names must be unique.
                </p>
            </div>

            <div class="button-group" style="justify-content:flex-end;margin-top:22px;">
                <a href="index.php" class="button button-secondary">
                    Cancel
                </a>

                <button type="submit" class="button button-primary">
                    Save Changes
                </button>
            </div>
        </form>
    </div>
</div>

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