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

// IMPORTANTE: RECUERDA PONER TU API KEY
$apiKey = '2b7bc92a8facaa376f2d24462f7d5f44098e0673fe5c1b3bc04f065bf39a5bc727979cba651a67e05f808b556a1f35ae';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['image_file'])) {
    http_response_code(400);
    echo json_encode(['error' => 'No se recibió ninguna imagen para convertir a boceto.']);
    exit;
}

$file = $_FILES['image_file'];
$filePath = $file['tmp_name'];
$fileName = $file['name'];
$fileType = $file['type'];

// URL CORRECTA
$url = 'https://clipdrop-api.co/sketch/v1/file';

// Preparar la petición a la API de ClipDrop
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$postFields = [
    'image_file' => new CURLFile($filePath, $fileType, $fileName),
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

$headers = [
    'x-api-key: ' . $apiKey,
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpcode == 200) {
    // La API devuelve directamente la imagen del boceto
    $base64 = 'data:image/png;base64,' . base64_encode($response);
    echo json_encode(['success' => true, 'sketch_base64' => $base64]);
} else {
    http_response_code($httpcode);
    echo json_encode(['error' => 'La API de Boceto falló.', 'details' => json_decode($response)]);
}
?>
