<?php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error.']);
        exit;
    }

    $file = $_FILES['image'];
    $allowedTypes = ['image/png', 'image/jpeg'];
    if (!in_array($file['type'], $allowedTypes)) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type. Only PNG, JPG, JPEG allowed.']);
        exit;
    }

    if ($file['size'] > 20 * 1024 * 1024) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'File too large. Maximum size is 20MB.']);
        exit;
    }

    $uploadDir = __DIR__ . '/uploads/images/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safeName = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
    $targetFile = $uploadDir . $safeName;

    if (move_uploaded_file($file['tmp_name'], $targetFile)) {
        echo json_encode(['status' => 'success', 'file' => 'uploads/images/' . $safeName]);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Could not move uploaded file.']);
    }
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
