<?php
// Konfigurasi
$uploadDir = 'uploads/';
$processedDir = 'processed/';
$backgroundsDir = 'backgrounds/';
$pythonScript = 'scripts/remove_bg.py';

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Buat folder jika belum ada
if (!file_exists($uploadDir)) mkdir($uploadDir, 0755, true);
if (!file_exists($processedDir)) mkdir($processedDir, 0755, true);

// Proses upload
if (isset($_FILES['photo'])) {
    // Generate unique filename
    $fileName = uniqid() . '_' . basename($_FILES['photo']['name']);
    $uploadPath = $uploadDir . $fileName;
    
    // Cek ekstensi file
    $allowed = ['jpg', 'jpeg', 'png'];
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) {
        die("Hanya file JPG, JPEG, atau PNG yang diizinkan.");
    }

    if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadPath)) {
        // Set permission file
        chmod($uploadPath, 0644);
        
        // Dapatkan background yang dipilih
        $bgName = $_POST['background'];
        $bgPath = $backgroundsDir . $bgName;
        
        if (!file_exists($bgPath)) {
            die("File background tidak ditemukan.");
        }
        
        // Generate output filename
        $outputFilename = 'result_' . time() . '.png';
        $outputPath = $processedDir . $outputFilename;
        
        // Build command
        $command = escapeshellcmd("python3 " . $pythonScript) . " " . 
                  escapeshellarg($uploadPath) . " " . 
                  escapeshellarg($bgPath) . " " . 
                  escapeshellarg($outputPath) . " 2>&1";
        
        // Debug command
        echo "<h3>Command:</h3>";
        echo "<pre>" . htmlspecialchars($command) . "</pre>";
        
        // Eksekusi command
        exec($command, $output, $returnCode);
        
        // Debug output
        echo "<h3>Output:</h3>";
        echo "<pre>" . htmlspecialchars(implode("\n", $output)) . "</pre>";
        
        if ($returnCode === 0 && file_exists($outputPath)) {
            // Tampilkan hasil
            echo "<h2>Hasil Penggantian Background:</h2>";
            echo "<div style='display: flex; gap: 20px;'>";
            echo "<div style='border: 1px solid #ddd; padding: 10px;'>";
            echo "<h3>Foto Asli</h3>";
            echo "<img src='".htmlspecialchars($uploadPath)."' style='max-width: 400px;'>";
            echo "</div>";
            
            echo "<div style='border: 1px solid #ddd; padding: 10px;'>";
            echo "<h3>Hasil</h3>";
            echo "<img src='".htmlspecialchars($outputPath)."' style='max-width: 400px;'>";
            echo "<br><a href='".htmlspecialchars($outputPath)."' download>Download Hasil</a>";
            echo "</div>";
            echo "</div>";
        } else {
            echo "<h2 style='color: red;'>Gagal memproses gambar</h2>";
            echo "<p>Return code: " . $returnCode . "</p>";
            
            // Tampilkan error dari Python
            if (!empty($output)) {
                echo "<h3>Error Detail:</h3>";
                echo "<pre>" . htmlspecialchars(implode("\n", $output)) . "</pre>";
            }
            
            // Tampilkan permission info
            echo "<h3>Permission Info:</h3>";
            echo "<pre>";
            echo "Upload Path: " . (is_readable($uploadPath) ? "Readable" : "Not Readable") . "\n";
            echo "BG Path: " . (is_readable($bgPath) ? "Readable" : "Not Readable") . "\n";
            echo "Output Path: " . (is_writable(dirname($outputPath)) ? "Writable" : "Not Writable") . "\n";
            echo "</pre>";
        }
    } else {
        echo "Gagal mengupload file. Error: " . $_FILES['photo']['error'];
    }
} else {
    echo "Tidak ada file yang diupload.";
}
?>