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

// Log webhook requests for debugging
$logFile = 'webhook-spliteasy.log';
$timestamp = date('Y-m-d H:i:s');
$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestHeaders = getallheaders();
$requestBody = file_get_contents('php://input');

$logData = "[$timestamp] Method: $requestMethod\n";
$logData .= "Headers: " . json_encode($requestHeaders, JSON_PRETTY_PRINT) . "\n";
$logData .= "Body: $requestBody\n\n";

file_put_contents($logFile, $logData, FILE_APPEND);

// Process the webhook payload
$payload = json_decode($requestBody, true);

if ($payload) {
    // Example: Extract transaction ID and status
    $transactionId = $payload['data']['id'] ?? 'N/A';
    $status = $payload['data']['status'] ?? 'N/A';
    $eventType = $payload['type'] ?? 'N/A';

    // Log specific transaction status changes
    $statusLog = "[$timestamp] Webhook received for Transaction ID: $transactionId, Event Type: $eventType, New Status: $status\n";
    file_put_contents($logFile, $statusLog, FILE_APPEND);

    // Here you would update your database with the new transaction status
    // For now, we just log it.

    // Respond with 200 OK to acknowledge receipt
    http_response_code(200);
    echo json_encode(['status' => 'success', 'message' => 'Webhook received and processed']);
} else {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid webhook payload']);
}
?>
