<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PhonePe Live Transaction Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            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 {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            box-sizing: border-box;
        }
        input:focus, select: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;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 PhonePe Live Transaction Test</h1>
        
        <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>

        <button class="btn" onclick="createLiveTransaction()" id="submitBtn">
            💳 Create Live Transaction
        </button>

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

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

        async function createLiveTransaction() {
            const submitBtn = document.getElementById('submitBtn');
            const resultDiv = document.getElementById('result');
            const statusDiv = document.getElementById('status');
            
            // 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;

            // 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;
            }

            // Disable button and show loading
            submitBtn.disabled = true;
            submitBtn.textContent = '🔄 Creating Transaction...';
            statusDiv.textContent = 'Creating live transaction...';
            hideResult();

            try {
                // Create transaction data
                const transactionData = {
                    amount: parseInt(amount) * 100, // Convert to paise
                    customerName: customerName,
                    customerMobile: customerMobile,
                    customerEmail: customerEmail,
                    description: description,
                    merchantOrderId: 'LIVE-' + Date.now() + '-' + Math.floor(Math.random() * 1000)
                };

                console.log('Creating live transaction:', transactionData);

                // Call backend to create payment
                const response = await fetch('https://astro.siddharthnahar.in/astro_admin/api/phonepe_v2_backend.php/createPayment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(transactionData)
                });

                const data = await response.json();
                console.log('Backend response:', data);

                if (data.redirectUrl) {
                    showResult('success', `✅ Live Transaction Created Successfully!<br><br>
                        <strong>Transaction ID:</strong> ${data.orderId || 'N/A'}<br>
                        <strong>Amount:</strong> ₹${amount}<br>
                        <strong>Status:</strong> ${data.state || 'PENDING'}<br><br>
                        <strong>Redirecting to PhonePe...</strong>`);
                    
                    statusDiv.textContent = 'Redirecting to PhonePe payment gateway...';
                    
                    // Open PhonePe payment gateway
                    setTimeout(() => {
                        window.open(data.redirectUrl, '_blank');
                        statusDiv.textContent = 'Payment gateway opened in new tab. Complete the payment to see live transaction in PhonePe dashboard.';
                    }, 2000);

                } else {
                    showResult('error', `❌ Transaction Creation Failed<br><br>
                        <strong>Error:</strong> ${data.message || 'Unknown error'}<br>
                        <strong>Response:</strong> ${JSON.stringify(data, null, 2)}`);
                    statusDiv.textContent = 'Transaction creation failed.';
                }

            } catch (error) {
                console.error('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.';
            }

            // Re-enable button
            submitBtn.disabled = false;
            submitBtn.textContent = '💳 Create Live Transaction';
        }

        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('Payment gateway opened')) {
                statusDiv.textContent = 'Payment gateway opened in new tab. Complete the payment to see live transaction in PhonePe dashboard. (Auto-refresh: ' + new Date().toLocaleTimeString() + ')';
            }
        }, 30000);
    </script>
</body>
</html>
