<?php
// 1. HEADER CORS ANTI-BLOKIR
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
} else {
    header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Origin, Accept");

// 2. TANGANI PREFLIGHT REQUEST
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

// --- KEAMANAN: TOKEN RAHASIA ---
$SECRET_TOKEN = "caxuga_rahasia_123";

if (!isset($_POST['token']) || $_POST['token'] !== $SECRET_TOKEN) {
    http_response_code(401);
    echo json_encode(['error' => 'Akses ditolak! Token keamanan tidak valid.']);
    exit;
}

// --- FOLDER TUJUAN BARU: 'file/' ---
$uploadDir = 'file/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// --- LOGIKA HAPUS FILE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $fileToDelete = basename($_POST['delete']);
    if (file_exists($uploadDir . $fileToDelete)) {
        unlink($uploadDir . $fileToDelete);
    }
    echo json_encode(['status' => 'deleted']);
    exit;
}

// --- LOGIKA TERIMA UPLOAD FILE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $fileName = basename($file['name']);
    
    // Bersihkan nama file
    $fileName = preg_replace("/[^a-zA-Z0-9.-]/", "_", $fileName);
    $targetPath = $uploadDir . $fileName;

    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        // Balas dengan URL lengkap dari subdomain
        $url = $protocol . "://" . $_SERVER['HTTP_HOST'] . "/" . $targetPath;
        echo json_encode(['url' => $url]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Gagal memindahkan file. Cek permission folder file di cPanel.']);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Tidak ada file yang dikirim.']);
}
?>