<?php
if (!empty($_FILES['photo'])) {
    $uploads = __DIR__ . '/uploads/';
    $filename = uniqid() . "_" . basename($_FILES["photo"]["name"]);
    $target = $uploads . $filename;

    if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target)) {
        $apiKey = 'YOUR_FREE_API_KEY';
        $imageUrl = 'https://YOUR_DOMAIN/uploads/' . $filename; // Ubah ke URL sebenarnya
        $data = json_encode([
            'image_url' => $imageUrl,
            'output_format' => 'png'
        ]);

        $ch = curl_init('https://api.freeremovebackground.com/api/v1/mutate/remove-background');
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: Bearer ' . $apiKey
            ),
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data
        ));
        
        $res = curl_exec($ch);
        curl_close($ch);

        $json = json_decode($res, true);
        if (!empty($json['success']) && $json['success'] === true) {
            $maskUrl = $json['url'];
            $bgPath = __DIR__ . '/bg.jpg';
            $outPath = __DIR__ . '/processed/' . $filename . '.png';

            // Download hasil
            $imgData = file_get_contents($maskUrl);
            file_put_contents(__DIR__ . '/processed/temp.png', $imgData);

            // Gabungkan
            $cmd = escapeshellcmd("python3 merge_bg.py processed/temp.png bg.jpg $outPath");
            shell_exec($cmd);

            echo "<h2>Hasil:</h2><img src='processed/" . basename($outPath) . "' width='300'>";
        } else {
            echo "Gagal: " . (isset($json['error']) ? $json['error'] : 'Unknown error.');

        }
    } else {
        echo "Gagal mengunggah file.";
    }
} else {
    echo "Tidak ada file diunggah.";
}
?>
