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

$apiKey = $_POST['api_key'] ?? '';
if (empty($apiKey)) {
    echo json_encode(['success' => false, 'message' => 'API Key missing']);
    exit;
}

$uploadDir = 'uploads/'; // Create this folder and make it writable (chmod 777)
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

$randomId = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 12);
$filename = $randomId . '.png';
$filepath = $uploadDir . $filename;
$url = 'https://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/' . $filepath;

$formData = new CURLFile(null); // Will be set below

if (!empty($_FILES['image_file']['tmp_name'])) {
    $formData = new CURLFile($_FILES['image_file']['tmp_name'], $_FILES['image_file']['type'], 'image.png');
} elseif (!empty($_POST['image_url'])) {
    $formData = ['image_url' => $_POST['image_url']];
} else {
    echo json_encode(['success' => false, 'message' => 'No image provided']);
    exit;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.remove.bg/v1.0/removebg');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-Api-Key: ' . $apiKey
]);

if ($formData instanceof CURLFile) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'image_file' => $formData,
        'size' => 'auto'
    ]);
} else {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
}

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

if ($httpCode == 200 && $response) {
    file_put_contents($filepath, $response);
    echo json_encode(['success' => true, 'url' => $url]);
} else {
    echo json_encode(['success' => false, 'message' => 'Remove.bg error: ' . $httpCode]);
}
?>