<?php
declare(strict_types=1);

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

$pdo = getDbConnection();
$currentUserId = (int)($_SESSION['user_id'] ?? 0);

$pageTitle = 'Create Topic';
$pageSubtitle = 'Create a new vocabulary topic';
$activeTeacherNav = 'topic-library';

$formError = '';
$name = '';

function topicSlug(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(?))
            LIMIT 1
        ");
        $check->execute([$name]);

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

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

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

            try {
                $stmt = $pdo->prepare("
                    INSERT INTO topics
                        (name, slug, status, created_by_teacher_id, created_at, updated_at)
                    VALUES
                        (?, ?, 'active', ?, NOW(), NOW())
                ");

                $stmt->execute([$name, $slug, $currentUserId ?: null]);

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

ob_start();
?>

<div class="wl-page-header">
    <div>
        <span class="section-kicker">Topic Library</span>
        <h2>Create 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">
            <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">
                    Create Topic
                </button>
            </div>
        </form>
    </div>
</div>

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