<?php
require_once __DIR__ . '/../auth/session.php';
require_once __DIR__ . '/../includes/permissions.php';

header('Content-Type: application/json');

$user = getCurrentUser();
if (!$user) {
    echo json_encode(['success' => false, 'error' => 'Non autorisé']);
    exit;
}

$server_id = $_POST['server_id'] ?? 0;
if (!$server_id) {
    echo json_encode(['success' => false, 'error' => 'ID de serveur manquant']);
    exit;
}

// Permissions check
$can_manage = Permissions::hasPermission($user['id'], $server_id, Permissions::MANAGE_SERVER) || Permissions::hasPermission($user['id'], $server_id, Permissions::ADMINISTRATOR);
// Also check owner
$stmt = db()->prepare("SELECT owner_id FROM servers WHERE id = ?");
$stmt->execute([$server_id]);
$server = $stmt->fetch();
$is_owner = ($server && $server['owner_id'] == $user['id']);

if (!$is_owner && !$can_manage) {
    echo json_encode(['success' => false, 'error' => 'Permissions insuffisantes']);
    exit;
}

if (!isset($_FILES['badge_image']) || $_FILES['badge_image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'error' => 'Aucun fichier reçu']);
    exit;
}

$file = $_FILES['badge_image'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
$maxSize = 1 * 1024 * 1024; // 1MB for badges

if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'error' => 'Format non supporté']);
    exit;
}

if ($file['size'] > $maxSize) {
    echo json_encode(['success' => false, 'error' => 'Fichier trop gros (max 1Mo)']);
    exit;
}

$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
if (empty($extension)) {
    $extensions = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
        'image/svg+xml' => 'svg'
    ];
    $extension = $extensions[$file['type']] ?? 'png';
}

$filename = 'badge_' . $server_id . '_' . time() . '_' . rand(1000, 9999) . '.' . $extension;
$dir = __DIR__ . '/../assets/images/badges/';
if (!is_dir($dir)) mkdir($dir, 0775, true);

$targetPath = $dir . $filename;
$relativeUrl = 'assets/images/badges/' . $filename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode(['success' => true, 'url' => $relativeUrl]);
} else {
    echo json_encode(['success' => false, 'error' => 'Erreur d\'écriture']);
}
