<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array("message" => "Method not allowed."));
    exit;
}

if (!isset($_FILES['picture']) || $_FILES['picture']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(array("message" => "No file uploaded or upload error."));
    exit;
}

$uploadDir = '/var/www/html/uploads/';
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$file = $_FILES['picture'];
$fileType = $file['type'];
$fileSize = $file['size'];
$fileName = $file['name'];
$tmpName = $file['tmp_name'];

if (!in_array($fileType, $allowedTypes)) {
    http_response_code(400);
    echo json_encode(array("message" => "Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed."));
    exit;
}

if ($fileSize > $maxFileSize) {
    http_response_code(400);
    echo json_encode(array("message" => "File too large. Maximum size is 5MB."));
    exit;
}

$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
$uniqueFileName = uniqid() . '.' . $fileExtension;
$uploadPath = $uploadDir . $uniqueFileName;

if (move_uploaded_file($tmpName, $uploadPath)) {
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
    // Remove /var/www/html/ from the path and create proper URL
    $relativePath = str_replace('/var/www/html/', '', $uploadPath);
    $fullUrl = $baseUrl . '/' . $relativePath;
    
    http_response_code(200);
    echo json_encode(array(
        "message" => "File uploaded successfully.",
        "filename" => $uniqueFileName,
        "url" => $fullUrl
    ));
} else {
    http_response_code(500);
    echo json_encode(array("message" => "Failed to upload file."));
}
?>
