<?php
require_once __DIR__ . '/session.php';

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $invite_code = $_POST['invite_code'] ?? '';
    
    if ($username && $email && $password) {
        $server_id = 1; // Default server
        if (PRIVATE_REGISTRATION) {
            if (empty($invite_code)) {
                $error = "Un code d'invitation est requis.";
            } else {
                $stmt = db()->prepare("SELECT id, invite_code_expires_at FROM servers WHERE invite_code = ?");
                $stmt->execute([$invite_code]);
                $server = $stmt->fetch();
                if (!$server) {
                    $error = "Code d'invitation invalide.";
                } elseif ($server['invite_code_expires_at'] && strtotime($server['invite_code_expires_at']) < time()) {
                    $error = "Ce code d'invitation a expiré.";
                } else {
                    $server_id = $server['id'];
                }
            }
        }

        if (!$error) {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            try {
                $stmt = db()->prepare("INSERT INTO users (username, display_name, email, password_hash) VALUES (?, ?, ?, ?)");
                $stmt->execute([$username, $username, $email, $hash]);
                $userId = db()->lastInsertId();
                
                // Add to the appropriate server
                $stmt = db()->prepare("INSERT IGNORE INTO server_members (server_id, user_id) VALUES (?, ?)");
                $stmt->execute([$server_id, $userId]);

                $_SESSION['user_id'] = $userId;
                header('Location: ../index.php?server_id=' . $server_id);
                exit;
            } catch (Exception $e) {
                $error = "L'inscription a échoué : " . $e->getMessage();
            }
        }
    } else {
        $error = "Veuillez remplir tous les champs.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Inscription | Corvara</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/corvara.css">
    <style>
        body { background-color: #313338; display: flex; align-items: center; justify-content: center; height: 100vh; }
        .auth-card { background-color: #2b2d31; padding: 32px; border-radius: 8px; width: 100%; max-width: 480px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); }
        .form-label { color: #b5bac1; font-size: 12px; font-weight: bold; text-transform: uppercase; }
        .form-control { background-color: #1e1f22; border: none; color: #dbdee1; padding: 10px; }
        .form-control:focus { background-color: #1e1f22; color: #dbdee1; box-shadow: none; }
        .btn-blurple { background-color: #3c6f7c; color: white; width: 100%; font-weight: bold; margin-top: 20px; }
        .btn-blurple:hover { background-color: #2e5661; color: white; }
        .auth-footer { color: #949ba4; font-size: 14px; margin-top: 10px; }
        .auth-footer a { color: #00a8fc; text-decoration: none; }
    </style>
</head>
<body>
    <div class="auth-card">
        <h3 class="text-center mb-4">Créer un compte</h3>
        <?php if($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Nom d'utilisateur</label>
                <input type="text" name="username" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Email</label>
                <input type="email" name="email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Mot de passe</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <?php if (PRIVATE_REGISTRATION): ?>
            <div class="mb-3">
                <label class="form-label">Code d'invitation</label>
                <input type="text" name="invite_code" class="form-control" placeholder="Ex: aB1!c2D3@4" required>
            </div>
            <?php endif; ?>
            <button type="submit" class="btn btn-blurple">Continuer</button>
            <div class="auth-footer">
                Vous avez déjà un compte ? <a href="login.php">Se connecter</a>
            </div>
        </form>
    </div>
</body>
</html>
