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

$user = getUserById($_SESSION['user_id']);

if (!$user || $user['level'] < 10) {
    header('Location: profile.php');
    exit;
}

if (isUserInClan($user['id'])) {
    header('Location: clan.php');
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    if (empty($name)) {
        $error = 'Введите название клана';
    } else {
        $result = createClan($user['id'], $name, $description);
        if ($result['success']) {
            header('Location: clan.php?id=' . $result['clan_id']);
            exit;
        } else {
            $error = $result['message'];
        }
    }
}

require_once 'inc/header.php';
?>

<div class="ttl"><b>Создание клана</b></div>
<div class="hr"></div>

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

<form method="post">
    <table>
        <tr><td>Название клана:</td><td><input type="text" name="name" maxlength="50" required></td></tr>
        <tr><td>Описание:</td><td><textarea name="description" rows="4" cols="30"></textarea></td></tr>
        <tr><td colspan="2"><button type="submit" class="btn">Создать (100 золота)</button></td></tr>
    </table>
</form>

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