<?php
/**
 * Checkout Page - PREMIUM VERSION
 * Digital Marketplace
 */

require_once __DIR__ . '/config/database.php';

$page_title = 'Checkout';

// Require login for checkout
if (!is_user_logged_in()) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    set_flash_message('Please login to proceed with checkout.', 'info');
    header('Location: ' . BASE_URL . '/login.php');
    exit;
}

// Get cart items
$cart_items = get_cart_items();

if (empty($cart_items)) {
    set_flash_message('Your cart is empty.', 'info');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get user data
$user = get_current_user_data($pdo);

// Calculate totals
$subtotal = get_cart_total();
$tax_rate = (float)(get_setting('tax_rate', '0'));
$tax = $subtotal * ($tax_rate / 100);
$shipping = 0;
$discount = 0;

// Apply coupon
$coupon_code = null;
if (isset($_SESSION['applied_coupon'])) {
    $coupon = get_coupon_by_code($_SESSION['applied_coupon']);
    if ($coupon) {
        $coupon_code = $coupon['code'];
        $discount = calculate_coupon_discount($coupon, $subtotal);
    }
}

$total = $subtotal + $tax + $shipping - $discount;

// Get active payment gateways
$payment_gateways = get_active_payment_gateways();

// Handle checkout submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_order'])) {
    // Verify CSRF
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request. Please try again.', 'error');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    // Get form data
    $customer_name = sanitize($_POST['customer_name'] ?? $user['name']);
    $customer_email = sanitize($_POST['customer_email'] ?? $user['email']);
    $customer_phone = sanitize($_POST['customer_phone'] ?? $user['phone'] ?? '');
    $payment_method = sanitize($_POST['payment_method'] ?? '');
    
    // Validate
    $errors = [];
    if (empty($customer_name)) $errors[] = 'Name is required';
    if (empty($customer_email) || !validate_email($customer_email)) $errors[] = 'Valid email is required';
    if (empty($payment_method)) $errors[] = 'Please select a payment method';
    
    if (empty($errors)) {
        // Check for affiliate referral
        $affiliate_id = null;
        $affiliate_commission = 0;
        if (isset($_COOKIE['affiliate_code'])) {
            $affiliate = get_affiliate_by_code($_COOKIE['affiliate_code']);
            if ($affiliate && $affiliate['status'] === 'active') {
                $affiliate_id = $affiliate['id'];
                $affiliate_commission = $total * ($affiliate['commission_rate'] / 100);
            }
        }
        
        // Create order
        $order_data = [
            'user_id' => get_current_user_id(),
            'customer_name' => $customer_name,
            'customer_email' => $customer_email,
            'customer_phone' => $customer_phone,
            'subtotal' => $subtotal,
            'tax' => $tax,
            'shipping' => $shipping,
            'discount' => $discount,
            'total' => $total,
            'coupon_code' => $coupon_code,
            'payment_method' => $payment_method,
            'license_type' => $cart_items[0]['license_type'] ?? 'regular',
            'affiliate_id' => $affiliate_id,
            'affiliate_commission' => $affiliate_commission
        ];
        
        $order_id = create_order($order_data);
        
        if ($order_id) {
            // Add order items
            foreach ($cart_items as $item) {
                add_order_item(
                    $order_id,
                    $item['product_id'],
                    $item['name'],
                    $item['price'],
                    $item['quantity'],
                    $item['license_type'] ?? 'regular',
                    $item['download_limit'] ?? 5
                );
            }
            
            // Update coupon usage
            if ($coupon_code) {
                increment_coupon_usage($coupon['id']);
            }
            
            // Clear cart
            clear_cart();
            unset($_SESSION['applied_coupon']);
            
            // Track affiliate referral
            if ($affiliate_id) {
                track_affiliate_referral($affiliate_id, $order_id, $total);
            }
            
            // Log activity
            log_activity('order_created', "Order #{$order_id} created");
            
            // Send order confirmation email
            send_order_confirmation($order_id);
            
            // Redirect to payment gateway or order confirmation
            $order = get_order_by_id($order_id);
            
            // Store order in session for payment processing
            $_SESSION['pending_order_id'] = $order_id;
            
            // Redirect based on payment method
            switch ($payment_method) {
                case 'paypal':
                    header('Location: ' . BASE_URL . '/payments/paypal.php?order_id=' . $order_id);
                    break;
                case 'stripe':
                    header('Location: ' . BASE_URL . '/payments/stripe.php?order_id=' . $order_id);
                    break;
                case 'paystack':
                    header('Location: ' . BASE_URL . '/payments/paystack.php?order_id=' . $order_id);
                    break;
                case 'flutterwave':
                    header('Location: ' . BASE_URL . '/payments/flutterwave.php?order_id=' . $order_id);
                    break;
                case 'bitcoin':
                    header('Location: ' . BASE_URL . '/payments/bitcoin.php?order_id=' . $order_id);
                    break;
                case 'bank_transfer':
                case 'eft':
                    header('Location: ' . BASE_URL . '/payments/bank-transfer.php?order_id=' . $order_id);
                    break;
                default:
                    // For cash on delivery or other methods
                    update_order_payment_status($order_id, 'pending');
                    set_flash_message('Order placed successfully! We will contact you soon.', 'success');
                    header('Location: ' . BASE_URL . '/account/order-view.php?id=' . $order_id);
            }
            exit;
        } else {
            set_flash_message('Failed to create order. Please try again.', 'error');
        }
    } else {
        set_flash_message(implode('<br>', $errors), 'error');
    }
}

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

<section class="section">
    <div class="container">
        <h1 class="mb-4">Checkout</h1>
        
        <form method="POST" id="checkoutForm" data-validate>
            <?php echo csrf_field(); ?>
            
            <div class="row g-4">
                <!-- Left Column - Customer Info & Payment -->
                <div class="col-lg-8">
                    <!-- Customer Information -->
                    <div class="card mb-4" data-aos="fade-right">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-user me-2"></i>Customer Information</h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Full Name *</label>
                                    <input type="text" name="customer_name" class="form-control" 
                                           value="<?php echo sanitize($user['name']); ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Email Address *</label>
                                    <input type="email" name="customer_email" class="form-control" 
                                           value="<?php echo sanitize($user['email']); ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Phone Number</label>
                                    <input type="tel" name="customer_phone" class="form-control" 
                                           value="<?php echo sanitize($user['phone'] ?? ''); ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Method -->
                    <div class="card" data-aos="fade-right" data-aos-delay="100">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-credit-card me-2"></i>Payment Method</h5>
                        </div>
                        <div class="card-body">
                            <div class="payment-methods">
                                <?php foreach ($payment_gateways as $gateway): ?>
                                <?php $config = $gateway['config'] ?? []; ?>
                                <div class="payment-method-option mb-3">
                                    <input type="radio" name="payment_method" id="payment_<?php echo $gateway['gateway']; ?>" 
                                           value="<?php echo $gateway['gateway']; ?>" required>
                                    <label for="payment_<?php echo $gateway['gateway']; ?>" class="payment-method-label">
                                        <div class="d-flex align-items-center">
                                            <div class="payment-icon">
                                                <?php if ($gateway['gateway'] === 'paypal'): ?>
                                                    <i class="fab fa-paypal"></i>
                                                <?php elseif ($gateway['gateway'] === 'stripe'): ?>
                                                    <i class="fab fa-stripe"></i>
                                                <?php elseif ($gateway['gateway'] === 'paystack'): ?>
                                                    <i class="fas fa-credit-card"></i>
                                                <?php elseif ($gateway['gateway'] === 'flutterwave'): ?>
                                                    <i class="fas fa-money-bill-wave"></i>
                                                <?php elseif ($gateway['gateway'] === 'bitcoin'): ?>
                                                    <i class="fab fa-bitcoin"></i>
                                                <?php elseif ($gateway['gateway'] === 'bank_transfer' || $gateway['gateway'] === 'eft'): ?>
                                                    <i class="fas fa-university"></i>
                                                <?php else: ?>
                                                    <i class="fas fa-credit-card"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div class="payment-info">
                                                <span class="payment-name"><?php echo ucfirst(str_replace('_', ' ', $gateway['gateway'])); ?></span>
                                                <small class="payment-description text-muted d-block">
                                                    <?php echo $config['description'] ?? 'Secure payment processing'; ?>
                                                </small>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Right Column - Order Summary -->
                <div class="col-lg-4">
                    <div class="card order-summary" data-aos="fade-left">
                        <div class="card-header">
                            <h5 class="mb-0">Order Summary</h5>
                        </div>
                        <div class="card-body">
                            <!-- Order Items -->
                            <div class="order-items mb-4">
                                <?php foreach ($cart_items as $item): ?>
                                <div class="order-item d-flex align-items-center gap-3 mb-3 pb-3 border-bottom border-secondary">
                                    <img src="<?php echo get_product_image_url($item); ?>" 
                                         alt="<?php echo sanitize($item['name']); ?>"
                                         class="rounded"
                                         style="width: 60px; height: 60px; object-fit: cover;"
                                         onerror="this.src='<?php echo ASSETS_URL; ?>/images/no-image.jpg'">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1"><?php echo sanitize($item['name']); ?></h6>
                                        <small class="text-muted">
                                            <?php echo $item['quantity']; ?> x <?php echo format_price($item['price']); ?>
                                            <?php if ($item['license_type']): ?>
                                                <span class="badge bg-secondary ms-1"><?php echo ucfirst($item['license_type']); ?></span>
                                            <?php endif; ?>
                                        </small>
                                    </div>
                                    <div class="text-end">
                                        <strong><?php echo format_price($item['price'] * $item['quantity']); ?></strong>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Price Breakdown -->
                            <div class="price-breakdown">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Subtotal</span>
                                    <span><?php echo format_price($subtotal); ?></span>
                                </div>
                                
                                <?php if ($tax > 0): ?>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Tax (<?php echo $tax_rate; ?>%)</span>
                                    <span><?php echo format_price($tax); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($discount > 0): ?>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-success">Discount</span>
                                    <span class="text-success">-<?php echo format_price($discount); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <hr class="border-secondary">
                                
                                <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_price($total); ?></span>
                                </div>
                            </div>
                            
                            <!-- Place Order Button -->
                            <button type="submit" name="place_order" class="btn btn-primary btn-lg w-100 mt-4">
                                <i class="fas fa-lock me-2"></i>Place Order
                            </button>
                            
                            <p class="text-center text-muted mt-3 mb-0">
                                <small><i class="fas fa-shield-alt me-1"></i>Secure checkout with SSL encryption</small>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

<style>
/* Checkout Styles */
.order-summary {
    position: sticky;
    top: 100px;
}

.order-item {
    border-color: var(--dark-lighter) !important;
}

.order-item:last-child {
    border-bottom: none !important;
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
}

/* Payment Methods */
.payment-method-option input {
    display: none;
}

.payment-method-label {
    display: block;
    padding: 16px;
    background: var(--dark-lighter);
    border: 2px solid var(--dark-lighter);
    border-radius: var(--radius);
    cursor: pointer;
    transition: var(--transition);
}

.payment-method-option input:checked + .payment-method-label {
    border-color: var(--primary);
    background: rgba(139, 92, 246, 0.1);
}

.payment-icon {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--dark);
    border-radius: var(--radius);
    font-size: 1.5rem;
    margin-right: 16px;
}

.payment-name {
    font-weight: 600;
    color: var(--white);
}
</style>

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