<?php
/*
 * Webhook Handler for BoxCoin Payment Confirmations
 * Forwards successful payments to limitx.app/verify.html
 */

// Get the raw POST data
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Log the incoming webhook for debugging
file_put_contents(__DIR__ . '/webhook_log.txt', date('Y-m-d H:i:s') . " - Received: " . $input . "\n", FILE_APPEND);

// Check if this is a payment completion webhook
if (isset($data['status']) && $data['status'] === 'completed') {
    // Prepare data to send to limitx.app
    $postData = [
        'secret' => 'Hamza@1231',
        'transaction_id' => $data['id'] ?? '',
        'amount' => $data['amount'] ?? '',
        'amount_fiat' => $data['amount_fiat'] ?? '',
        'cryptocurrency' => $data['cryptocurrency'] ?? '',
        'currency' => $data['currency'] ?? '',
        'status' => $data['status'],
        'external_reference' => $data['external_reference'] ?? '',
        'hash' => $data['hash'] ?? '',
        'timestamp' => time()
    ];

    // Send POST request to limitx.app/verify.html
    $ch = curl_init('https://limitx.app/verify.html');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'User-Agent: BoxCoin-Webhook/1.0'
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For testing, remove in production
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Log the response
    file_put_contents(__DIR__ . '/webhook_log.txt', date('Y-m-d H:i:s') . " - Sent to limitx.app: HTTP $httpCode - Response: " . $response . "\n", FILE_APPEND);

    // Respond to BoxCoin webhook
    http_response_code(200);
    echo json_encode(['status' => 'success', 'message' => 'Webhook forwarded successfully']);
} else {
    // Not a completion webhook, just acknowledge
    http_response_code(200);
    echo json_encode(['status' => 'ignored', 'message' => 'Not a completion webhook']);
}
?>
