<?php
// admin/media_action.php — actions médiathèque (JSON). Protégé par login.
require_once dirname(__DIR__) . '/inc/schema.php';
require_once dirname(__DIR__) . '/inc/auth.php';
auth_require();
header('Content-Type: application/json; charset=utf-8');
header('X-LiteSpeed-Cache-Control: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
init_schema();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$db = db();

function out($a){ echo json_encode($a); exit; }

if ($action === 'list') {
    $rows = $db->query('SELECT * FROM medias ORDER BY cree_le DESC, id DESC')->fetchAll();
    foreach ($rows as &$r) { $r['full'] = SITE_URL . '/' . $r['url']; }
    out($rows);
}

if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    $st = $db->prepare('SELECT * FROM medias WHERE id = ?');
    $st->execute([$id]);
    $m = $st->fetch();
    if (!$m) out(['ok'=>false,'error'=>'Introuvable']);
    $path = MEDIAS_DIR . '/' . $m['fichier'];
    if (is_file($path)) @unlink($path);
    $db->prepare('DELETE FROM medias WHERE id = ?')->execute([$id]);
    out(['ok'=>true]);
}

if ($action === 'upload') {
    $MAX_DIM = 2000; $Q = 82;
    $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']);
        $origName = $_FILES['file']['name'] ?? 'image';
    } elseif (!empty($_POST['data'])) {
        $d = preg_replace('#^data:image/[\w.+-]+;base64,#', '', $_POST['data']);
        $bytes = base64_decode($d, true);
        $origName = $_POST['name'] ?? 'collee';
    }
    if (!$bytes || strlen($bytes) < 10) out(['ok'=>false,'error'=>'Aucune image reçue.']);

    $src = @imagecreatefromstring($bytes);
    if (!$src) out(['ok'=>false,'error'=>'Format non reconnu.']);
    $w = imagesx($src); $h = imagesy($src);
    if ($w > $MAX_DIM || $h > $MAX_DIM) {
        $r = min($MAX_DIM/$w, $MAX_DIM/$h);
        $nw=(int)round($w*$r); $nh=(int)round($h*$r);
        $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;
    }
    $base = slugify(pathinfo($origName, PATHINFO_FILENAME));
    $base = substr($base, 0, 40);
    $fname = $base . '-' . substr(md5($bytes.microtime()),0,6) . '.webp';
    $path = MEDIAS_DIR . '/' . $fname;
    if (!imagewebp($src, $path, $Q)) { imagedestroy($src); out(['ok'=>false,'error'=>'Échec WebP.']); }
    imagedestroy($src);

    $url = 'medias/' . $fname;
    $ins = $db->prepare('INSERT INTO medias (fichier,url,largeur,hauteur,poids,source) VALUES (?,?,?,?,?,?)');
    $ins->execute([$fname, $url, $w, $h, filesize($path), 'upload']);
    out(['ok'=>true,'id'=>$db->lastInsertId(),'url'=>$url,'full'=>SITE_URL.'/'.$url,'name'=>$fname,'w'=>$w,'h'=>$h]);
}

out(['ok'=>false,'error'=>'Action inconnue']);
