<?php
require_once __DIR__ . '/../auth/session.php';
require_once __DIR__ . '/../includes/utils.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $server_id = $_POST['server_id'] ?? 0;
    $user_id = $_SESSION['user_id'];
    
    require_once __DIR__ . '/../includes/permissions.php';
    if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_SERVER) || Permissions::hasPermission($user_id, $server_id, Permissions::ADMINISTRATOR)) {
        $new_invite_code = generateInviteCode();
        $expires_at = date('c', time() + 1800); // ISO 8601 format
        
        $stmt = db()->prepare("UPDATE servers SET invite_code = ?, invite_code_expires_at = ? WHERE id = ?");
        $stmt->execute([$new_invite_code, date('Y-m-d H:i:s', time() + 1800), $server_id]);
        
        echo json_encode([
            'success' => true,
            'invite_code' => $new_invite_code,
            'expires_at' => $expires_at
        ]);
        exit;
    }
}

echo json_encode(['success' => false, 'error' => 'Permission denied']);
