<?php
// upload_image.php

// Allow CORS (optional)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type");
header('Content-Type: application/json');

// Check if action=insertimg
if (isset($_GET['action']) && $_GET['action'] === 'insertimg') {

    // Make sure a file was uploaded
    if (!empty($_FILES) && isset($_FILES['file'])) {

        // Create upload folder if not exists
        if (!is_dir('upload')) {
            mkdir('upload', 0777, true);
        }

        // Create a unique file path
        $file_name = '_' . uniqid() . '_' . basename($_FILES['file']['name']);
        $path = 'upload/' . $file_name;

        // URL where the file will be accessible
        $url = "https://ballandbat.com/imageupload/" . $path;  
        // Change domain to yours

        $result = array();

        // Try moving uploaded file
        if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
            $result['result'] = 1;
            $result['imgurl'] = $url;
        } else {
            $result['result'] = 0;
            $result['imgurl'] = "";
        }

        echo json_encode($result);
        exit;
    }

    // No file found
    echo json_encode([
        'result' => 0,
        'imgurl' => '',
        'error' => 'No file uploaded'
    ]);
    exit;
}

echo json_encode([
    'result' => 0,
    'error' => 'Invalid action'
]);
exit;
?>
