<?php
// Enable error reporting and logging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
ini_set('error_log', __DIR__ . '/debug.log');

// Debug script to inspect incoming requests

// Add CORS // Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';
 
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Log all incoming request data
$method = $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN';
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$raw_input = file_get_contents('php://input');

// Create log entry
$log_entry = [
    'time' => date('Y-m-d H:i:s'),
    'method' => $method,
    'content_type' => $contentType,
    'get_data' => $_GET,
    'post_data' => $_POST,
    'raw_input' => $raw_input,
    'input_as_json' => json_decode($raw_input, true),
    'json_error' => json_last_error_msg()
];

// Write to log file
error_log(print_r($log_entry, true));

// Return debug info
echo json_encode([
    'success' => true,
    'debug_info' => $log_entry
]);
