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

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

$image_id = filter_input(INPUT_POST, 'image_id', FILTER_VALIDATE_INT);
$annotations = $_POST['annotations'] ?? '';
$image_data = $_POST['image_data'] ?? ''; // base64 du canvas

if (!$image_id) {
    echo json_encode(['success' => false, 'error' => 'ID image manquant.']);
    exit;
}

$pdo = getPDO();

// Récupérer le chemin de l'image originale
$stmt = $pdo->prepare("SELECT image_path FROM fiches_images WHERE id = ?");
$stmt->execute([$image_id]);
$row = $stmt->fetch();
if (!$row) {
    echo json_encode(['success' => false, 'error' => 'Image introuvable.']);
    exit;
}
$original_path = $row['image_path'];

// Sauvegarder l'image annotée
$annotated_path = null;
if (!empty($image_data)) {
    // Extraire base64
    if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $matches)) {
        $type = $matches[1];
        $image_data = substr($image_data, strpos($image_data, ',') + 1);
        $image_data = base64_decode($image_data);
        $upload_dir = 'uploads/fiches_images/';
        $filename = 'annotated_' . basename($original_path);
        $annotated_path = $upload_dir . $filename;
        file_put_contents($annotated_path, $image_data);
    }
}

// Mise à jour de la base
$stmt = $pdo->prepare("UPDATE fiches_images SET annotations = ?, annotated_image_path = ? WHERE id = ?");
if ($stmt->execute([$annotations, $annotated_path, $image_id])) {
    logAction($pdo, $_SESSION['user_id'], 'save_annotations', "Image ID $image_id");
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => 'Erreur lors de la sauvegarde.']);
}