<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

// ============================================================================
// FLUTTERWAVE WEBHOOK TEST SCRIPT
// ============================================================================
// This script helps you test the webhook handler locally
// DELETE THIS FILE AFTER TESTING - DO NOT LEAVE IN PRODUCTION
// ============================================================================

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../include/config.php';

// Check if user is admin
if (!isset($_SESSION['logged_in']) || !isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    die('Access denied. Admin only.');
}

$flutterwave_webhook_secret = $site_data['flutterwave_webhook_secret'] ?? '';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flutterwave Webhook Tester</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 20px; background: #f5f5f5; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #4D148C; margin-bottom: 10px; }
        .warning { background: #fff3cd; border: 1px solid #ffc107; padding: 15px; border-radius: 5px; margin: 20px 0; color: #856404; }
        .info { background: #d1ecf1; border: 1px solid #0dcaf0; padding: 15px; border-radius: 5px; margin: 20px 0; color: #055160; }
        .form-group { margin-bottom: 20px; }
        label { display: block; font-weight: 600; margin-bottom: 5px; color: #333; }
        input, textarea, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; }
        textarea { min-height: 200px; font-family: 'Courier New', monospace; }
        button { background: #4D148C; color: white; padding: 12px 24px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; font-weight: 600; }
        button:hover { background: #6b23c2; }
        .result { margin-top: 20px; padding: 20px; border-radius: 5px; }
        .success { background: #d4edda; border: 1px solid #28a745; color: #155724; }
        .error { background: #f8d7da; border: 1px solid #dc3545; color: #721c24; }
        .code { background: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; border-radius: 5px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 12px; margin-top: 10px; }
        .config { background: #fff3cd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .config strong { color: #856404; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 Flutterwave Webhook Tester</h1>
        <p style="color: #666; margin-bottom: 20px;">Test your webhook handler before going live</p>

        <div class="warning">
            <strong>⚠️ Security Warning:</strong> This test script is for development only. 
            Delete this file (<code>test-flutterwave-webhook.php</code>) before deploying to production!
        </div>

        <div class="config">
            <strong>Current Configuration:</strong><br>
            Webhook Secret: <?php echo !empty($flutterwave_webhook_secret) ? '✅ Configured' : '❌ Not set'; ?><br>
            Webhook URL: <code><?php echo $site_data['web_url']; ?>/user/flutterwave-webhook.php</code>
        </div>

        <?php if (empty($flutterwave_webhook_secret)): ?>
        <div class="info">
            <strong>ℹ️ Setup Required:</strong> You need to set your webhook secret in the database first:
            <div class="code">UPDATE settings SET flutterwave_webhook_secret = 'YOUR_SECRET_HASH' WHERE id = 1;</div>
        </div>
        <?php endif; ?>

        <form id="webhookTestForm">
            <div class="form-group">
                <label>Event Type</label>
                <select name="event_type" id="event_type">
                    <option value="charge.completed">charge.completed (Payment Success)</option>
                    <option value="transfer.completed">transfer.completed (Transfer)</option>
                </select>
            </div>

            <div class="form-group">
                <label>Transaction Reference (must exist in your database)</label>
                <input type="text" name="tx_ref" value="TXN_" placeholder="e.g., TXN_ABC123_1234567890" required>
            </div>

            <div class="form-group">
                <label>Amount (NGN)</label>
                <input type="number" name="amount" value="1000" step="0.01" required>
            </div>

            <div class="form-group">
                <label>Currency</label>
                <select name="currency">
                    <option value="NGN">NGN</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option>
                    <option value="GBP">GBP</option>
                </select>
            </div>

            <div class="form-group">
                <label>Status</label>
                <select name="status">
                    <option value="successful">successful</option>
                    <option value="failed">failed</option>
                    <option value="pending">pending</option>
                </select>
            </div>

            <div class="form-group">
                <label>Custom Webhook Payload (JSON) - Optional</label>
                <textarea name="custom_payload" id="custom_payload" placeholder="Leave empty to use auto-generated payload"></textarea>
            </div>

            <button type="submit">🚀 Send Test Webhook</button>
        </form>

        <div id="result"></div>
    </div>

    <script>
        document.getElementById('webhookTestForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = '<div class="info">⏳ Sending webhook...</div>';
            
            const formData = new FormData(e.target);
            
            let payload;
            const customPayload = formData.get('custom_payload').trim();
            
            if (customPayload) {
                try {
                    payload = JSON.parse(customPayload);
                } catch (err) {
                    resultDiv.innerHTML = '<div class="error">❌ Invalid JSON in custom payload</div>';
                    return;
                }
            } else {
                // Auto-generate payload
                payload = {
                    event: formData.get('event_type'),
                    data: {
                        id: Math.floor(Math.random() * 1000000),
                        tx_ref: formData.get('tx_ref'),
                        flw_ref: 'FLW-TEST-' + Date.now(),
                        status: formData.get('status'),
                        currency: formData.get('currency'),
                        charged_amount: parseFloat(formData.get('amount')),
                        amount: parseFloat(formData.get('amount')),
                        payment_type: 'card',
                        created_at: new Date().toISOString(),
                        customer: {
                            email: 'test@example.com',
                            name: 'Test User',
                            phone_number: '+2348012345678'
                        }
                    }
                };
            }
            
            try {
                const response = await fetch('<?php echo $site_data['web_url']; ?>/user/flutterwave-webhook.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'verif-hash': '<?php echo $flutterwave_webhook_secret; ?>'
                    },
                    body: JSON.stringify(payload)
                });
                
                const responseText = await response.text();
                let responseData;
                
                try {
                    responseData = JSON.parse(responseText);
                } catch (err) {
                    responseData = { raw: responseText };
                }
                
                if (response.ok) {
                    resultDiv.innerHTML = `
                        <div class="result success">
                            <strong>✅ Webhook sent successfully!</strong>
                            <p>Status: ${response.status} ${response.statusText}</p>
                            <div class="code">${JSON.stringify(responseData, null, 2)}</div>
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = `
                        <div class="result error">
                            <strong>❌ Webhook failed</strong>
                            <p>Status: ${response.status} ${response.statusText}</p>
                            <div class="code">${JSON.stringify(responseData, null, 2)}</div>
                        </div>
                    `;
                }
                
                // Show the payload that was sent
                resultDiv.innerHTML += `
                    <div style="margin-top: 20px;">
                        <strong>Payload Sent:</strong>
                        <div class="code">${JSON.stringify(payload, null, 2)}</div>
                    </div>
                `;
                
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="result error">
                        <strong>❌ Network Error</strong>
                        <p>${error.message}</p>
                    </div>
                `;
            }
        });
        
        // Auto-fill with example payload on load
        const examplePayload = {
            "event": "charge.completed",
            "data": {
                "id": 285959875,
                "tx_ref": "TXN_ABC123_1234567890",
                "flw_ref": "FLW-MOCK-d80f07c58e62a4dccf69a6dc5d57e4f8",
                "status": "successful",
                "currency": "NGN",
                "charged_amount": 1000,
                "amount": 1000,
                "payment_type": "card",
                "customer": {
                    "email": "test@example.com",
                    "name": "Test User"
                }
            }
        };
    </script>
</body>
</html>
