<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Backend Test - PhonePe V2</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #5f259f;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        input, select, textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            box-sizing: border-box;
        }
        input:focus, select:focus, textarea:focus {
            border-color: #5f259f;
            outline: none;
        }
        .btn {
            background: #5f259f;
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
        }
        .btn:hover {
            background: #4a1f7a;
        }
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .status {
            margin-top: 10px;
            font-weight: bold;
        }
        .amount-display {
            font-size: 24px;
            font-weight: bold;
            color: #5f259f;
            text-align: center;
            margin: 10px 0;
        }
        .debug-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
        .debug-section h3 {
            color: #495057;
            margin-top: 0;
        }
        pre {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            font-size: 12px;
        }
        .two-column {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        @media (max-width: 768px) {
            .two-column {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Backend Test - PhonePe V2</h1>
        
        <div class="two-column">
            <div>
                <div class="form-group">
                    <label for="amount">Transaction Amount (₹)</label>
                    <input type="number" id="amount" value="1" min="1" max="10000" step="1">
                    <div class="amount-display" id="amountDisplay">₹ 1</div>
                </div>

                <div class="form-group">
                    <label for="customerName">Customer Name</label>
                    <input type="text" id="customerName" value="Test Customer" placeholder="Enter customer name">
                </div>

                <div class="form-group">
                    <label for="customerMobile">Customer Mobile</label>
                    <input type="tel" id="customerMobile" value="9828479035" placeholder="Enter mobile number">
                </div>

                <div class="form-group">
                    <label for="customerEmail">Customer Email</label>
                    <input type="email" id="customerEmail" value="test@example.com" placeholder="Enter email">
                </div>

                <div class="form-group">
                    <label for="description">Transaction Description</label>
                    <input type="text" id="description" value="Live Transaction Test" placeholder="Enter description">
                </div>

                <div class="form-group">
                    <label for="merchantOrderId">Merchant Order ID (Optional)</label>
                    <input type="text" id="merchantOrderId" value="" placeholder="Leave empty for auto-generated">
                </div>
            </div>

            <div>
                <div class="form-group">
                    <label for="backendUrl">Backend URL</label>
                    <input type="text" id="backendUrl" value="https://astro.siddharthnahar.in/astro_admin/api/phonepe_v2_backend.php" placeholder="Backend URL">
                </div>

                <div class="form-group">
                    <label for="testType">Test Type</label>
                    <select id="testType">
                        <option value="createPayment">Create Payment</option>
                        <option value="status">Check Status</option>
                        <option value="webhook">Test Webhook</option>
                    </select>
                </div>

                <div class="form-group" id="statusOrderIdGroup" style="display: none;">
                    <label for="statusOrderId">Order ID for Status Check</label>
                    <input type="text" id="statusOrderId" placeholder="Enter order ID">
                </div>

                <button class="btn" onclick="runTest()" id="submitBtn">
                    🚀 Run Backend Test
                </button>

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

        <div class="debug-section">
            <h3>🔍 Debug Information</h3>
            <div id="debugInfo">
                <p>Click "Run Backend Test" to see detailed debug information here.</p>
            </div>
        </div>
    </div>

    <script>
        // Update amount display
        document.getElementById('amount').addEventListener('input', function() {
            document.getElementById('amountDisplay').textContent = '₹ ' + this.value;
        });

        // Show/hide status order ID field
        document.getElementById('testType').addEventListener('change', function() {
            const statusGroup = document.getElementById('statusOrderIdGroup');
            if (this.value === 'status') {
                statusGroup.style.display = 'block';
            } else {
                statusGroup.style.display = 'none';
            }
        });

        async function runTest() {
            const submitBtn = document.getElementById('submitBtn');
            const resultDiv = document.getElementById('result');
            const statusDiv = document.getElementById('status');
            const debugDiv = document.getElementById('debugInfo');
            
            // Get form data
            const amount = document.getElementById('amount').value;
            const customerName = document.getElementById('customerName').value;
            const customerMobile = document.getElementById('customerMobile').value;
            const customerEmail = document.getElementById('customerEmail').value;
            const description = document.getElementById('description').value;
            const merchantOrderId = document.getElementById('merchantOrderId').value;
            const backendUrl = document.getElementById('backendUrl').value;
            const testType = document.getElementById('testType').value;
            const statusOrderId = document.getElementById('statusOrderId').value;

            // Validate
            if (!amount || amount < 1) {
                showResult('error', 'Please enter a valid amount (minimum ₹1)');
                return;
            }

            if (!customerName || !customerMobile) {
                showResult('error', 'Please fill customer name and mobile number');
                return;
            }

            if (testType === 'status' && !statusOrderId) {
                showResult('error', 'Please enter Order ID for status check');
                return;
            }

            // Disable button and show loading
            submitBtn.disabled = true;
            submitBtn.textContent = '🔄 Testing Backend...';
            statusDiv.textContent = 'Running backend test...';
            hideResult();

            try {
                let requestData, endpoint, method;

                if (testType === 'createPayment') {
                    endpoint = '/createPayment';
                    method = 'POST';
                    requestData = {
                        amount: parseInt(amount) * 100, // Convert to paise
                        customerName: customerName,
                        customerMobile: customerMobile,
                        customerEmail: customerEmail,
                        description: description,
                        merchantOrderId: merchantOrderId || 'LIVE-' + Date.now() + '-' + Math.floor(Math.random() * 1000),
                        webhookUrl: 'https://astro.siddharthnahar.in/astro_admin/api/phonepe_v2_backend.php/webhook'
                    };
                } else if (testType === 'status') {
                    endpoint = '/status';
                    method = 'POST';
                    requestData = {
                        merchantOrderId: statusOrderId
                    };
                } else if (testType === 'webhook') {
                    endpoint = '/webhook';
                    method = 'POST';
                    requestData = {
                        orderId: statusOrderId || 'TEST123',
                        state: 'PAID'
                    };
                }

                const fullUrl = backendUrl + endpoint;
                
                console.log('Backend Test Request:', {
                    url: fullUrl,
                    method: method,
                    data: requestData
                });

                // Show debug info
                debugDiv.innerHTML = `<h4>Request Details:</h4><pre>URL: ${fullUrl}\nMethod: ${method}\nHeaders: {\n  "Content-Type": "application/json"\n}\nBody: ${JSON.stringify(requestData, null, 2)}</pre>`;

                // Make request
                const response = await fetch(fullUrl, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const responseText = await response.text();
                let responseData;
                
                try {
                    responseData = JSON.parse(responseText);
                } catch (e) {
                    responseData = { raw: responseText };
                }

                console.log('Backend Test Response:', {
                    status: response.status,
                    statusText: response.statusText,
                    data: responseData
                });

                // Update debug info
                debugDiv.innerHTML += `<h4>Response Details:</h4><pre>Status: ${response.status} ${response.statusText}\nHeaders: ${JSON.stringify(Object.fromEntries(response.headers.entries()), null, 2)}\nBody: ${JSON.stringify(responseData, null, 2)}</pre>`;

                if (response.ok) {
                    if (testType === 'createPayment' && responseData.redirectUrl) {
                        showResult('success', `✅ Payment Created Successfully!<br><br><strong>Order ID:</strong> ${responseData.orderId || 'N/A'}<br><strong>Amount:</strong> ₹${amount}<br><strong>Status:</strong> ${responseData.state || 'PENDING'}<br><strong>Redirect URL:</strong> <a href="${responseData.redirectUrl}" target="_blank">${responseData.redirectUrl}</a><br><br><strong>Test the URL:</strong> <button onclick="window.open('${responseData.redirectUrl}', '_blank')">Open Payment Gateway</button>`);
                        statusDiv.textContent = 'Payment created successfully!';
                    } else if (testType === 'status') {
                        showResult('info', `📊 Status Check Result:<br><br><strong>Order ID:</strong> ${responseData.orderId || 'N/A'}<br><strong>State:</strong> ${responseData.state || 'N/A'}<br><strong>Amount:</strong> ₹${(responseData.amount || 0) / 100}<br><strong>Expires At:</strong> ${responseData.expireAt ? new Date(responseData.expireAt).toLocaleString() : 'N/A'}`);
                        statusDiv.textContent = 'Status check completed!';
                    } else if (testType === 'webhook') {
                        showResult('info', `🔗 Webhook Test Result:<br><br><strong>Response:</strong> ${JSON.stringify(responseData, null, 2)}`);
                        statusDiv.textContent = 'Webhook test completed!';
                    } else {
                        showResult('info', `📋 Backend Response:<br><br><strong>Response:</strong> ${JSON.stringify(responseData, null, 2)}`);
                        statusDiv.textContent = 'Backend test completed!';
                    }
                } else {
                    showResult('error', `❌ Backend Error<br><br><strong>Status:</strong> ${response.status} ${response.statusText}<br><strong>Response:</strong> ${JSON.stringify(responseData, null, 2)}`);
                    statusDiv.textContent = 'Backend test failed!';
                }

            } catch (error) {
                console.error('Backend Test Error:', error);
                showResult('error', `❌ Network Error<br><br><strong>Error:</strong> ${error.message}<br><strong>Details:</strong> Check console for more information`);
                statusDiv.textContent = 'Network error occurred!';
                
                // Update debug info
                debugDiv.innerHTML += `<h4>Error Details:</h4><pre>Error: ${error.message}\nStack: ${error.stack}</pre>`;
            }

            // Re-enable button
            submitBtn.disabled = false;
            submitBtn.textContent = '🚀 Run Backend Test';
        }

        function showResult(type, message) {
            const resultDiv = document.getElementById('result');
            resultDiv.className = `result ${type}`;
            resultDiv.innerHTML = message;
            resultDiv.style.display = 'block';
        }

        function hideResult() {
            const resultDiv = document.getElementById('result');
            resultDiv.style.display = 'none';
        }

        // Auto-refresh status every 30 seconds
        setInterval(() => {
            const statusDiv = document.getElementById('status');
            if (statusDiv.textContent.includes('completed') || statusDiv.textContent.includes('failed')) {
                statusDiv.textContent = statusDiv.textContent + ' (Last updated: ' + new Date().toLocaleTimeString() + ')';
            }
        }, 30000);
    </script>
</body>
</html>
