<?php
/**
 * PayPal 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 PayPal settings
$paypal = get_payment_gateway('paypal');
if (!$paypal || !$paypal['is_active']) {
    set_flash_message('PayPal payment is currently unavailable.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

$config = $paypal['config'];
$client_id = $config['client_id'] ?? '';
$client_secret = $config['client_secret'] ?? '';
$sandbox = ($config['mode'] ?? 'sandbox') === 'sandbox';

$paypal_url = $sandbox ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';

$page_title = 'Pay with PayPal';

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 text-center">
                        <div class="payment-icon paypal mb-4">
                            <i class="fab fa-paypal"></i>
                        </div>
                        
                        <h2 class="mb-2">Complete Your Payment</h2>
                        <p class="text-muted mb-4">Order #<?php echo $order['order_number']; ?></p>
                        
                        <div class="order-summary-box mb-4">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">Amount:</span>
                                <span class="h4 mb-0"><?php echo format_price($order['total']); ?></span>
                            </div>
                        </div>
                        
                        <!-- PayPal Button Container -->
                        <div id="paypal-button-container"></div>
                        
                        <div class="mt-4">
                            <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>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- PayPal SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=<?php echo $client_id; ?>&currency=<?php echo CURRENCY; ?>&intent=capture"></script>

<script>
paypal.Buttons({
    createOrder: function(data, actions) {
        return actions.order.create({
            purchase_units: [{
                reference_id: '<?php echo $order['order_number']; ?>',
                description: 'Order #<?php echo $order['order_number']; ?>',
                amount: {
                    currency_code: '<?php echo CURRENCY; ?>',
                    value: '<?php echo number_format($order['total'], 2, '.', ''); ?>'
                }
            }]
        });
    },
    onApprove: function(data, actions) {
        return actions.order.capture().then(function(details) {
            // Send payment details to server
            fetch('<?php echo BASE_URL; ?>/payments/paypal-callback.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    order_id: '<?php echo $order_id; ?>',
                    paypal_order_id: data.orderID,
                    paypal_payment_id: details.id,
                    payer_email: details.payer.email_address,
                    status: details.status
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    window.location.href = result.redirect_url;
                } else {
                    alert(result.message || 'Payment failed. Please try again.');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Something went wrong. Please try again.');
            });
        });
    },
    onCancel: function(data) {
        alert('Payment cancelled. You can try again.');
    },
    onError: function(err) {
        console.error('PayPal Error:', err);
        alert('Payment error. Please try again or use a different payment method.');
    }
}).render('#paypal-button-container');
</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.paypal {
    background: linear-gradient(135deg, #003087 0%, #0070e0 100%);
    color: white;
}

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

#paypal-button-container {
    min-height: 45px;
}
</style>

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