<?php

/**
 * Normalize Android / legacy sales payloads for the Node bulk sync API.
 *
 * Handles:
 * - '{"JSonObject":[{...}]}' string
 * - Wrapping single/double quotes from form posts
 * - Bare JSON arrays [{...}]
 * - Already-decoded PHP arrays
 */
function mch_normalize_sales_payload($raw)
{
    if (is_array($raw)) {
        if (isset($raw['JSonObject']) || isset($raw['JsonObject']) || isset($raw['jsonObject'])) {
            return $raw;
        }

        return array('JSonObject' => $raw);
    }

    if (!is_string($raw)) {
        return array('JSonObject' => array());
    }

    $payload = stripslashes(trim($raw));
    if ($payload === '') {
        return array('JSonObject' => array());
    }

    $payload = mch_strip_wrapping_quotes($payload);

    $decoded = json_decode($payload, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        return mch_wrap_json_object($decoded);
    }

    // Legacy PHP format: {"JSonObject":[...]} with manual brace trim
    if (stripos($payload, '{"JSonObject":') !== false || stripos($payload, '{"JsonObject":') !== false) {
        $legacy = preg_replace('/^\s*\{\s*"(?:JSonObject|JsonObject|jsonObject)"\s*:\s*/i', '', $payload);
        $legacy = rtrim($legacy);
        if (substr($legacy, -1) === '}') {
            $legacy = substr($legacy, 0, -1);
        }

        $decoded = json_decode($legacy, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            return array('JSonObject' => $decoded);
        }
    }

    if ($payload !== '' && $payload[0] === '[') {
        $decoded = json_decode($payload, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            return array('JSonObject' => $decoded);
        }
    }

    throw new InvalidArgumentException(
        'Invalid sales JSON payload: ' . json_last_error_msg()
    );
}

/**
 * Remove outer '...' or "..." wrappers sometimes sent by mobile clients.
 */
function mch_strip_wrapping_quotes($value)
{
    $value = trim($value);

    while (strlen($value) >= 2) {
        $first = $value[0];
        $last = $value[strlen($value) - 1];

        if (($first === "'" && $last === "'") || ($first === '"' && $last === '"')) {
            $value = trim(substr($value, 1, -1));
            continue;
        }

        break;
    }

    // Stray leading quote before [ or {
    $value = preg_replace("/^['\"]+/", '', $value);
    $value = preg_replace("/['\"]+$/", '', $value);

    return trim($value);
}

/**
 * @param array $decoded
 * @return array
 */
function mch_wrap_json_object(array $decoded)
{
    if (isset($decoded['JSonObject']) || isset($decoded['JsonObject']) || isset($decoded['jsonObject'])) {
        return $decoded;
    }

    if (mch_is_list_array($decoded)) {
        return array('JSonObject' => $decoded);
    }

    return $decoded;
}

/**
 * @param array $arr
 * @return bool
 */
function mch_is_list_array(array $arr)
{
    if ($arr === array()) {
        return true;
    }

    return array_keys($arr) === range(0, count($arr) - 1);
}
