<?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 du serveur manquant']);
    exit;
}

if (!Permissions::hasPermission($user['id'], $server_id, Permissions::MANAGE_SERVER)) {
    echo json_encode(['success' => false, 'error' => 'Vous n\'avez pas la permission de gérer ce serveur']);
    exit;
}

if (!isset($_FILES['icon']) || $_FILES['icon']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'error' => 'Aucun fichier reçu ou erreur de téléchargement']);
    exit;
}

$file = $_FILES['icon'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
$maxSize = 2 * 1024 * 1024; // 2MB

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

if ($file['size'] > $maxSize) {
    echo json_encode(['success' => false, 'error' => 'Le fichier est trop volumineux (max 2Mo)']);
    exit;
}

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

$filename = 'server_' . $server_id . '_' . time() . '.' . $extension;
$dir = __DIR__ . '/../assets/images/servers/';
if (!is_dir($dir)) {
    mkdir($dir, 0775, true);
}

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

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    // Optionally fetch old icon to delete it if it's local
    $stmt = db()->prepare("SELECT icon_url FROM servers WHERE id = ?");
    $stmt->execute([$server_id]);
    $server = $stmt->fetch();
    
    if ($server && !empty($server['icon_url']) && strpos($server['icon_url'], 'assets/images/servers/') === 0) {
        $oldFile = __DIR__ . '/../' . $server['icon_url'];
        if (file_exists($oldFile)) {
            unlink($oldFile);
        }
    }

    echo json_encode(['success' => true, 'url' => $relativeUrl]);
} else {
    echo json_encode(['success' => false, 'error' => 'Erreur lors de l\'enregistrement du fichier']);
}
