<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Payment.php');

// Check if user is logged in
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}
$userId = $_SESSION['user_id'];

$db = Database::getInstance();
$payment = new Payment();

$orderId = $_GET['order_id'] ?? null;

if (!$orderId) {
    die('Invalid order ID');
}

$order = $db->fetch(
    'SELECT * FROM payment_orders WHERE order_id = ? AND user_id = ?',
    [$orderId, $userId]
);

if (!$order) {
    die('Order not found');
}

$user = $db->fetch('SELECT * FROM users WHERE id = ?', [$userId]);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Gateway - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .payment-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 500px;
            width: 100%;
            padding: 40px;
        }

        .payment-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .payment-header h2 {
            font-weight: 700;
            color: #333;
            margin-bottom: 10px;
        }

        .order-summary {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            border-left: 4px solid #667eea;
        }

        .order-summary h5 {
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            color: #666;
        }

        .summary-row.total {
            border-top: 2px solid #ddd;
            padding-top: 15px;
            margin-top: 15px;
            font-weight: 700;
            color: #333;
            font-size: 18px;
        }

        .payment-methods {
            margin-bottom: 25px;
        }

        .payment-methods h5 {
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
        }

        .method-option {
            display: flex;
            align-items: center;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .method-option:hover {
            border-color: #667eea;
            background: #f8f9ff;
        }

        .method-option.active {
            border-color: #667eea;
            background: #f8f9ff;
        }

        .method-option input[type="radio"] {
            margin-right: 15px;
            cursor: pointer;
        }

        .method-option label {
            margin: 0;
            cursor: pointer;
            flex: 1;
            font-weight: 500;
        }

        .btn-pay {
            width: 100%;
            padding: 12px;
            font-size: 16px;
            font-weight: 600;
            border: none;
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transition: all 0.3s ease;
        }

        .btn-pay:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-pay:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .security-badge {
            text-align: center;
            margin-top: 20px;
            color: #666;
            font-size: 14px;
        }

        .security-badge i {
            color: #10b981;
        }

        /* MOBILE RESPONSIVE */
        @media (max-width: 576px) {
            .payment-container {
                padding: 25px 20px;
                max-width: 100%;
                border-radius: 12px;
            }

            .payment-header h2 {
                font-size: 1.5rem;
            }

            .order-summary {
                padding: 15px;
                margin-bottom: 20px;
            }

            .summary-row {
                font-size: 14px;
                padding: 6px 0;
            }

            .method-option {
                padding: 12px;
                font-size: 14px;
                margin-bottom: 8px;
            }

            .method-option input[type="radio"] {
                margin-right: 10px;
            }

            .btn-pay {
                padding: 14px;
                font-size: 15px;
                margin-top: 10px;
            }

            .security-badge {
                font-size: 12px;
                margin-top: 15px;
            }
        }

        @media (max-width: 768px) {
            .payment-container {
                max-width: 95%;
            }
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <div class="payment-header">
            <h2><i class="fas fa-lock"></i> Secure Payment</h2>
            <p class="text-muted">Complete your payment to add credits</p>
        </div>

        <div class="order-summary">
            <h5>Order Summary</h5>
            <div class="summary-row">
                <span>Order ID:</span>
                <span><code><?php echo htmlspecialchars($order['order_id']); ?></code></span>
            </div>
            <div class="summary-row">
                <span>Package:</span>
                <span><?php echo htmlspecialchars($order['package_name']); ?></span>
            </div>
            <div class="summary-row">
                <span>Amount:</span>
                <span>₹<?php echo number_format($order['amount'], 2); ?></span>
            </div>
            <div class="summary-row total">
                <span>Total Payable:</span>
                <span>₹<?php echo number_format($order['amount'], 2); ?></span>
            </div>
        </div>

        <div class="payment-methods">
            <h5>Select Payment Method</h5>
            
            <div class="method-option active">
                <input type="radio" id="razorpay" name="payment_method" value="razorpay" checked>
                <label for="razorpay">
                    <i class="fas fa-wallet"></i> Razorpay (Credit/Debit Card, UPI, Wallet)
                </label>
            </div>

            <div class="method-option">
                <input type="radio" id="manual-upi" name="payment_method" value="manual_upi">
                <label for="manual-upi">
                    <i class="fas fa-mobile-alt"></i> Manual UPI Payment
                </label>
            </div>
        </div>

        <button class="btn-pay" id="payButton">
            <i class="fas fa-arrow-right"></i> Proceed to Payment
        </button>

        <div class="security-badge">
            <i class="fas fa-shield-alt"></i> Your payment is 100% secure and encrypted
        </div>
    </div>

    <script>
        const orderId = '<?php echo addslashes($order['order_id']); ?>';
        const amount = <?php echo $order['amount']; ?>;
        const userEmail = '<?php echo htmlspecialchars($user['email']); ?>';
        const userName = '<?php echo htmlspecialchars($user['name']); ?>';

        document.getElementById('payButton').addEventListener('click', function() {
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;

            if (paymentMethod === 'razorpay') {
                initiateRazorpayPayment();
            } else {
                window.location.href = 'manual_upi_payment.php?order_id=' + orderId;
            }
        });

        function initiateRazorpayPayment() {
            const options = {
                "key": "YOUR_RAZORPAY_KEY_ID", // Replace with your Razorpay key
                "amount": amount * 100, // Amount in paise
                "currency": "INR",
                "name": "<?php echo APP_NAME; ?>",
                "description": "Add Credits to Your Account",
                "order_id": orderId,
                "prefill": {
                    "name": userName,
                    "email": userEmail
                },
                "theme": {
                    "color": "#667eea"
                },
                "handler": function(response) {
                    verifyPayment(response.razorpay_payment_id, response.razorpay_order_id);
                },
                "modal": {
                    "ondismiss": function() {
                        console.log('Payment window closed.');
                    }
                }
            };

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

        function verifyPayment(paymentId, razorpayOrderId) {
            // Send payment verification to server
            fetch('verify_payment.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    order_id: orderId,
                    payment_id: paymentId,
                    razorpay_order_id: razorpayOrderId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Payment successful! Credits have been added to your account.');
                    window.location.href = 'payments.php';
                } else {
                    alert('Payment verification failed: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while verifying payment.');
            });
        }
    </script>
</body>
</html>
