<?php
if ($_FILES['file']) {
    $file = $_FILES['file'];
    //$uploadDir = 'uploads/';
	$uploadDir = 'app/web/upload/message/';
    $uploadFile = $uploadDir . basename($file['name']);

    // Check if the upload directory exists
    if (!is_dir($uploadDir)) {
        // Attempt to create the directory
        if (!mkdir($uploadDir, 0755, true)) {
            echo json_encode(['error' => 'Failed to create upload directory.']);
            exit;
        }
    }

    // Ensure directory has correct permissions (optional)
    chmod($uploadDir, 0755);

    // Validate file type (optional)
    $fileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));
    $validTypes = ['jpg', 'jpeg', 'png', 'gif','svg'];
    if (!in_array($fileType, $validTypes)) {
        echo json_encode(['error' => 'Invalid file type.']);
        exit;
    }

    // Move the uploaded file to the server
    if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
        // Return the file location as a JSON response
        echo json_encode(['location' => $uploadFile]);
    } else {
        echo json_encode(['error' => 'File upload failed: ' . error_get_last()['message']]);
    }
}
?>
