<?php
// api-upload.php
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['status' => 'error', 'message' => 'POST only'], 405);
}

requireAdmin();

if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    jsonResponse(['status' => 'error', 'message' => 'File tidak valid'], 400);
}

$file = $_FILES['image'];
if ($file['size'] > UPLOAD_MAX_SIZE) {
    jsonResponse(['status' => 'error', 'message' => 'File terlalu besar (max 2MB)'], 400);
}

$allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!in_array($file['type'], $allowed)) {
    jsonResponse(['status' => 'error', 'message' => 'Format tidak didukung. Gunakan JPG, PNG, WebP, atau GIF.'], 400);
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = 'product_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$uploadPath = __DIR__ . '/' . UPLOAD_DIR;
if (!is_dir($uploadPath)) {
    mkdir($uploadPath, 0755, true);
}

$dest = $uploadPath . $filename;
if (!move_uploaded_file($file['tmp_name'], $dest)) {
    jsonResponse(['status' => 'error', 'message' => 'Gagal upload file'], 500);
}

jsonResponse([
    'status' => 'success',
    'image' => BASE_URL . '/' . UPLOAD_DIR . $filename,
    'filename' => $filename,
]);
