<?php
// Header CORS
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit(); }

// Debug Error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 1. Buat Folder jika belum ada
$target_dir = "uploads/";
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0755, true);
}

if (isset($_FILES['photo'])) {
    $file = $_FILES['photo'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = "img_" . time() . "_" . rand(100,999) . "." . $ext;
    $target_file = $target_dir . $filename;

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        // URL HASIL (Ganti domain jika perlu, atau biarkan relatif jika proxy menangani)
        // Kita kirim full URL agar aman
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $path = dirname($_SERVER['REQUEST_URI']);
        $image_url = $protocol . "://" . $host . $path . "/" . $target_file;
        
        http_response_code(201);
        echo json_encode(["status" => "success", "image_url" => $image_url]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Gagal memindahkan file. Cek permission folder."]);
    }
} else {
    http_response_code(400);
    echo json_encode(["error" => "Tidak ada file yang dikirim."]);
}
?>