<?php
/**
 * Hostxolo - Razorpay Checkout Page
 * Secure online payment integration
 */
require_once 'config.php';
require_login();

$user_id = $_SESSION['user_id'];
$subscription_id = intval($_GET['subscription'] ?? 0);
$txn_id = sanitize($_GET['txn'] ?? '');

if (!$subscription_id || empty($txn_id)) {
    redirect(BASE_URL . 'plans.php', 'error', 'Invalid checkout request');
}

// Get subscription and transaction details
$subscription = null;
$transaction = null;
$user = null;

try {
    $stmt = db()->prepare("
        SELECT us.*, sp.name as plan_name, sp.description as plan_description
        FROM user_subscriptions us
        JOIN subscription_plans sp ON us.plan_id = sp.id
        WHERE us.id = ? AND us.user_id = ? AND us.status = 'pending'
    ");
    $stmt->execute([$subscription_id, $user_id]);
    $subscription = $stmt->fetch();
    
    $stmt = db()->prepare("SELECT * FROM transactions WHERE transaction_number = ? AND user_id = ? AND status = 'pending'");
    $stmt->execute([$txn_id, $user_id]);
    $transaction = $stmt->fetch();
    
    $stmt = db()->prepare("SELECT full_name, email, phone FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    error_log("Checkout error: " . $e->getMessage());
}

if (!$subscription || !$transaction) {
    redirect(BASE_URL . 'plans.php', 'error', 'Invalid or expired checkout session');
}

// Razorpay configuration
$razorpay_key = RAZORPAY_KEY_ID;
$amount_paise = intval($subscription['amount'] * 100);

$page_title = 'Secure Checkout';
include 'includes/header.php';
?>

<section class="py-5" style="margin-top: 70px;">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6">
                <div class="card shadow-lg border-0">
                    <div class="card-header bg-primary text-white py-4">
                        <h4 class="mb-0 fw-bold"><i class="bi bi-shield-lock me-2"></i>Secure Checkout</h4>
                    </div>
                    <div class="card-body p-4 p-md-5">
                        <!-- Order Summary -->
                        <div class="card bg-light border-0 mb-4">
                            <div class="card-body">
                                <h5 class="fw-bold mb-3">Order Summary</h5>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Plan:</span>
                                    <span class="fw-bold"><?php echo $subscription['plan_name']; ?></span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Billing:</span>
                                    <span class="fw-bold"><?php echo ucfirst($subscription['subscription_type']); ?>ly</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Transaction ID:</span>
                                    <span class="text-muted"><?php echo $txn_id; ?></span>
                                </div>
                                <hr>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="h5 mb-0">Total:</span>
                                    <span class="h3 mb-0 text-primary"><?php echo format_currency($subscription['amount']); ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Payment Button -->
                        <div class="d-grid gap-2">
                            <button id="pay-btn" class="btn btn-primary btn-lg">
                                <i class="bi bi-credit-card me-2"></i>Pay <?php echo format_currency($subscription['amount']); ?>
                            </button>
                            <a href="<?php echo BASE_URL; ?>plans.php" class="btn btn-outline-secondary">
                                Cancel
                            </a>
                        </div>

                        <!-- Security Badges -->
                        <div class="text-center mt-4">
                            <p class="text-muted small mb-2">
                                <i class="bi bi-shield-check text-success me-1"></i>
                                256-bit SSL Secure Payment
                            </p>
                            <img src="https://razorpay.com/assets/razorpay-logo.svg" alt="Razorpay" height="24" class="opacity-75">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Razorpay Integration -->
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById('pay-btn').addEventListener('click', function(e) {
    e.preventDefault();
    
    var options = {
        key: '<?php echo $razorpay_key; ?>',
        amount: <?php echo $amount_paise; ?>,
        currency: 'INR',
        name: 'Hostxolo',
        description: '<?php echo addslashes($subscription['plan_name']); ?>',
        image: '<?php echo ASSETS_URL; ?>images/logo.png',
        order_id: '', // Will be generated by server
        handler: function(response) {
            // Submit payment response to server
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '<?php echo BASE_URL; ?>payment-verify.php';
            
            var fields = {
                'razorpay_payment_id': response.razorpay_payment_id,
                'razorpay_order_id': response.razorpay_order_id,
                'razorpay_signature': response.razorpay_signature,
                'subscription_id': '<?php echo $subscription_id; ?>',
                'txn_id': '<?php echo $txn_id; ?>',
                'csrf_token': '<?php echo generate_csrf_token(); ?>'
            };
            
            for (var key in fields) {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = fields[key];
                form.appendChild(input);
            }
            
            document.body.appendChild(form);
            form.submit();
        },
        prefill: {
            name: '<?php echo addslashes($user['full_name']); ?>',
            email: '<?php echo addslashes($user['email']); ?>',
            contact: '<?php echo addslashes($user['phone'] ?? ''); ?>'
        },
        theme: {
            color: '#f97316'
        },
        modal: {
            ondismiss: function() {
                // Redirect to payment failed page when payment modal is closed
                window.location.href = '<?php echo BASE_URL; ?>payment-failed.php?txn=<?php echo $txn_id; ?>&reason=cancelled';
            }
        }
    };
    
    var rzp = new Razorpay(options);
    rzp.open();
});
</script>

<?php include 'includes/footer.php'; ?>
