<?php
/**
 * Stripe Payment Integration
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

$order_id = (int)($_GET['order_id'] ?? 0);

if (!$order_id) {
    set_flash_message('Invalid order.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get order
$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    set_flash_message('Order not found.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

if ($order['payment_status'] === 'paid') {
    set_flash_message('This order has already been paid.', 'info');
    header('Location: ' . BASE_URL . '/account/order-view.php?id=' . $order_id);
    exit;
}

// Get Stripe settings
$stripe = get_payment_gateway('stripe');
if (!$stripe || !$stripe['is_active']) {
    set_flash_message('Stripe payment is currently unavailable.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

$config = $stripe['config'];
$publishable_key = $config['publishable_key'] ?? '';
$secret_key = $config['secret_key'] ?? '';

$page_title = 'Pay with Stripe';

include __DIR__ . '/../includes/header.php';
?>

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card payment-card" data-aos="fade-up">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <div class="payment-icon stripe mb-4">
                                <i class="fab fa-stripe"></i>
                            </div>
                            
                            <h2 class="mb-2">Complete Your Payment</h2>
                            <p class="text-muted">Order #<?php echo $order['order_number']; ?></p>
                        </div>
                        
                        <div class="order-summary-box mb-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-muted">Amount to Pay:</span>
                                <span class="h3 mb-0 text-primary"><?php echo format_price($order['total']); ?></span>
                            </div>
                        </div>
                        
                        <!-- Stripe Payment Form -->
                        <form id="payment-form">
                            <div id="card-element" class="mb-4">
                                <!-- Stripe Card Element will be inserted here -->
                            </div>
                            <div id="card-errors" class="alert alert-danger d-none" role="alert"></div>
                            
                            <button type="submit" class="btn btn-primary btn-lg w-100" id="submit-button">
                                <i class="fas fa-lock me-2"></i>Pay Now
                            </button>
                        </form>
                        
                        <div class="mt-4 text-center">
                            <a href="<?php echo BASE_URL; ?>/checkout.php" class="btn btn-outline-light">
                                <i class="fas fa-arrow-left me-2"></i>Back to Checkout
                            </a>
                        </div>
                        
                        <div class="text-center mt-4">
                            <small class="text-muted">
                                <i class="fas fa-shield-alt me-1"></i>
                                Secure payment powered by Stripe
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Stripe.js -->
<script src="https://js.stripe.com/v3/"></script>

<script>
const stripe = Stripe('<?php echo $publishable_key; ?>');
const elements = stripe.elements();

const cardElement = elements.create('card', {
    style: {
        base: {
            color: '#fff',
            fontFamily: '"Inter", sans-serif',
            fontSize: '16px',
            '::placeholder': {
                color: '#6b7280'
            }
        },
        invalid: {
            color: '#ef4444'
        }
    }
});

cardElement.mount('#card-element');

const form = document.getElementById('payment-form');
const submitButton = document.getElementById('submit-button');
const cardErrors = document.getElementById('card-errors');

form.addEventListener('submit', async (event) => {
    event.preventDefault();
    
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
    cardErrors.classList.add('d-none');
    
    // Create payment intent on server
    const response = await fetch('<?php echo BASE_URL; ?>/payments/stripe-create-intent.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            order_id: <?php echo $order_id; ?>
        })
    });
    
    const result = await response.json();
    
    if (!result.success) {
        cardErrors.textContent = result.message || 'Payment initialization failed';
        cardErrors.classList.remove('d-none');
        submitButton.disabled = false;
        submitButton.innerHTML = '<i class="fas fa-lock me-2"></i>Pay Now';
        return;
    }
    
    // Confirm card payment
    const { error, paymentIntent } = await stripe.confirmCardPayment(result.client_secret, {
        payment_method: {
            card: cardElement,
            billing_details: {
                name: '<?php echo sanitize($order['customer_name']); ?>',
                email: '<?php echo sanitize($order['customer_email']); ?>'
            }
        }
    });
    
    if (error) {
        cardErrors.textContent = error.message;
        cardErrors.classList.remove('d-none');
        submitButton.disabled = false;
        submitButton.innerHTML = '<i class="fas fa-lock me-2"></i>Pay Now';
    } else {
        // Payment successful
        if (paymentIntent.status === 'succeeded') {
            window.location.href = '<?php echo BASE_URL; ?>/payments/stripe-success.php?order_id=<?php echo $order_id; ?>&payment_intent=' + paymentIntent.id;
        }
    }
});

cardElement.on('change', (event) => {
    if (event.error) {
        cardErrors.textContent = event.error.message;
        cardErrors.classList.remove('d-none');
    } else {
        cardErrors.classList.add('d-none');
    }
});
</script>

<style>
.payment-card {
    border: 1px solid var(--dark-lighter);
    background: var(--gradient-card);
}

.payment-icon {
    width: 100px;
    height: 100px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 3rem;
}

.payment-icon.stripe {
    background: linear-gradient(135deg, #635bff 0%, #96f 100%);
    color: white;
}

.order-summary-box {
    padding: 1.5rem;
    background: var(--dark);
    border-radius: var(--radius);
}

#card-element {
    padding: 1rem;
    background: var(--dark);
    border: 1px solid var(--dark-lighter);
    border-radius: var(--radius);
}

.StripeElement--focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.15);
}
</style>

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