<?php
// File: public_html/upload_etalase.php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// 1. Cek Folder
$target_dir = "etalase/";
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0755, true); // 0755 biasanya cukup, 777 hanya jika perlu
}

// 2. Logika Upload
if (isset($_FILES['file_etalase'])) { // PERHATIKAN: Harus 'file_etalase' sesuai JS
    $file = $_FILES['file_etalase'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    // Validasi
    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    if (!in_array($ext, $allowed)) {
        echo json_encode(["status" => "error", "message" => "Hanya file gambar (JPG/PNG/WEBP)"]);
        exit;
    }

    if ($file['size'] > 5000000) { // 5MB Limit
        echo json_encode(["status" => "error", "message" => "File terlalu besar (Max 5MB)"]);
        exit;
    }

    // Nama File Baru (Anti Bentrok)
    $newName = time() . "_" . uniqid() . "." . $ext;
    $target_file = $target_dir . $newName;

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        // Deteksi URL Otomatis
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
        $domain = $_SERVER['HTTP_HOST'];
        $path = dirname($_SERVER['PHP_SELF']);
        $path = ($path == '/' || $path == '\\') ? '' : $path;
        
        $url = "$protocol://$domain$path/$target_file";
        
        echo json_encode(["status" => "success", "url" => $url]);
    } else {
        echo json_encode(["status" => "error", "message" => "Gagal memindahkan file ke folder etalase"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Tidak ada data file_etalase yang diterima"]);
}
?>