<?php
require_once __DIR__ . '/common.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input_data = null;
    $request_type = null;
    $contentType = trim(strtolower($_SERVER['HTTP_CONTENT_TYPE'] ?? $_SERVER['CONTENT_TYPE'] ?? ''));

    if (strpos($contentType, 'application/json') === 0) {
        $raw_post_data = file_get_contents('php://input');

        if ($raw_post_data === false || $raw_post_data === '') {
            send_error(400, 'Received empty request body or could not read input.', "Error: Could not read php://input or it was empty.");
        }

        $input_data = json_decode($raw_post_data, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            send_error(400, 'Invalid JSON payload received.', 'JSON Decode Error: ' . json_last_error_msg() . " | Raw data snippet: " . substr($raw_post_data, 0, 100));
        } elseif (!is_array($input_data)) {
            send_error(400, 'Invalid JSON payload: Expected a JSON object.', "JSON Decode Warning: Result is not an array. Data: " . print_r($input_data, true));
        } else {
            $request_type = $input_data['request_type'] ?? null;
        }
    } else {
        send_error(415, 'Unsupported Media Type. This endpoint requires application/json.', "Unsupported Media Type Received: " . $contentType);
    }

    if ($request_type === null) {
        if (is_array($input_data) && !isset($input_data['request_type'])) {
            send_error(400, 'Missing "request_type" field within the request payload.');
        } else {
            send_error(400, 'Missing required parameter: request_type (or processing error).');
        }
    }

    $dbconn = getDBConnection();
    
    switch ($request_type) {
        case 'ohgo':
            handle_ohgo_request($dbconn, $input_data);
            break;
        case 'ohgonopoly':
            handle_ohgo_request_no_poly($dbconn, $input_data);
            break;
        case 'power':
            handle_power_request($dbconn, $input_data);
            break;
        case 'powernopoly':
            handle_power_request_no_poly($dbconn, $input_data);
            break;
        case 'wupoly':
            handle_wu_request_poly($dbconn, $input_data);
            break;
        case 'campoly':
            handle_cam_request($dbconn, $input_data);
            break;
        default:
            send_error(400, 'Invalid request_type specified: ' . htmlspecialchars($request_type));
            break;
    }
} else {
    http_response_code(405);
    header('Allow: POST');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'Invalid request method. Only POST is allowed.']);
    exit;
}
?>