<?php
if (session_status() === PHP_SESSION_NONE) session_start();
include 'config/db.php';
include 'config/razorpay.php';

// Must be logged in and have a pending order
if (!isset($_SESSION['user_id'], $_SESSION['pending_order_id'])) {
    header('Location: cart.php');
    exit;
}

$order_id = (int)$_SESSION['pending_order_id'];
$user_id  = (int)$_SESSION['user_id'];

// Fetch order
$order = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT o.*, u.name, u.email, u.phone
     FROM orders o JOIN users u ON o.user_id = u.id
     WHERE o.id = $order_id AND o.user_id = $user_id LIMIT 1"
));
if (!$order) { header('Location: cart.php'); exit; }

$error = $_GET['error'] ?? null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment - ShopNest Rentals</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        .pay-card {
            max-width: 500px; margin: 80px auto 40px;
            background: #fff; border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.10);
            overflow: hidden;
        }
        .pay-header {
            background: linear-gradient(135deg, #2c3e50, #1a252f);
            color: #fff; padding: 30px;
            text-align: center;
        }
        .pay-header .amount {
            font-size: 2.8rem; font-weight: 700; color: #ff6b35;
        }
        .pay-body { padding: 30px; }
        .pay-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f0f0f0; }
        .pay-row:last-child { border-bottom: none; }
        .btn-pay {
            display: block; width: 100%;
            background: linear-gradient(45deg, #ff6b35, #ff8e53);
            border: none; color: #fff;
            padding: 15px; border-radius: 12px;
            font-size: 1.1rem; font-weight: 700;
            cursor: pointer; transition: all 0.3s;
            margin-top: 20px;
        }
        .btn-pay:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(255,107,53,.35); }
        .btn-pay:disabled { opacity: .7; cursor: not-allowed; transform: none; }
        .security-note { font-size: .78rem; color: #888; text-align: center; margin-top: 12px; }
        .rzp-logo { height: 22px; vertical-align: middle; }
        .spinner { display: none; }
        .btn-pay.loading .spinner { display: inline-block; }
        .btn-pay.loading .btn-text { display: none; }
    </style>
</head>
<body>
<?php include 'includes/header.php'; ?>

<div class="pay-card">
    <div class="pay-header">
        <i class="fas fa-shield-alt fa-2x mb-3" style="color:#ff6b35;"></i>
        <h4 class="mb-1">Secure Payment</h4>
        <div class="amount">₹<?php echo number_format($order['total_price'], 2); ?></div>
        <small>Order #<?php echo str_pad($order_id, 6, '0', STR_PAD_LEFT); ?></small>
    </div>

    <div class="pay-body">
        <?php if ($error): ?>
        <div class="alert alert-danger">
            <div class="d-flex align-items-center">
                <i class="fas fa-exclamation-circle me-3 fa-2x"></i>
                <div>
                    <h6 class="mb-1">Payment Issue</h6>
                    <p class="mb-0 small">
                        <?php
                            $msgs = [
                                'signature_mismatch' => 'Payment verification failed. Please try again.',
                                'cancelled'          => 'Payment was cancelled or the window was closed.',
                                'failed'             => 'Payment failed: ' . htmlspecialchars($_GET['detail'] ?? 'Unknown error'),
                                'api_error'          => 'Could not connect to payment gateway.',
                            ];
                            echo $msgs[$error] ?? 'Something went wrong. Please try again.';
                        ?>
                    </p>
                </div>
            </div>
        </div>
        <div class="alert alert-info py-2 small">
            <i class="fas fa-info-circle me-1"></i> <strong>Test Mode Tip:</strong> After entering card details, make sure to click <strong>"Success"</strong> on the Razorpay test screen to complete the order.
        </div>
        <?php endif; ?>

        <!-- Order summary -->
        <div class="mb-3">
            <div class="pay-row"><span class="text-muted">Name</span><strong><?php echo htmlspecialchars($order['name']); ?></strong></div>
            <div class="pay-row"><span class="text-muted">Email</span><strong><?php echo htmlspecialchars($order['email']); ?></strong></div>
            <div class="pay-row"><span class="text-muted">Order</span><strong>#<?php echo str_pad($order_id, 6, '0', STR_PAD_LEFT); ?></strong></div>
            <div class="pay-row"><span class="text-muted">Amount</span><strong class="text-success">₹<?php echo number_format($order['total_price'], 2); ?></strong></div>
        </div>

        <button id="payBtn" class="btn-pay">
            <span class="btn-text"><i class="fas fa-lock me-2"></i>Pay ₹<?php echo number_format($order['total_price'], 2); ?> Now</span>
            <span class="spinner"><span class="spinner-border spinner-border-sm me-2"></span>Processing…</span>
        </button>

        <p class="security-note">
            <i class="fas fa-lock me-1"></i> Secured by
            <img src="https://razorpay.com/assets/razorpay-logo.svg" alt="Razorpay" class="rzp-logo">
            · 256-bit SSL
        </p>

        <div class="text-center mt-3">
            <a href="cart.php" class="text-muted small"><i class="fas fa-arrow-left me-1"></i>Back to Cart</a>
        </div>
    </div>
</div>

<!-- Hidden form to POST back to verify-payment.php -->
<form id="rzpForm" method="POST" action="verify-payment.php">
    <input type="hidden" name="razorpay_payment_id" id="rzp_payment_id">
    <input type="hidden" name="razorpay_order_id"   id="rzp_order_id">
    <input type="hidden" name="razorpay_signature"   id="rzp_signature">
</form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById('payBtn').addEventListener('click', async function () {
    const btn = this;
    btn.disabled = true;
    btn.classList.add('loading');

    // 1. Create Razorpay order server-side
    let rzpOrder;
    try {
        const res = await fetch('create-razorpay-order.php');
        rzpOrder = await res.json();
        if (rzpOrder.error) throw new Error(rzpOrder.error);
    } catch (err) {
        alert('Could not initiate payment: ' + err.message);
        btn.disabled = false;
        btn.classList.remove('loading');
        return;
    }

    // 2. Open Razorpay checkout popup
    const options = {
        key:         '<?php echo RAZORPAY_KEY_ID; ?>',
        amount:      rzpOrder.amount,
        currency:    'INR',
        name:        'ShopNest Rentals',
        description: 'Rental Order #<?php echo str_pad($order_id, 6, "0", STR_PAD_LEFT); ?>',
        order_id:    rzpOrder.id,
        prefill: {
            name:    '<?php echo addslashes(htmlspecialchars($order['name'])); ?>',
            email:   '<?php echo addslashes(htmlspecialchars($order['email'])); ?>',
            contact: '<?php echo addslashes(htmlspecialchars($order['phone'] ?? '')); ?>',
        },
        theme: { color: '#ff6b35' },
        handler: function (response) {
            // Payment successful — submit hidden form
            document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
            document.getElementById('rzp_order_id').value   = response.razorpay_order_id;
            document.getElementById('rzp_signature').value  = response.razorpay_signature;
            document.getElementById('rzpForm').submit();
        },
        modal: {
            ondismiss: function () {
                btn.disabled = false;
                btn.classList.remove('loading');
                window.location.href = 'payment.php?error=cancelled';
            }
        }
    };

    const rzp = new Razorpay(options);
    rzp.on('payment.failed', function (response) {
        let errorCode = response.error.code;
        let errorDesc = encodeURIComponent(response.error.description);
        window.location.href = `payment.php?error=failed&detail=${errorDesc}`;
    });
    rzp.open();
});
</script>
</body>
</html>
