<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../config/currency.php';
require_once '../config/payment_security.php';
require_once '../includes/functions.php';
require_once '../includes/payments.php';

// Cart Manager Class
class CartManager {
    private $db;
    private $userId;

    public function __construct($db, $userId = null) {
        $this->db = $db;
        $this->userId = $userId;
    }

    public function getCart() {
        if (!$this->userId) {
            return ['items' => [], 'total' => 0.00, 'currency' => 'USD'];
        }

        $stmt = $this->db->prepare("
            SELECT ci.*,
                   COALESCE(c.title, e.title) as title,
                   COALESCE(c.price, e.price) as price,
                   COALESCE(c.currency, e.currency) as currency,
                   COALESCE(c.is_free, e.is_free) as is_free,
                   COALESCE(c.thumbnail, NULL) as thumbnail,
                   COALESCE(c.max_students, NULL) as max_students,
                   ci.item_type
            FROM cart_items ci
            LEFT JOIN courses c ON ci.item_id = c.id AND ci.item_type = 'course'
            LEFT JOIN exams e ON ci.item_id = e.id AND ci.item_type = 'exam'
            WHERE ci.user_id = ?
            ORDER BY ci.created_at ASC
        ");
        $stmt->execute([$this->userId]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = 0.00;
        $currency = 'USD';

        foreach ($items as &$item) {
            if (!$item['is_free']) {
                $total += floatval($item['price']);
                $currency = $item['currency'];
            }
        }

        return [
            'items' => $items,
            'total' => $total,
            'currency' => $currency,
            'item_count' => count($items)
        ];
    }

    public function addToCart($itemId, $itemType = 'course') {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $table = $itemType === 'exam' ? 'exams' : 'courses';
        $statusField = $itemType === 'exam' ? 'status' : 'status';
        $statusValue = 'published';

        // Check if item exists and is published
        $stmt = $this->db->prepare("SELECT id, title, is_free FROM {$table} WHERE id = ? AND {$statusField} = ?");
        $stmt->execute([$itemId, $statusValue]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$item) {
            return ['success' => false, 'error' => ucfirst($itemType) . ' not found'];
        }

        // Check if already enrolled/purchased
        if ($itemType === 'course') {
            $stmt = $this->db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status != 'dropped'");
            $stmt->execute([$itemId, $this->userId]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Already enrolled in this course'];
            }
        } else {
            $stmt = $this->db->prepare("SELECT id FROM exam_attempts WHERE exam_id = ? AND student_id = ?");
            $stmt->execute([$itemId, $this->userId]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Already attempted this exam'];
            }
        }

        // Check if already in cart
        $stmt = $this->db->prepare("SELECT id FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = ?");
        $stmt->execute([$this->userId, $itemId, $itemType]);
        $existingCartItem = $stmt->fetch();

        if ($existingCartItem) {
            $stmt = $this->db->prepare("UPDATE cart_items SET updated_at = NOW() WHERE id = ?");
            $stmt->execute([$existingCartItem['id']]);
            return ['success' => true, 'message' => ucfirst($itemType) . ' already in cart', 'already_in_cart' => true];
        }

        // Add to cart
        $stmt = $this->db->prepare("INSERT INTO cart_items (user_id, item_type, item_id, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$this->userId, $itemType, $itemId]);

        return ['success' => true, 'message' => ucfirst($itemType) . ' added to cart'];
    }

    public function removeFromCart($itemId, $itemType = 'course') {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $stmt = $this->db->prepare("DELETE FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = ?");
        $stmt->execute([$this->userId, $itemId, $itemType]);

        return ['success' => true, 'message' => ucfirst($itemType) . ' removed from cart'];
    }

    public function clearCart() {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $stmt = $this->db->prepare("DELETE FROM cart_items WHERE user_id = ?");
        $stmt->execute([$this->userId]);

        return ['success' => true, 'message' => 'Cart cleared'];
    }
}

$db = getDB();

if (!isLoggedIn()) {
    header('Location: login.php?redirect=checkout.php');
    exit;
}

$userId = $_SESSION['user_id'];
$user = getUserContext();

$cartManager = new CartManager($db, $userId);

// Handle add/remove item requests
$actionMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_item') {
        $itemId = intval($_POST['item_id'] ?? 0);
        $itemType = $_POST['item_type'] ?? 'course';
        if ($itemId > 0) {
            $result = $cartManager->addToCart($itemId, $itemType);
            $actionMessage = $result;
        }
    } elseif ($_POST['action'] === 'remove_item') {
        $itemId = intval($_POST['item_id'] ?? 0);
        $itemType = $_POST['item_type'] ?? 'course';
        if ($itemId > 0) {
            $result = $cartManager->removeFromCart($itemId, $itemType);
            $actionMessage = $result;
        }
    } elseif ($_POST['action'] === 'clear_cart') {
        $result = $cartManager->clearCart();
        $actionMessage = $result;
    }
    // Refresh cart after action
    $cart = $cartManager->getCart();
} else {
    $cart = $cartManager->getCart();
}

$cartItems = $cart['items'];
$subtotal = 0;
foreach ($cartItems as $item) {
    if (!$item['is_free']) {
        $subtotal += floatval($item['price']);
    }
}
$tax = $subtotal * 0.1;
$total = $subtotal + $tax;

// Generate CSRF token
$csrfToken = PaymentSecurity::generateCSRFToken();

// Get available payment gateways
$paymentGateways = [];
try {
    $stmt = $db->prepare("SELECT DISTINCT gateway_name FROM payment_gateway_settings WHERE is_active = 1");
    $stmt->execute();
    $gateways = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($gateways as $g) {
        $paymentGateways[] = $g['gateway_name'];
    }
} catch (Exception $e) {
    // Default gateways
    $paymentGateways = ['paynow', 'paypal'];
}

// Default to paynow if no gateways found
if (empty($paymentGateways)) {
    $paymentGateways = ['paynow'];
}

// Handle payment processing
$paymentResult = null;
$paymentError = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process_payment') {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !PaymentSecurity::validateCSRFToken($_POST['csrf_token'])) {
        $paymentError = 'Invalid form submission. Please refresh the page and try again.';
    } else {
        try {
            $gatewayName = $_POST['payment_gateway'] ?? 'paynow';
            $discountCode = !empty($_POST['discount_code']) ? $_POST['discount_code'] : null;
            
            // Validate gateway is configured and active
            if (!in_array($gatewayName, $paymentGateways)) {
                throw new Exception('The selected payment method is not currently available. Please choose another option.');
            }
            
            // Get active environment for this gateway
            $stmt = $db->prepare("
                SELECT gateway_type FROM payment_gateway_settings
                WHERE gateway_name = ? AND is_active = 1 LIMIT 1
            ");
            $stmt->execute([$gatewayName]);
            $environment = $stmt->fetchColumn() ?: 'sandbox';
            
            // Initialize payment gateway
            $gateway = new PaymentGateway($gatewayName, $environment);
            
            // Get cart items for processing
            $cartManager = new CartManager($db, $userId);
            $cart = $cartManager->getCart();
            
            if (empty($cart['items'])) {
                $paymentError = 'Your cart is empty.';
            } else {
                // Get user email
                $stmt = $db->prepare("SELECT email FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $userEmail = $stmt->fetchColumn();
                
                $itemType = 'cart';
                $itemId = json_encode(array_column($cart['items'], 'item_id'));
                $amount = $total;
                $currency = $cart['currency'] ?: 'USD';
                $itemName = count($cart['items']) > 1 ? 'Multiple Courses' : $cart['items'][0]['title'];
                
                // Process payment via configured gateway
                if ($gatewayName === 'paynow') {
                    $result = $gateway->processPaynowPayment(
                        $userId, $itemType, $itemId, $amount, $currency, $discountCode, $userEmail, $itemName
                    );
                } elseif ($gatewayName === 'paypal') {
                    $result = $gateway->processPaypalPayment(
                        $userId, $itemType, $itemId, $amount, $currency, $discountCode, $userEmail, $itemName
                    );
                } else {
                    throw new Exception('Unsupported payment gateway.');
                }
                
                if ($result['success'] && !empty($result['redirect_url'])) {
                    // Redirect to payment gateway for authorization
                    header('Location: ' . $result['redirect_url']);
                    exit;
                } elseif ($result['success']) {
                    // Immediate success (rare with real gateways)
                    $paymentResult = [
                        'success' => true,
                        'transaction_id' => $result['transaction_id'],
                        'amount' => $amount,
                        'items' => count($cart['items'])
                    ];
                } else {
                    $paymentError = $result['error'] ?? 'Payment processing failed. Please try again.';
                }
            }
        } catch (Exception $e) {
            $paymentError = $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?>'s Checkout | Mutalex Academy</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        @keyframes fade-in { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .animate-fade-in { animation: fade-in 0.4s ease-out forwards; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-thumb { background: #CBD5E1; border-radius: 10px; }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen flex flex-col">

    <!-- Header (Synced with student panel) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-50 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Logo" class="h-9 w-9">
                <div>
                    <h1 class="text-lg font-bold text-primary-blue leading-none">Mutalex Academy</h1>
                    <p class="text-[11px] text-gray-500 uppercase tracking-wider font-semibold mt-1">Student Portal</p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <div class="hidden sm:flex flex-col items-end mr-2">
                    <span class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                    <span class="text-[10px] text-green-600 font-bold uppercase">Online Status</span>
                </div>
                <img class="h-10 w-10 rounded-xl border-2 border-indigo-50 object-cover shadow-sm" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="Avatar">
                <button class="lg:hidden p-2 rounded-lg bg-slate-100 text-slate-600" id="mobileMenuButton">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </header>

    <div class="flex flex-1 pt-16">
        <!-- Sidebar (Synced with student panel) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 sticky top-16 h-[calc(100vh-64px)] overflow-y-auto">
            <nav class="space-y-1">
                <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>
                <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-book-open w-5"></i>
                    <span class="font-medium">Catalog</span>
                </a>
                <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-graduation-cap w-5"></i>
                    <span class="font-medium">My Courses</span>
                </a>
                <div class="pt-4 pb-2">
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-3">Account</p>
                </div>
                <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-chart-pie w-5"></i>
                    <span class="font-medium">Grades</span>
                </a>
                <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-xl text-red-500 hover:bg-red-50 transition duration-150">
                    <i class="fas fa-sign-out-alt w-5"></i>
                    <span class="font-medium">Logout</span>
                </a>
            </nav>
            <div class="mt-10 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                <p class="text-[10px] text-slate-400 font-bold uppercase">Support ID</p>
                <p class="text-xs font-mono text-slate-600 mt-1"><?php echo strtoupper(substr(md5($userId), 0, 8)); ?></p>
            </div>
        </aside>

        <!-- Mobile Menu -->
        <div id="mobileMenu" class="fixed inset-0 bg-slate-900/50 z-[60] hidden backdrop-blur-sm lg:hidden">
            <div class="w-72 bg-white h-full p-6 shadow-2xl animate-fade-in">
                <div class="flex justify-between items-center mb-8">
                    <h2 class="font-bold text-primary-blue">Menu</h2>
                    <button id="closeMobileMenu" class="text-2xl text-slate-400">&times;</button>
                </div>
                <nav class="space-y-2">
                    <a href="dashboard.php" class="block p-3 rounded-xl bg-slate-50 text-slate-700">🏠 Dashboard</a>
                    <a href="available_courses.php" class="block p-3 rounded-xl text-slate-700">📖 Catalog</a>
                    <a href="../logout.php" class="block p-3 rounded-xl text-red-500">🚪 Logout</a>
                </nav>
            </div>
        </div>

        <!-- Main Content -->
        <main class="flex-1 p-4 lg:p-8">
            <div class="max-w-5xl mx-auto">
                
                <!-- Progress Stepper -->
                <div class="flex items-center justify-center mb-10 max-w-xl mx-auto px-4">
                    <?php
                    $currentStep = isset($_GET['step']) ? intval($_GET['step']) : 1;
                    $steps = [['id' => 1, 'l' => 'Details'], ['id' => 2, 'l' => 'Payment'], ['id' => 3, 'l' => 'Review']];
                    foreach ($steps as $i => $s):
                        $active = $currentStep >= $s['id'];
                    ?>
                        <div class="flex flex-col items-center relative">
                            <div class="w-10 h-10 rounded-full flex items-center justify-center border-2 z-10 transition-all <?php echo $active ? 'bg-indigo-600 border-indigo-600 text-white' : 'bg-white border-slate-200 text-slate-400'; ?>">
                                <?php if ($currentStep > $s['id']) echo '<i class="fas fa-check text-sm"></i>'; else echo $s['id']; ?>
                            </div>
                            <span class="text-[10px] mt-2 font-bold uppercase tracking-tighter <?php echo $active ? 'text-indigo-900' : 'text-slate-400'; ?>"><?php echo $s['l']; ?></span>
                        </div>
                        <?php if ($i < 2): ?>
                            <div class="flex-1 h-1 mx-2 -mt-6 transition-all <?php echo $currentStep > $s['id'] ? 'bg-indigo-600' : 'bg-slate-200'; ?>"></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                    <!-- Left: Forms -->
                    <div class="lg:col-span-7">
                        <?php if (empty($cartItems)): ?>
                            <div class="bg-white rounded-3xl p-12 text-center border border-slate-200 shadow-sm animate-fade-in">
                                <div class="w-20 h-20 bg-indigo-50 text-indigo-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                    <i class="fas fa-shopping-basket text-3xl"></i>
                                </div>
                                <h2 class="text-2xl font-bold text-slate-900">Your cart is empty</h2>
                                <p class="text-slate-500 mt-2 mb-8">It looks like you haven't added any courses yet.</p>
                                <a href="available_courses.php" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-100 hover:bg-indigo-700 transition-all inline-block">Explore Catalog</a>
                            </div>
                        <?php else: ?>
                            <div class="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden animate-fade-in">
                                <div class="p-6 lg:p-10">
                                    <?php if ($paymentResult && $paymentResult['success']): ?>
                                        <!-- Success Notification -->
                                        <div class="text-center py-8 space-y-6 animate-fade-in">
                                            <div class="w-24 h-24 bg-green-100 text-green-500 rounded-full flex items-center justify-center mx-auto animate-bounce">
                                                <i class="fas fa-check-circle text-5xl"></i>
                                            </div>
                                            <div>
                                                <h3 class="text-2xl font-bold text-slate-900">Payment Successful!</h3>
                                                <p class="text-slate-500 mt-2">Thank you for your purchase.</p>
                                            </div>
                                            
                                            <!-- Transaction Details -->
                                            <div class="p-6 bg-slate-50 rounded-2xl border border-slate-200 text-left max-w-md mx-auto">
                                                <div class="space-y-3">
                                                    <div class="flex justify-between">
                                                        <span class="text-slate-500">Transaction ID</span>
                                                        <span class="font-mono text-sm font-bold text-slate-700"><?php echo htmlspecialchars($paymentResult['transaction_id']); ?></span>
                                                    </div>
                                                    <div class="flex justify-between">
                                                        <span class="text-slate-500">Amount Paid</span>
                                                        <span class="font-bold text-green-600">$<?php echo number_format($paymentResult['amount'], 2); ?></span>
                                                    </div>
                                                    <div class="flex justify-between">
                                                        <span class="text-slate-500">Items Enrolled</span>
                                                        <span class="font-bold text-slate-700"><?php echo $paymentResult['items']; ?> course(s)</span>
                                                    </div>
                                                    <div class="flex justify-between">
                                                        <span class="text-slate-500">Date</span>
                                                        <span class="text-slate-700"><?php echo date('Y-m-d H:i'); ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Actions -->
                                            <div class="flex flex-col sm:flex-row gap-3 justify-center pt-4">
                                                <a href="courses.php" class="px-8 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all inline-flex items-center justify-center gap-2">
                                                    <i class="fas fa-graduation-cap"></i> My Courses
                                                </a>
                                                <a href="dashboard.php" class="px-8 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition-all inline-flex items-center justify-center gap-2">
                                                    <i class="fas fa-home"></i> Dashboard
                                                </a>
                                            </div>
                                            
                                            <!-- Email Notification Note -->
                                            <div class="flex items-center justify-center gap-2 p-4 bg-blue-50 rounded-xl border border-blue-200 max-w-md mx-auto">
                                                <i class="fas fa-envelope text-blue-600"></i>
                                                <span class="text-sm text-blue-700">A confirmation email has been sent to <?php echo htmlspecialchars($user['email']); ?></span>
                                            </div>
                                        </div>
                                    <?php elseif ($currentStep == 1): ?>
                                        <form method="GET" class="space-y-6">
                                            <input type="hidden" name="step" value="2">
                                            <h3 class="text-xl font-bold text-slate-900">Billing Details</h3>
                                            <div class="grid grid-cols-2 gap-4">
                                                <div class="col-span-2">
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Email Address</label>
                                                    <input type="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div class="col-span-2">
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Billing Address</label>
                                                    <input type="text" placeholder="Street Address" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div>
                                                    <label class="text-xs font-bold text-slate-500 uppercase">City</label>
                                                    <input type="text" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div>
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Postal Code</label>
                                                    <input type="text" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                            </div>
                                            <button type="submit" class="w-full bg-indigo-600 text-white py-4 rounded-2xl font-bold hover:bg-indigo-700 shadow-xl shadow-indigo-100 transition-all flex items-center justify-center gap-2">
                                                Continue to Payment <i class="fas fa-arrow-right text-xs"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($currentStep == 2): ?>
                                        <form method="POST" id="payment-form" class="space-y-6">
                                            <input type="hidden" name="action" value="process_payment">
                                            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                                            <h3 class="text-xl font-bold text-slate-900">Payment Method</h3>
                                            
                                            <!-- Error Display -->
                                            <?php if ($paymentError): ?>
                                                <div class="p-4 bg-red-50 border border-red-200 rounded-2xl">
                                                    <div class="flex items-center gap-3 text-red-600">
                                                        <i class="fas fa-exclamation-circle"></i>
                                                        <span class="text-sm font-medium"><?php echo htmlspecialchars($paymentError); ?></span>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div class="grid grid-cols-<?php echo count($paymentGateways); ?> gap-3">
                                                <?php if (in_array('paypal', $paymentGateways)): ?>
                                                    <button type="button" onclick="selectPayment('paypal')" id="btn-paypal" class="payment-btn p-4 border-2 rounded-2xl flex flex-col items-center gap-2 transition-all <?php echo (isset($_POST['payment_gateway']) && $_POST['payment_gateway'] === 'paypal') ? 'border-indigo-600 bg-indigo-50' : 'border-slate-100 hover:border-indigo-100'; ?>">
                                                        <i class="fab fa-paypal text-blue-500"></i>
                                                        <span class="text-[10px] font-bold uppercase">PayPal</span>
                                                    </button>
                                                <?php endif; ?>
                                                <button type="button" onclick="selectPayment('card')" id="btn-card" class="payment-btn p-4 border-2 rounded-2xl flex flex-col items-center gap-2 transition-all <?php echo (isset($_POST['payment_gateway']) && $_POST['payment_gateway'] === 'card') ? 'border-indigo-600 bg-indigo-50' : 'border-slate-100 hover:border-indigo-100'; ?>">
                                                    <i class="fas fa-credit-card text-indigo-600"></i>
                                                    <span class="text-[10px] font-bold uppercase">Card</span>
                                                </button>
                                            </div>

                                            <div class="mt-8">
                                                <!-- PayPal Form -->
                                                <div id="paypal-form" class="payment-method-form space-y-4 <?php echo (isset($_POST['payment_gateway']) && $_POST['payment_gateway'] === 'paypal') ? '' : 'hidden'; ?>">
                                                    <input type="hidden" name="payment_gateway" value="paypal">
                                                    <div class="p-6 bg-blue-50 rounded-2xl border border-blue-100">
                                                        <div class="flex items-center gap-4 mb-4">
                                                            <div class="w-12 h-12 bg-white rounded-xl flex items-center justify-center border border-slate-100 shadow-sm text-blue-600">
                                                                <i class="fab fa-paypal text-xl"></i>
                                                            </div>
                                                            <div>
                                                                <p class="font-bold text-slate-900">PayPal</p>
                                                                <p class="text-xs text-slate-500">Pay securely with your PayPal account</p>
                                                            </div>
                                                        </div>
                                                        <p class="text-sm text-blue-700 font-medium">You will be redirected to PayPal to complete your payment securely.</p>
                                                    </div>
                                                </div>
                                                
                                                <!-- Card Form -->
                                                <div id="card-form" class="payment-method-form space-y-4 <?php echo (isset($_POST['payment_gateway']) && $_POST['payment_gateway'] === 'card') ? '' : 'hidden'; ?>">
                                                    <input type="hidden" name="payment_gateway" value="card">
                                                    <div class="p-6 bg-white rounded-2xl border border-slate-200">
                                                        <div class="flex items-center gap-4 mb-4">
                                                            <div class="w-12 h-12 bg-indigo-600 rounded-xl flex items-center justify-center text-white">
                                                                <i class="fas fa-credit-card text-xl"></i>
                                                            </div>
                                                            <div>
                                                                <p class="font-bold text-slate-900">Credit/Debit Card</p>
                                                                <p class="text-xs text-slate-500">Visa, Mastercard, American Express</p>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Card Number -->
                                                        <div class="space-y-1">
                                                            <label class="text-xs font-bold text-slate-500 uppercase">Card Number</label>
                                                            <div class="relative">
                                                                <input type="text" 
                                                                       name="card_number" 
                                                                       id="card_number"
                                                                       placeholder="1234 5678 9012 3456" 
                                                                       class="w-full mt-1 p-3 pl-12 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                                                                       maxlength="19"
                                                                       oninput="validateCardNumber(this)"
                                                                       onblur="validateCardNumber(this)">
                                                                <i class="fas fa-credit-card absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
                                                            </div>
                                                            <p class="text-xs text-red-500 hidden" id="card_number_error"></p>
                                                        </div>
                                                        
                                                        <div class="grid grid-cols-2 gap-4 mt-4">
                                                            <!-- Expiry Date -->
                                                            <div class="space-y-1">
                                                                <label class="text-xs font-bold text-slate-500 uppercase">Expiry Date</label>
                                                                <input type="text" 
                                                                       name="card_expiry" 
                                                                       id="card_expiry"
                                                                       placeholder="MM/YY" 
                                                                       class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                                                                       maxlength="5"
                                                                       oninput="validateExpiry(this)"
                                                                       onblur="validateExpiry(this)">
                                                                <p class="text-xs text-red-500 hidden" id="card_expiry_error"></p>
                                                            </div>
                                                            
                                                            <!-- CVC -->
                                                            <div class="space-y-1">
                                                                <label class="text-xs font-bold text-slate-500 uppercase">CVC</label>
                                                                <div class="relative">
                                                                    <input type="text" 
                                                                           name="card_cvc" 
                                                                           id="card_cvc"
                                                                           placeholder="123" 
                                                                           class="w-full mt-1 p-3 pr-12 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                                                                           maxlength="4"
                                                                           oninput="validateCVC(this)"
                                                                           onblur="validateCVC(this)">
                                                                    <i class="fas fa-question-circle absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 cursor-help" title="3-4 digits on the back of your card"></i>
                                                                </div>
                                                                <p class="text-xs text-red-500 hidden" id="card_cvc_error"></p>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Cardholder Name -->
                                                        <div class="space-y-1 mt-4">
                                                            <label class="text-xs font-bold text-slate-500 uppercase">Cardholder Name</label>
                                                            <input type="text" 
                                                                   name="card_name" 
                                                                   id="card_name"
                                                                   placeholder="Name on card" 
                                                                   class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                                                                   oninput="validateCardName(this)"
                                                                   onblur="validateCardName(this)">
                                                            <p class="text-xs text-red-500 hidden" id="card_name_error"></p>
                                                        </div>
                                                        
                                                        <div class="flex items-center gap-2 mt-4 p-3 bg-green-50 rounded-xl border border-green-200">
                                                            <i class="fas fa-lock text-green-600"></i>
                                                            <span class="text-xs text-green-700">Your payment information is encrypted and secure</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Discount Code -->
                                            <div class="space-y-1">
                                                <label class="text-xs font-bold text-slate-500 uppercase">Discount Code (Optional)</label>
                                                <div class="flex gap-2">
                                                    <input type="text" 
                                                           name="discount_code" 
                                                           id="discount_code"
                                                           placeholder="Enter discount code" 
                                                           class="flex-1 mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                                                           oninput="validateDiscountCode(this)">
                                                    <button type="button" onclick="validateDiscountCodeInput()" class="px-4 py-2 bg-slate-100 text-slate-600 rounded-xl font-medium hover:bg-slate-200 transition-all">
                                                        Apply
                                                    </button>
                                                </div>
                                                <p class="text-xs text-green-600 hidden" id="discount_success"></p>
                                                <p class="text-xs text-red-500 hidden" id="discount_error"></p>
                                            </div>
                                            
                                            <div class="flex gap-4 pt-6">
                                                <a href="?step=1" class="flex-1 text-center py-4 rounded-2xl font-bold border border-slate-200 text-slate-500 hover:bg-slate-50 transition-all">Back</a>
                                                <button type="submit" id="submit-payment" class="flex-[2] bg-indigo-600 text-white py-4 rounded-2xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
                                                    <span>Complete Purchase</span>
                                                    <span class="text-sm opacity-80">$<?php echo number_format($total, 2); ?></span>
                                                </button>
                                            </div>
                                        </form>
                                    <?php elseif ($currentStep == 3): ?>
                                        <div class="text-center py-6 space-y-6">
                                            <div class="w-20 h-20 bg-green-50 text-green-500 rounded-full flex items-center justify-center mx-auto">
                                                <i class="fas fa-shield-check text-4xl"></i>
                                            </div>
                                            <div>
                                                <h3 class="text-2xl font-bold text-slate-900">Ready to complete?</h3>
                                                <p class="text-slate-500 mt-2">Please verify your items and total before finalizing payment.</p>
                                            </div>
                                            <div class="p-4 bg-slate-50 rounded-2xl border border-slate-100 text-left text-sm space-y-2">
                                                <div class="flex justify-between font-medium"><span class="text-slate-400 uppercase text-[10px]">Email</span><span><?php echo htmlspecialchars($user['email']); ?></span></div>
                                                <div class="flex justify-between font-medium"><span class="text-slate-400 uppercase text-[10px]">Currency</span><span>USD</span></div>
                                            </div>
                                            <a href="?step=2" class="text-indigo-600 font-bold text-sm block">Edit Payment Info</a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Right: Summary -->
                    <div class="lg:col-span-5">
                        <div class="bg-indigo-900 text-white rounded-3xl p-8 shadow-2xl sticky top-24">
                            <h4 class="text-lg font-bold mb-6 flex items-center gap-3">
                                <i class="fas fa-shopping-cart text-indigo-300"></i> Order Summary
                            </h4>
                            
                            <!-- Action Messages -->
                            <?php if ($actionMessage): ?>
                                <div class="mb-4 p-3 rounded-xl <?php echo ($actionMessage['success'] ?? false) ? 'bg-green-500/20 border border-green-400/30' : 'bg-red-500/20 border border-red-400/30'; ?>">
                                    <p class="text-sm <?php echo ($actionMessage['success'] ?? false) ? 'text-green-300' : 'text-red-300'; ?>">
                                        <i class="fas <?php echo ($actionMessage['success'] ?? false) ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                                        <?php echo htmlspecialchars($actionMessage['message'] ?? 'Unknown error'); ?>
                                    </p>
                                </div>
                            <?php endif; ?>
                            
                            <div class="space-y-4 max-h-[300px] overflow-y-auto pr-2 custom-scroll">
                                <?php foreach ($cartItems as $item): ?>
                                    <div class="flex items-center gap-4 p-3 bg-white/5 rounded-xl group" id="cart-item-<?php echo $item['item_id']; ?>">
                                        <img src="<?php echo $item['thumbnail'] ?: 'https://placehold.co/100x100/1E3A8A/ffffff?text=Course'; ?>" class="w-12 h-12 rounded-xl object-cover border border-white/10" />
                                        <div class="flex-1 min-w-0">
                                            <p class="text-sm font-bold truncate"><?php echo htmlspecialchars($item['title']); ?></p>
                                            <p class="text-[10px] text-indigo-300 uppercase font-bold tracking-widest"><?php echo $item['item_type']; ?></p>
                                        </div>
                                        <div class="flex flex-col items-end gap-2">
                                            <p class="font-bold text-sm">$<?php echo number_format($item['price'], 2); ?></p>
                                            <form method="POST" class="remove-item-form">
                                                <input type="hidden" name="action" value="remove_item">
                                                <input type="hidden" name="item_id" value="<?php echo $item['item_id']; ?>">
                                                <input type="hidden" name="item_type" value="<?php echo $item['item_type']; ?>">
                                                <button type="submit" class="text-xs text-indigo-300 hover:text-red-400 transition-colors flex items-center gap-1 opacity-0 group-hover:opacity-100" onclick="return confirm('Remove this item from cart?');">
                                                    <i class="fas fa-times-circle"></i> Remove
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Clear Cart Button -->
                            <?php if (!empty($cartItems)): ?>
                                <div class="mt-4 pt-4 border-t border-white/10">
                                    <form method="POST" class="clear-cart-form">
                                        <input type="hidden" name="action" value="clear_cart">
                                        <button type="submit" class="text-xs text-indigo-300 hover:text-red-400 transition-colors flex items-center gap-1" onclick="return confirm('Clear all items from cart?');">
                                            <i class="fas fa-trash-alt"></i> Clear Cart
                                        </button>
                                    </form>
                                </div>
                            <?php endif; ?>
                            
                            <div class="mt-4 pt-6 border-t border-white/10 space-y-3">
                                <div class="flex justify-between text-indigo-200 text-sm"><span>Subtotal</span><span>$<?php echo number_format($subtotal, 2); ?></span></div>
                                <div class="flex justify-between text-indigo-200 text-sm"><span>Tax (10%)</span><span>$<?php echo number_format($tax, 2); ?></span></div>
                                <div class="flex justify-between text-2xl font-bold pt-2"><span>Total</span><span class="text-green-400">$<?php echo number_format($total, 2); ?></span></div>
                            </div>
                            <div class="mt-8 flex items-center gap-3 p-4 bg-white/5 rounded-2xl border border-white/10">
                                <i class="fas fa-lock text-indigo-400"></i>
                                <p class="text-[10px] uppercase font-bold tracking-widest text-indigo-200">256-Bit SSL Encrypted Payment</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Menu Toggle
        const btn = document.getElementById('mobileMenuButton');
        const menu = document.getElementById('mobileMenu');
        const closeBtn = document.getElementById('closeMobileMenu');

        btn.onclick = () => menu.classList.remove('hidden');
        closeBtn.onclick = () => menu.classList.add('hidden');

        // Payment Method Toggle
        function selectPayment(m) {
            document.querySelectorAll('.payment-btn').forEach(b => {
                b.classList.remove('border-indigo-600', 'bg-indigo-50');
                b.classList.add('border-slate-100');
            });
            document.getElementById('btn-'+m).classList.add('border-indigo-600', 'bg-indigo-50');
            
            document.querySelectorAll('.payment-method-form').forEach(f => f.classList.add('hidden'));
            document.getElementById(m+'-form').classList.remove('hidden');
            
            // Update hidden input
            document.querySelectorAll('input[name="payment_gateway"]').forEach(input => input.value = m);
        }

        // Real-time Card Number Validation
        function validateCardNumber(input) {
            let value = input.value.replace(/\s/g, '').replace(/\D/g, '');
            let formatted = '';
            for (let i = 0; i < value.length && i < 16; i++) {
                if (i > 0 && i % 4 === 0) formatted += ' ';
                formatted += value[i];
            }
            input.value = formatted;
            
            const errorEl = document.getElementById('card_number_error');
            const luhnValid = validateLuhn(value);
            
            if (value.length > 0 && value.length < 16) {
                errorEl.textContent = 'Please enter a valid 16-digit card number';
                errorEl.classList.remove('hidden');
                input.classList.add('border-red-500');
                return false;
            } else if (value.length === 16 && !luhnValid) {
                errorEl.textContent = 'Please enter a valid card number';
                errorEl.classList.remove('hidden');
                input.classList.add('border-red-500');
                return false;
            } else {
                errorEl.classList.add('hidden');
                input.classList.remove('border-red-500');
                input.classList.add('border-slate-200');
                return true;
            }
        }

        // Luhn Algorithm for Card Validation
        function validateLuhn(number) {
            if (!/^\d+$/.test(number)) return false;
            let sum = 0;
            let isEven = false;
            for (let i = number.length - 1; i >= 0; i--) {
                let digit = parseInt(number[i], 10);
                if (isEven) {
                    digit *= 2;
                    if (digit > 9) digit -= 9;
                }
                sum += digit;
                isEven = !isEven;
            }
            return sum % 10 === 0;
        }

        // Expiry Date Validation
        function validateExpiry(input) {
            let value = input.value.replace(/\D/g, '');
            if (value.length >= 2) {
                value = value.substring(0, 2) + '/' + value.substring(2, 4);
            }
            input.value = value;
            
            const errorEl = document.getElementById('card_expiry_error');
            const [month, year] = value.split('/');
            const now = new Date();
            const currentYear = now.getFullYear() % 100;
            const currentMonth = now.getMonth() + 1;
            
            if (value.length === 5) {
                if (parseInt(month) < 1 || parseInt(month) > 12) {
                    errorEl.textContent = 'Invalid month';
                    errorEl.classList.remove('hidden');
                    input.classList.add('border-red-500');
                    return false;
                }
                if (parseInt(year) < currentYear || (parseInt(year) === currentYear && parseInt(month) < currentMonth)) {
                    errorEl.textContent = 'Card has expired';
                    errorEl.classList.remove('hidden');
                    input.classList.add('border-red-500');
                    return false;
                }
                errorEl.classList.add('hidden');
                input.classList.remove('border-red-500');
                input.classList.add('border-slate-200');
                return true;
            } else {
                errorEl.classList.add('hidden');
                return true;
            }
        }

        // CVC Validation
        function validateCVC(input) {
            let value = input.value.replace(/\D/g, '');
            input.value = value;
            
            const errorEl = document.getElementById('card_cvc_error');
            
            if (value.length > 0 && (value.length < 3 || value.length > 4)) {
                errorEl.textContent = 'CVC must be 3-4 digits';
                errorEl.classList.remove('hidden');
                input.classList.add('border-red-500');
                return false;
            } else {
                errorEl.classList.add('hidden');
                input.classList.remove('border-red-500');
                input.classList.add('border-slate-200');
                return true;
            }
        }

        // Cardholder Name Validation
        function validateCardName(input) {
            const value = input.value.trim();
            const errorEl = document.getElementById('card_name_error');
            
            if (value.length > 0 && value.length < 3) {
                errorEl.textContent = 'Name must be at least 3 characters';
                errorEl.classList.remove('hidden');
                input.classList.add('border-red-500');
                return false;
            } else if (/[^a-zA-Z\s]/.test(value)) {
                errorEl.textContent = 'Name can only contain letters and spaces';
                errorEl.classList.remove('hidden');
                input.classList.add('border-red-500');
                return false;
            } else {
                errorEl.classList.add('hidden');
                input.classList.remove('border-red-500');
                input.classList.add('border-slate-200');
                return true;
            }
        }

        // Discount Code Validation
        function validateDiscountCode(input) {
            const value = input.value.trim().toUpperCase();
            input.value = value;
        }

        async function validateDiscountCodeInput() {
            const input = document.getElementById('discount_code');
            const successEl = document.getElementById('discount_success');
            const errorEl = document.getElementById('discount_error');
            
            successEl.classList.add('hidden');
            errorEl.classList.add('hidden');
            
            if (!input.value.trim()) {
                return;
            }
            
            try {
                const response = await fetch('../api/discounts.php?code=' + encodeURIComponent(input.value));
                const data = await response.json();
                
                if (data.valid) {
                    successEl.textContent = data.message || 'Discount applied!';
                    successEl.classList.remove('hidden');
                } else {
                    errorEl.textContent = data.message || 'Invalid discount code';
                    errorEl.classList.remove('hidden');
                }
            } catch (e) {
                errorEl.textContent = 'Unable to validate discount code';
                errorEl.classList.remove('hidden');
            }
        }

        // Form Submission with Loading State
        document.getElementById('payment-form')?.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('submit-payment');
            const gateway = document.querySelector('input[name="payment_gateway"]').value;
            
            // Validate card fields if card payment
            if (gateway === 'card') {
                const cardValid = validateCardNumber(document.getElementById('card_number'));
                const expiryValid = validateExpiry(document.getElementById('card_expiry'));
                const cvcValid = validateCVC(document.getElementById('card_cvc'));
                const nameValid = validateCardName(document.getElementById('card_name'));
                
                if (!cardValid || !expiryValid || !cvcValid || !nameValid) {
                    return;
                }
            }
            
            // Show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            
            // Submit the form
            this.submit();
        });

        // Auto-format card number on paste
        document.getElementById('card_number')?.addEventListener('paste', function(e) {
            e.preventDefault();
            const pastedData = e.clipboardData.getData('text');
            const cleaned = pastedData.replace(/\D/g, '').substring(0, 16);
            this.value = cleaned;
            validateCardNumber(this);
        });

        // Format expiry on paste
        document.getElementById('card_expiry')?.addEventListener('paste', function(e) {
            e.preventDefault();
            const pastedData = e.clipboardData.getData('text').replace(/\D/g, '').substring(0, 4);
            if (pastedData.length >= 2) {
                this.value = pastedData.substring(0, 2) + '/' + pastedData.substring(2, 4);
            } else {
                this.value = pastedData;
            }
            validateExpiry(this);
        });
        
        // Remove item via AJAX
        async function removeItem(itemId, itemType) {
            if (!confirm('Remove this item from cart?')) return;
            
            const formData = new FormData();
            formData.append('action', 'remove_item');
            formData.append('item_id', itemId);
            formData.append('item_type', itemType);
            
            try {
                const response = await fetch('checkout.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Remove item from UI with animation
                    const itemElement = document.getElementById('cart-item-' + itemId);
                    if (itemElement) {
                        itemElement.style.transition = 'all 0.3s ease';
                        itemElement.style.opacity = '0';
                        itemElement.style.transform = 'translateX(20px)';
                        setTimeout(() => {
                            itemElement.remove();
                            // Refresh page after short delay to update totals
                            setTimeout(() => location.reload(), 300);
                        }, 300);
                    }
                } else {
                    alert('Error: ' + (result.message || 'Failed to remove item'));
                }
            } catch (e) {
                console.error('Remove item error:', e);
                alert('An error occurred while removing the item');
            }
        }
        
        // Clear cart via AJAX
        async function clearCart() {
            if (!confirm('Clear all items from cart?')) return;
            
            const formData = new FormData();
            formData.append('action', 'clear_cart');
            
            try {
                const response = await fetch('checkout.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Reload page to update cart
                    location.reload();
                } else {
                    alert('Error: ' + (result.message || 'Failed to clear cart'));
                }
            } catch (e) {
                console.error('Clear cart error:', e);
                alert('An error occurred while clearing the cart');
            }
        }
        
        // Add item to cart via AJAX (for adding back items or from catalog)
        async function addToCart(itemId, itemType = 'course') {
            const formData = new FormData();
            formData.append('action', 'add_item');
            formData.append('item_id', itemId);
            formData.append('item_type', itemType);
            
            try {
                const response = await fetch('checkout.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Show success message
                    if (!result.already_in_cart) {
                        // Reload page to update cart
                        location.reload();
                    } else {
                        alert(result.message);
                    }
                } else {
                    alert('Error: ' + (result.message || 'Failed to add item'));
                }
            } catch (e) {
                console.error('Add to cart error:', e);
                alert('An error occurred while adding the item');
            }
        }
    </script>

</body>
</html>
