<?php
session_start();
header('Content-Type: application/json');

// Debug mode - log everything
$debugFile = __DIR__ . '/../../debug_hold_bills.log';

// Log raw input
$rawInput = file_get_contents('php://input');
file_put_contents($debugFile, "=== " . date('Y-m-d H:i:s') . " ===\n", FILE_APPEND);
file_put_contents($debugFile, "Raw Input Length: " . strlen($rawInput) . "\n", FILE_APPEND);
file_put_contents($debugFile, "Raw Input (first 500 chars): " . substr($rawInput, 0, 500) . "\n", FILE_APPEND);

// Try to decode
$data = json_decode($rawInput, true);
$jsonError = json_last_error();

file_put_contents($debugFile, "JSON Error Code: " . $jsonError . "\n", FILE_APPEND);
file_put_contents($debugFile, "JSON Error Message: " . json_last_error_msg() . "\n", FILE_APPEND);

if ($jsonError === JSON_ERROR_NONE) {
    file_put_contents($debugFile, "Data decoded successfully\n", FILE_APPEND);
    file_put_contents($debugFile, "Items count: " . (isset($data['items']) ? count($data['items']) : 0) . "\n", FILE_APPEND);
    if (isset($data['items']) && count($data['items']) > 0) {
        file_put_contents($debugFile, "First item: " . print_r($data['items'][0], true) . "\n", FILE_APPEND);
    }
} else {
    file_put_contents($debugFile, "JSON DECODE FAILED!\n", FILE_APPEND);
    
    // Try to find the problematic character
    for ($i = 0; $i < strlen($rawInput); $i++) {
        $char = $rawInput[$i];
        $ord = ord($char);
        if ($ord < 32 && $ord != 9 && $ord != 10 && $ord != 13) {
            file_put_contents($debugFile, "Found control char at position $i: ord=$ord\n", FILE_APPEND);
        }
    }
}

file_put_contents($debugFile, "\n\n", FILE_APPEND);

// Return the actual error
echo json_encode([
    'success' => false,
    'message' => 'Debug mode - check debug_hold_bills.log file',
    'jsonError' => $jsonError,
    'jsonErrorMsg' => json_last_error_msg(),
    'inputLength' => strlen($rawInput)
]);
?>
