<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method tidak diizinkan']);
    exit;
}

if (!isset($_FILES['image']) || $_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) {
    echo json_encode(['success' => false, 'message' => 'Tidak ada file yang diunggah']);
    exit;
}

$file = $_FILES['image'];
$maxSize = 20 * 1024 * 1024; // 20MB
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];

// Validasi
if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Error upload: ' . $file['error']]);
    exit;
}

if ($file['size'] > $maxSize) {
    echo json_encode(['success' => false, 'message' => 'File terlalu besar (maks 20MB)']);
    exit;
}

if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'Format file tidak didukung']);
    exit;
}

// Buat folder uploads jika belum ada
if (!is_dir('../uploads')) {
    mkdir('../uploads', 0755, true);
}

// Generate nama unik
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '_' . time() . '.' . $extension;
$destination = '../uploads/' . $filename;

// Pindahkan file
if (move_uploaded_file($file['tmp_name'], $destination)) {
    // URL gambar
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") 
               . "://$_SERVER[HTTP_HOST]";
    $imageUrl = $baseUrl . '/uploads/' . $filename;
    
    echo json_encode([
        'success' => true,
        'message' => 'Upload berhasil',
        'filename' => $filename,
        'url' => $imageUrl,
        'direct_link' => $imageUrl,
        'bb_code' => '[img]' . $imageUrl . '[/img]',
        'html_code' => '<img src="' . $imageUrl . '" alt="Uploaded image">',
        'size' => $file['size'],
        'type' => $file['type']
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan file']);
}
?>