<?php
require_once 'includes/auth.php';
require_once 'config/database.php';

header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['image']) || !isset($data['oldUrl'])) {
    echo json_encode(['success' => false, 'error' => 'Données manquantes']);
    exit;
}

$imageData = $data['image'];
$oldUrl = $data['oldUrl'];
if (file_exists($oldUrl)) {
    unlink($oldUrl);
}
$imageData = str_replace('data:image/jpeg;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$imageBinary = base64_decode($imageData);
$upload_dir = 'uploads/photos/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
$filename = 'photo_' . uniqid() . '_' . time() . '.jpg';
$path = $upload_dir . $filename;
if (file_put_contents($path, $imageBinary)) {
    echo json_encode(['success' => true, 'newUrl' => $path]);
} else {
    echo json_encode(['success' => false, 'error' => 'Erreur sauvegarde']);
}