<?php
// Allow CORS and POST
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json");

// Define the upload directory
$uploadDir = dirname(__DIR__) . "/uploads/stories/";

// Make sure the directory exists
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

// Check if the request method is POST and file is received
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['story_image'])) {
    $file = $_FILES['story_image'];

    // Ensure there's no upload error
    if ($file['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $uniqueName = 'story_' . uniqid('', true) . '.' . $ext;
        $destination = $uploadDir . $uniqueName;

        if (move_uploaded_file($file['tmp_name'], $destination)) {
            // Generate URL to access image
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
            $host = $_SERVER['HTTP_HOST'];
            $imageUrl = $protocol . $host . '/mobile/api/uploads/stories/' . $uniqueName;

            echo json_encode(['success' => true, 'image_url' => $imageUrl]);
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to move uploaded file.']);
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Upload error: ' . $file['error']]);
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Invalid request.']);
}
