<?php
// ============================================================
// upload.php — réception d'une image, conversion WebP, stockage.
// Renvoie du JSON : { ok, url, name, w, h, size } ou { ok:false, error }
// ============================================================
header('Content-Type: application/json; charset=utf-8');

$MEDIAS_DIR = dirname(__DIR__) . '/medias';
$MAX_DIM    = 2000;   // côté max en pixels (redimensionne si plus grand)
$QUALITY    = 82;     // qualité WebP

function fail($msg){ echo json_encode(['ok'=>false,'error'=>$msg]); exit; }

// 1. Récupérer les bytes de l'image, soit via fichier uploadé, soit via base64 (coller)
$bytes = null;
$origName = 'image';

if (!empty($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
    $bytes = file_get_contents($_FILES['file']['tmp_name']);
    if (!empty($_FILES['file']['name'])) $origName = $_FILES['file']['name'];
} elseif (!empty($_POST['data'])) {
    // data URL : "data:image/png;base64,...."
    $data = $_POST['data'];
    if (preg_match('#^data:image/[\w.+-]+;base64,#', $data)) {
        $data = preg_replace('#^data:image/[\w.+-]+;base64,#', '', $data);
    }
    $bytes = base64_decode($data, true);
    if (!empty($_POST['name'])) $origName = $_POST['name'];
}

if ($bytes === null || strlen($bytes) < 10) fail('Aucune image reçue.');

// 2. Charger l'image via GD
$src = @imagecreatefromstring($bytes);
if (!$src) fail('Format d\'image non reconnu.');

$w = imagesx($src);
$h = imagesy($src);

// 3. Redimensionner si trop grand (en gardant les proportions)
if ($w > $MAX_DIM || $h > $MAX_DIM) {
    $ratio = min($MAX_DIM / $w, $MAX_DIM / $h);
    $nw = (int)round($w * $ratio);
    $nh = (int)round($h * $ratio);
    $dst = imagecreatetruecolor($nw, $nh);
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $w,$h);
    imagedestroy($src);
    $src = $dst;
    $w = $nw; $h = $nh;
}

// 4. Construire un nom de fichier propre et unique
$base = pathinfo($origName, PATHINFO_FILENAME);
$base = strtolower($base);
$base = preg_replace('/[^a-z0-9]+/', '-', $base);
$base = trim($base, '-');
if ($base === '') $base = 'image';
$base = substr($base, 0, 40);
$fname = $base . '-' . substr(md5($bytes . microtime()), 0, 6) . '.webp';
$path  = $MEDIAS_DIR . '/' . $fname;

// 5. Enregistrer en WebP
if (!imagewebp($src, $path, $QUALITY)) { imagedestroy($src); fail('Échec de l\'enregistrement WebP.'); }
imagedestroy($src);

$url = 'medias/' . $fname;
echo json_encode([
    'ok'   => true,
    'url'  => $url,
    'full' => 'https://tuinaloygue.fr/' . $url,
    'name' => $fname,
    'w'    => $w,
    'h'    => $h,
    'size' => filesize($path),
]);
