<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Config
$target_dir = "uploads/";
$allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

// Ensure upload dir exists
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {

        $file_tmp = $_FILES['image']['tmp_name'];
        $file_name = $_FILES['image']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Validate Type
        if (!in_array($file_ext, $allowed_types)) {
            echo json_encode(['success' => false, 'error' => 'Invalid file type. Only JPG, PNG, GIF, WEBP allowed.']);
            exit;
        }

        // Generate Unique Name
        $new_name = uniqid('img_', true) . '.' . $file_ext;
        $target_file = $target_dir . $new_name;

        // Move File
        if (move_uploaded_file($file_tmp, $target_file)) {
            // Return valid URL (assuming server root is parent of 'server')
            // Adjust this path based on where home.html is running relative to the server
            // If running php -S localhost:8000 from Ghadget root:
            // URL should be server/uploads/filename
            $url = 'server/' . $target_file;
            echo json_encode(['success' => true, 'url' => $url]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to move uploaded file.']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'No file uploaded or upload error code: ' . $_FILES['image']['error']]);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
}
