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

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

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

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

$file = $_FILES['avatar'];
$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 = 'avatar_' . $user['id'] . '_' . time() . '.' . $extension;
$targetPath = __DIR__ . '/../assets/images/avatars/' . $filename;
$relativeUrl = 'assets/images/avatars/' . $filename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    // Optionally delete old local avatar if it exists
    if (!empty($user['avatar_url']) && strpos($user['avatar_url'], 'assets/images/avatars/') === 0) {
        $oldFile = __DIR__ . '/../' . $user['avatar_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']);
}
