<?php
// Allow requests from any origin (CORS headers)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the file was uploaded
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        // Define the upload directory
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true); // Create directory if it doesn't exist
        }

        // Get the uploaded file information
        $fileTmpPath = $_FILES['file']['tmp_name'];
        $fileName = $_FILES['file']['name'];
        $fileSize = $_FILES['file']['size'];
        $fileType = $_FILES['file']['type'];

        // Ensure the file name is unique by appending a timestamp
        $fileNameNew = time() . '_' . $fileName;
        $dest_path = $uploadDir . $fileNameNew;

        // Move the file to the upload directory
        if (move_uploaded_file($fileTmpPath, $dest_path)) {
            // File upload was successful
            $response = array(
                'status' => 'success',
                'message' => 'File uploaded successfully!',
                'file_url' => 'https://your-domain.com/' . $dest_path // Adjust the base URL accordingly
            );
        } else {
            // Error occurred while moving the uploaded file
            $response = array(
                'status' => 'error',
                'message' => 'Error moving the uploaded file.'
            );
        }
    } else {
        // Error handling if no file was uploaded
        $response = array(
            'status' => 'error',
            'message' => 'No file uploaded or there was an upload error.'
        );
    }
} else {
    // Only POST requests are allowed
    $response = array(
        'status' => 'error',
        'message' => 'Invalid request method. Only POST is allowed.'
    );
}

// Return JSON response
echo json_encode($response);
