<?php
session_start();
require_once 'inc/functions.php';
check404();
securityCheck();
if (!isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$sectionId = isset($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$section = getSectionById($sectionId);
if (!$section) {
    header('Location: forum.php');
    exit;
}

// Проверка прав на создание темы
if (!canCreateTopic($_SESSION['user_id'], $sectionId)) {
    header('Location: subforum.php?id=' . $sectionId);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    if (!empty($title) && !empty($content)) {
        createTopic($_SESSION['user_id'], $sectionId, $title, $content);
        header('Location: subforum.php?id=' . $sectionId);
        exit;
    } else {
        $error = 'Заполните все поля.';
    }
}

require_once 'inc/header.php';
?>

<span class="ttl"><b>Создание новой темы в разделе «<?= htmlspecialchars($section['title']) ?>»</b></span>
<div class="clb"></div>
<div class="hr"></div>

<?php if (isset($error)): ?>
    <div class="error"><?= $error ?></div>
<?php endif; ?>

<form method="post">
    <table>
        <tr>
            <td>Заголовок:</td>
            <td><input type="text" name="title" size="60" maxlength="255" required/></td>
        </tr>
        <tr>
            <td valign="top">Сообщение:</td>
            <td><textarea name="content" rows="10" cols="60" required></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Создать тему" class="btn"/></td>
        </tr>
    </table>
</form>

<?php require_once 'inc/foot.php'; ?>