<?php
/**
 * BayarCash Webhook Test Script
 *
 * This script simulates a BayarCash webhook callback to test the integration.
 *
 * Usage:
 * php tests/test-webhook.php
 */

// Test payload - simulates a successful payment callback from BayarCash
$testPayload = [
    'record_type' => 'transaction',
    'transaction_id' => 'TEST_TXN_' . time(),
    'exchange_reference_number' => 'EXC' . time(),
    'exchange_transaction_id' => 'EXT' . time(),
    'order_number' => 'BOOK-1', // Change this to match an existing booking ID
    'currency' => 'MYR',
    'amount' => '150.00',
    'payer_name' => 'Test User',
    'payer_email' => 'test@example.com',
    'payer_bank_name' => 'Test Bank',
    'status' => 3, // 3 = Success
    'status_description' => 'Success',
    'datetime' => date('Y-m-d H:i:s'),
    'checksum' => 'test_checksum_remove_for_production'
];

// Your webhook URL
$webhookUrl = 'http://gengsewa.test/payment/callback';

echo "╔════════════════════════════════════════════════════════════════╗\n";
echo "║         BayarCash Webhook Test Script                         ║\n";
echo "╚════════════════════════════════════════════════════════════════╝\n\n";

echo "Testing webhook endpoint: {$webhookUrl}\n\n";

echo "Test Payload:\n";
echo json_encode($testPayload, JSON_PRETTY_PRINT) . "\n\n";

echo "Sending POST request...\n\n";

// Initialize cURL
$ch = curl_init($webhookUrl);

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($testPayload),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Accept: application/json'
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false, // For local development only
]);

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

curl_close($ch);

echo "═══════════════════════════════════════════════════════════════\n";
echo "Response:\n";
echo "═══════════════════════════════════════════════════════════════\n";

if ($error) {
    echo "❌ Error: {$error}\n\n";
    exit(1);
}

echo "HTTP Status Code: {$httpCode}\n";
echo "Response Body:\n{$response}\n\n";

if ($httpCode === 200) {
    echo "✅ Webhook test successful!\n\n";
    echo "Check your application logs at: storage/logs/laravel.log\n";
    echo "Look for entries with 'BayarCash Callback' to see the processing details.\n";
} else {
    echo "❌ Webhook test failed!\n\n";
    echo "Troubleshooting:\n";
    echo "1. Ensure the application is running at: {$webhookUrl}\n";
    echo "2. Check that BOOK-1 exists in your bookings table\n";
    echo "3. Review application logs: storage/logs/laravel.log\n";
    echo "4. Verify CSRF protection is disabled for this route\n";
}

echo "\n";
