<?php
// 1. PREVENT WHITESPACE CORRUPTION
// Ensure no whitespace exists before the <?php tag above.
error_reporting(E_ALL);
ini_set('display_errors', 0); 
ini_set('log_errors', 1);

// Start output buffering to catch any unwanted included whitespace
ob_start();

require 'db_connect.php'; 

// Clear any output generated by the include (like newlines in db_connect.php)
ob_clean(); 

header('Content-Type: application/json');
$response = array();

// 2. SERVER CHECKS
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    // Attempt to create it if it doesn't exist
    mkdir($uploadDir, 0777, true);
}

// 3. UPLOAD LOGIC
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {

    $uniqueName = uniqid() . '-' . basename($_FILES['image']['name']);
    $targetFilePath = $uploadDir . $uniqueName;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFilePath)) {
        
        $relativeImageUrl = $targetFilePath;

        // Prepare SQL
        $stmt = $conn->prepare("INSERT INTO media (image_url) VALUES (?)");
        
        if ($stmt) {
            $stmt->bind_param("s", $relativeImageUrl);
            
            if ($stmt->execute()) {
                // --- SUCCESS BLOCK ---
                // FIX: Build the full URL dynamically based on protocol (http/https)
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                $fullImageUrl = $protocol . "://" . $_SERVER['HTTP_HOST'] . "/api/" . $relativeImageUrl;

                // FIX: Add 'message' and 'error' keys (many Android apps expect these)
                $response['status'] = 'success';
                $response['error'] = false; 
                $response['message'] = 'Image uploaded successfully';
                $response['imagePath'] = $fullImageUrl;
                
                // IMPORTANT: Send 200 OK
                http_response_code(200);
            } else {
                http_response_code(500);
                $response['status'] = 'error';
                $response['error'] = true;
                $response['message'] = 'Database insert failed: ' . $stmt->error;
            }
            $stmt->close();
        } else {
            http_response_code(500);
            $response['status'] = 'error';
            $response['message'] = 'Database prepare failed';
        }
    } else {
        http_response_code(500);
        $response['status'] = 'error';
        $response['message'] = 'Failed to move uploaded file';
    }
} else {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'No valid file received';
}

// 4. FINAL OUTPUT
echo json_encode($response);
$conn->close();
?>