<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Verification Dashboard - User 45</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        header {
            background: linear-gradient(135deg, #2575fc 0%, #6a11cb 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        header h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 600;
        }
        .user-info {
            margin-top: 10px;
            font-size: 1.1rem;
            opacity: 0.9;
        }
        .payment {
            background: white;
            border: 1px solid #e1e5e9;
            padding: 20px;
            margin: 15px 0;
            border-radius: 10px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .payment:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        }
        .pending {
            border-left: 6px solid #ff9500;
            background: linear-gradient(135deg, #fff9f0 0%, #fff 100%);
        }
        .completed {
            border-left: 6px solid #34c759;
            background: linear-gradient(135deg, #f0fff4 0%, #fff 100%);
        }
        .failed {
            border-left: 6px solid #ff3b30;
            background: linear-gradient(135deg, #fff0f0 0%, #fff 100%);
        }
        button {
            padding: 12px 20px;
            margin: 5px;
            cursor: pointer;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }
        .btn-pay {
            background: linear-gradient(135deg, #34c759 0%, #2ecc71 100%);
            color: white;
        }
        .btn-pay:hover {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(52, 199, 89, 0.4);
        }
        .btn-view {
            background: linear-gradient(135deg, #2575fc 0%, #6a11cb 100%);
            color: white;
        }
        .btn-view:hover {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(37, 117, 252, 0.4);
        }
        .btn-refresh {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
            color: white;
            padding: 12px 25px;
            font-size: 1rem;
        }
        .btn-refresh:hover {
            background: linear-gradient(135deg, #495057 0%, #343a40 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4);
        }
        .stats {
            display: flex;
            gap: 20px;
            margin: 30px;
            flex-wrap: wrap;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            flex: 1;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            min-width: 200px;
            transition: transform 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-3px);
        }
        .stat-value {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .alert {
            padding: 15px 20px;
            margin: 20px;
            border-radius: 8px;
            font-weight: 500;
            border-left: 4px solid transparent;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left-color: #34c759;
        }
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left-color: #ff3b30;
        }
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-left-color: #2575fc;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
            font-size: 1.1rem;
        }
        .payment-details {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
            border-left: 4px solid #2575fc;
        }
        .payment-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 15px 0;
        }
        .info-item {
            display: flex;
            justify-content: between;
        }
        .info-label {
            font-weight: 600;
            color: #495057;
            min-width: 120px;
        }
        .info-value {
            color: #212529;
        }
        .actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        .main-content {
            padding: 0 30px 30px 30px;
        }
        .filters {
            display: flex;
            gap: 15px;
            margin: 20px 0;
            flex-wrap: wrap;
            align-items: center;
        }
        .filter-select {
            padding: 10px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            background: white;
            font-size: 0.9rem;
            min-width: 150px;
        }
        .no-payments {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        .no-payments i {
            font-size: 3rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        .payment-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .payment-id {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2575fc;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-completed {
            background: #d1edf1;
            color: #0c5460;
        }
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>Payment Verification Dashboard</h1>
            <div class="user-info">User ID: 45 | Parent Account | Test Mode (No Authentication Required)</div>
        </header>

        <!-- CSRF Token Meta Tag -->
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <div id="alert-container"></div>

        <div class="stats">
            <div class="stat-card">
                <div class="stat-value" id="total-payments">0</div>
                <div>Total Payments</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="pending-payments">0</div>
                <div>Pending</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="completed-payments">0</div>
                <div>Completed</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="failed-payments">0</div>
                <div>Failed</div>
            </div>
        </div>

        <div class="main-content">
            <div class="filters">
                <button class="btn-refresh" onclick="loadPayments()">
                    🔄 Refresh Payments
                </button>
                <select class="filter-select" id="status-filter" onchange="filterPayments()">
                    <option value="">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="completed">Completed</option>
                    <option value="failed">Failed</option>
                </select>
                <select class="filter-select" id="sort-filter" onchange="sortPayments()">
                    <option value="newest">Newest First</option>
                    <option value="oldest">Oldest First</option>
                    <option value="amount_high">Amount: High to Low</option>
                    <option value="amount_low">Amount: Low to High</option>
                </select>
            </div>

            <div id="payments-container">
                <div class="loading">
                    <div>🔄 Loading payments for User ID 45...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPaymentId = null;
        let allPayments = [];

        // CSRF Token setup for AJAX requests
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // Load payments on page load
        $(document).ready(function() {
            loadPayments();
        });

        function loadPayments() {
            showAlert('Loading payments for User ID 45...', 'info');
            $('#payments-container').html('<div class="loading">🔄 Loading payments...</div>');

            // Use our test route that doesn't require authentication
            $.ajax({
                url: '/test/payments/user/45',
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        allPayments = response.data;
                        displayPayments(allPayments);
                        updateStats(allPayments);
                        showAlert('Payments loaded successfully! Found ' + response.data.length + ' payments.', 'success');
                    } else {
                        showAlert('Failed to load payments: ' + response.message, 'error');
                        $('#payments-container').html('<div class="loading">❌ Error loading payments</div>');
                    }
                },
                error: function(xhr, status, error) {
                    showAlert('Error loading payments: ' + error, 'error');
                    $('#payments-container').html('<div class="loading">❌ Error: ' + error + '</div>');
                    console.error('API Error:', error);
                }
            });
        }

        function displayPayments(payments) {
            if (payments.length === 0) {
                $('#payments-container').html(`
                    <div class="no-payments">
                        <div>📭</div>
                        <h3>No payments found for User ID 45</h3>
                        <p>There are no payment records for this user.</p>
                    </div>
                `);
                return;
            }

            let html = '<h2>Payments Found: ' + payments.length + '</h2>';

            payments.forEach(payment => {
                const statusClass = payment.payment_status;
                const amount = parseFloat(payment.amount).toFixed(2);
                const date = new Date(payment.created_at).toLocaleString();
                const booking = payment.booking || {};
                const babysitter = payment.babysitter || {};

                html += `
                    <div class="payment ${statusClass}">
                        <div class="payment-header">
                            <div class="payment-id">Payment #${payment.payment_id}</div>
                            <div class="status-badge status-${statusClass}">
                                ${statusClass.toUpperCase()}
                            </div>
                        </div>

                        <div class="payment-info-grid">
                            <div class="info-item">
                                <span class="info-label">Booking ID:</span>
                                <span class="info-value">${payment.booking_id}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Amount:</span>
                                <span class="info-value">$${amount} ${payment.currency}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Created:</span>
                                <span class="info-value">${date}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Babysitter:</span>
                                <span class="info-value">${babysitter.first_name ? babysitter.first_name + ' ' + babysitter.last_name : 'N/A'}</span>
                            </div>
                        </div>

                        ${payment.razorpay_order_id ? `
                        <div class="payment-details">
                            <strong>Razorpay Order:</strong> ${payment.razorpay_order_id}<br>
                            ${payment.razorpay_payment_id ? `<strong>Payment ID:</strong> ${payment.razorpay_payment_id}` : ''}
                        </div>
                        ` : ''}

                        <div class="actions">
                            ${(payment.payment_status === 'pending' || payment.payment_status === 'failed') ?
                                `<button class="btn-pay" onclick="startPayment(${payment.payment_id}, ${payment.booking_id})">
                                    💳 Pay Now
                                </button>` :
                                ''
                            }
                            <button class="btn-view" onclick="viewDetails(${payment.payment_id})">
                                👁️ View Details
                            </button>
                        </div>
                    </div>
                `;
            });

            $('#payments-container').html(html);
        }

        function updateStats(payments) {
            const total = payments.length;
            const pending = payments.filter(p => p.payment_status === 'pending').length;
            const completed = payments.filter(p => p.payment_status === 'completed').length;
            const failed = payments.filter(p => p.payment_status === 'failed').length;

            $('#total-payments').text(total);
            $('#pending-payments').text(pending);
            $('#completed-payments').text(completed);
            $('#failed-payments').text(failed);
        }

        function filterPayments() {
            const statusFilter = $('#status-filter').val();
            let filteredPayments = allPayments;

            if (statusFilter) {
                filteredPayments = allPayments.filter(payment =>
                    payment.payment_status === statusFilter
                );
            }

            displayPayments(filteredPayments);
            updateStats(filteredPayments);
        }

        function sortPayments() {
            const sortBy = $('#sort-filter').val();
            let sortedPayments = [...allPayments];

            switch (sortBy) {
                case 'newest':
                    sortedPayments.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
                    break;
                case 'oldest':
                    sortedPayments.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
                    break;
                case 'amount_high':
                    sortedPayments.sort((a, b) => parseFloat(b.amount) - parseFloat(a.amount));
                    break;
                case 'amount_low':
                    sortedPayments.sort((a, b) => parseFloat(a.amount) - parseFloat(b.amount));
                    break;
            }

            displayPayments(sortedPayments);
        }

        function startPayment(paymentId, bookingId) {
            showAlert('Creating payment order for booking ' + bookingId + '...', 'info');

            // Use our test route that doesn't require authentication
            $.ajax({
                url: '/test/payments/create-order',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    booking_id: bookingId,
                    payment_method: 'razorpay'
                }),
                success: function(response) {
                    if (response.success) {
                        currentPaymentId = response.data.payment_id;
                        showAlert('Payment order created! Opening Razorpay...', 'success');
                        openRazorpay(response.data);
                    } else {
                        showAlert('Failed to create payment order: ' + response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    showAlert('Error creating payment order: ' + error, 'error');
                    console.error('Create Order Error:', error);
                }
            });
        }

        function openRazorpay(paymentData) {
            const options = {
                key: paymentData.razorpay_order.key,
                amount: paymentData.razorpay_order.amount,
                currency: paymentData.razorpay_order.currency,
                name: 'Babysitter Booking',
                description: 'Payment for Booking #' + paymentData.booking_details.booking_id,
                order_id: paymentData.razorpay_order.id,
                handler: function(response) {
                    showAlert('Payment completed! Verifying...', 'info');
                    verifyPayment(response);
                },
                prefill: {
                    name: 'Test User 45',
                    email: 'test45@example.com',
                    contact: '9999999999'
                },
                theme: {
                    color: '#3399cc'
                },
                modal: {
                    ondismiss: function() {
                        showAlert('Payment cancelled by user', 'info');
                    }
                }
            };

            const rzp = new Razorpay(options);
            rzp.open();
        }

        function verifyPayment(razorpayResponse) {
            showAlert('Verifying payment...', 'info');

            $.ajax({
                url: '/test/payments/verify',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    razorpay_order_id: razorpayResponse.razorpay_order_id,
                    razorpay_payment_id: razorpayResponse.razorpay_payment_id,
                    razorpay_signature: razorpayResponse.razorpay_signature
                }),
                success: function(response) {
                    if (response.success) {
                        showAlert('🎉 Payment successful! Booking confirmed.', 'success');
                        // Reload payments after 2 seconds
                        setTimeout(() => {
                            loadPayments();
                        }, 2000);
                    } else {
                        showAlert('❌ Payment verification failed: ' + response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    showAlert('❌ Verification error: ' + error, 'error');
                }
            });
        }

        function viewDetails(paymentId) {
            // Use our test route to get payment details
            $.ajax({
                url: '/test/payments/' + paymentId,
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        const payment = response.data;
                        const booking = payment.booking || {};
                        const babysitter = payment.babysitter || {};

                        const details = `
Payment Details:

🆔 Payment ID: ${payment.payment_id}
📋 Booking ID: ${payment.booking_id}
💰 Amount: $${payment.amount} ${payment.currency}
📊 Status: ${payment.payment_status}
🏦 Commission: ${payment.commission_rate}% ($${payment.commission_amount})
👶 Babysitter Payout: $${payment.babysitter_payout_amount}
💳 Payment Method: ${payment.payment_method}
🌐 Gateway: ${payment.payment_gateway}
📝 Razorpay Order: ${payment.razorpay_order_id || 'N/A'}
✅ Razorpay Payment: ${payment.razorpay_payment_id || 'N/A'}
📅 Created: ${new Date(payment.created_at).toLocaleString()}
🕒 Paid At: ${payment.paid_at ? new Date(payment.paid_at).toLocaleString() : 'N/A'}

Booking Info:
👤 Babysitter: ${babysitter.first_name ? babysitter.first_name + ' ' + babysitter.last_name : 'N/A'}
📧 Email: ${babysitter.email || 'N/A'}
📞 Phone: ${babysitter.phone_number || 'N/A'}
                        `;
                        alert('Payment Details:\n\n' + details);
                    } else {
                        showAlert('Failed to load payment details: ' + response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    showAlert('Error loading payment details: ' + error, 'error');
                }
            });
        }

        function showAlert(message, type) {
            const alertClass = 'alert-' + (type === 'success' ? 'success' : type === 'error' ? 'error' : 'info');
            const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️';
            $('#alert-container').html('<div class="alert ' + alertClass + '">' + icon + ' ' + message + '</div>');

            // Auto-hide success/info alerts after 5 seconds
            if (type !== 'error') {
                setTimeout(() => {
                    $('#alert-container').empty();
                }, 5000);
            }
        }
    </script>
</body>
</html>
