<?php
/**
 * Webhook Test Receiver
 * POST here to see the payload your webhook received
 * Access: https://fampay.adityahost.in/webhook_test.php
 */
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = file_get_contents('php://input');
    $headers = getallheaders();
    
    $log = [
        'received_at' => date('Y-m-d H:i:s'),
        'method' => $_SERVER['REQUEST_METHOD'],
        'remote_addr' => $_SERVER['REMOTE_ADDR'],
        'headers' => [
            'X-FamAPI-Event' => $headers['X-FamAPI-Event'] ?? 'N/A',
            'X-FamAPI-Signature' => $headers['X-FamAPI-Signature'] ?? 'N/A',
            'Content-Type' => $headers['Content-Type'] ?? 'N/A'
        ],
        'body_raw' => $body,
        'body_parsed' => json_decode($body, true) ?? ['error' => 'Invalid JSON']
    ];
    
    // Save to a log file
    $logFile = __DIR__ . '/webhook_test_log.json';
    $logs = [];
    if (file_exists($logFile)) {
        $logs = json_decode(file_get_contents($logFile), true) ?? [];
    }
    array_unshift($logs, $log);
    $logs = array_slice($logs, 0, 50); // keep last 50
    file_put_contents($logFile, json_encode($logs, JSON_PRETTY_PRINT));
    
    http_response_code(200);
    echo json_encode(['status' => 'received', 'message' => 'Webhook test received successfully']);
} else {
    // Show recent logs
    $logFile = __DIR__ . '/webhook_test_log.json';
    $logs = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) : [];
    echo json_encode(['status' => 'ok', 'message' => 'Webhook test endpoint is live', 'recent_logs' => $logs], JSON_PRETTY_PRINT);
}
