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

$db = getDB();

// Get user ID if logged in
$userId = $_SESSION['user_id'] ?? null;
$user = getUserContext();

// Get cart contents
$cartResponse = json_decode(file_get_contents('http://localhost/lms/api/cart.php'), true);
$cart = $cartResponse['cart'] ?? ['items' => [], 'total' => 0.00, 'currency' => 'USD'];

$page_title = 'Shopping Cart';
?>

<!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($page_title ?? 'Shopping Cart'); ?> | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Main Application Container -->
<div id="app" class="flex">

    <!-- Sidebar Navigation (Desktop View) -->
    <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
        <div class="flex flex-col h-full">
            <!-- Logo/Title -->
            <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
            </div>

            <!-- Navigation Links -->
            <nav class="space-y-2 flex-grow">
                <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Home -->
                    <span class="w-5 h-5">🏠</span>
                    <span>Dashboard</span>
                </a>
                <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Catalog -->
                    <span class="w-5 h-5">📖</span>
                    <span>View All Courses</span>
                </a>
                <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Book -->
                    <span class="w-5 h-5">📚</span>
                    <span>My Courses</span>
                </a>
                <a href="exams.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Exam -->
                    <span class="w-5 h-5">📝</span>
                    <span>My Exam</span>
                </a>
                <a href="../exams/catalog.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: All Exams -->
                    <span class="w-5 h-5">📋</span>
                    <span>All Exam</span>
                </a>
                <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Checkmark -->
                    <span class="w-5 h-5">✅</span>
                    <span>Grades & Reports</span>
                </a>
                <a href="calendar.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Calendar -->
                    <span class="w-5 h-5">📅</span>
                    <span>Calendar</span>
                </a>
                <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Globe -->
                    <span class="w-5 h-5">🌐</span>
                    <span>View Site</span>
                </a>
                <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <!-- Icon Placeholder: Logout -->
                    <span class="w-5 h-5">🚪</span>
                    <span>Logout</span>
                </a>
            </nav>

            <!-- Footer/User Info (Bottom of Sidebar) -->
            <div class="mt-8 pt-4 border-t border-accent-subtle">
                <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
            </div>
        </div>
    </aside>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Mutalex Academy Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue">Mutalex Academy</h1>
                    <p class="text-sm text-gray-600">Shopping Cart</p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <!-- Cart Button -->
                <button onclick="showDashboardCheckoutModal()" class="text-gray-600 hover:text-primary-blue p-2 rounded-full relative transition duration-150">
                    <!-- Shopping Cart Icon -->
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-cart">
                        <circle cx="8" cy="21" r="1"/>
                        <circle cx="19" cy="21" r="1"/>
                        <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.15"/>
                    </svg>
                    <span id="dashboard-cart-count" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center hidden">0</span>
                </button>

                <!-- User Profile -->
                <div class="flex items-center space-x-2">
                    <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                    <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="User Avatar">
                    <!-- Mobile Menu Button (Hamburger) -->
                    <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                        <span class="text-xl">☰</span>
                    </button>
                </div>
            </div>
        </div>
    </header>

        <!-- Mobile Navigation Overlay (Hidden by default) -->
        <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
            <div class="flex justify-between items-center mb-10">
                <div class="text-xl font-extrabold text-primary-blue tracking-wider"></div>
                <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
            </div>
            <nav class="space-y-4">
                <!-- Links repeated from sidebar -->
                <a href="dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                <a href="available_courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 View All Courses</a>
                <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle"> My Courses</a>
                <a href="exams.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 My Exam</a>
                <a href="../exams/catalog.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📋 All Exam
                <a href="reports.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">✅ Grades & Reports</a>
                <a href="calendar.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</a>
                <a href="../index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🌐 View Site</a>
                <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
            </nav>
        </div>

<div class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">
                        <i class="fas fa-shopping-cart me-2"></i>
                        Shopping Cart
                    </h4>
                </div>
                <div class="card-body">
                    <?php if (empty($cart['items'])): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">Your cart is empty</h5>
                            <p class="text-muted">Add some courses to get started!</p>
                            <a href="courses/catalog.php" class="btn btn-primary">
                                <i class="fas fa-arrow-left me-2"></i>Browse Courses
                            </a>
                        </div>
                    <?php else: ?>
                        <!-- Cart Items -->
                        <div class="mb-4">
                            <h5 class="mb-3">Order Summary</h5>
                            <div class="cart-items">
                                <?php foreach ($cart['items'] as $item): ?>
                                    <div class="cart-item d-flex align-items-center justify-content-between p-3 border rounded mb-2">
                                        <div class="d-flex align-items-center">
                                            <?php if ($item['thumbnail']): ?>
                                                <img src="<?php echo htmlspecialchars($item['thumbnail']); ?>" alt="" class="cart-item-image me-3" style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;">
                                            <?php endif; ?>
                                            <div>
                                                <h6 class="mb-1"><?php echo htmlspecialchars($item['title']); ?></h6>
                                                <small class="text-muted">
                                                    <?php if ($item['is_free']): ?>
                                                        <span class="badge bg-success">Free</span>
                                                    <?php else: ?>
                                                        <span class="text-primary fw-bold"><?php echo formatCurrency($item['price'], $item['currency']); ?></span>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        </div>
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(<?php echo $item['item_id']; ?>)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Cart Summary -->
                        <div class="cart-summary bg-light p-4 rounded mb-4">
                            <h6 class="mb-3">Order Total</h6>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="fw-bold">Total Amount:</span>
                                <span class="h4 text-primary mb-0">
                                    <?php echo formatCurrency($cart['total'], $cart['currency']); ?>
                                </span>
                            </div>
                            <?php if ($cart['total'] > 0): ?>
                                <div class="mt-3 text-muted small">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Secure payment processing powered by Paynow and PayPal
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-flex justify-content-between align-items-center">
                            <a href="courses/catalog.php" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Continue Shopping
                            </a>
                            <?php if (!$userId): ?>
                                <a href="login.php?redirect=student/dashboard.php" class="btn btn-primary btn-lg">
                                    <i class="fas fa-sign-in-alt me-2"></i>
                                    Login to Checkout
                                </a>
                            <?php else: ?>
                                <a href="student/dashboard.php" class="btn btn-primary btn-lg">
                                    <i class="fas fa-credit-card me-2"></i>
                                    Proceed to Checkout
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Initialize cart on page load
document.addEventListener('DOMContentLoaded', function() {
    loadCartContent();
});

// Load cart content
function loadCartContent() {
    fetch('../api/cart.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update cart count badge
            const cartBadge = document.getElementById('dashboard-cart-count');
            if (cartBadge) {
                const count = data.cart.item_count || 0;
                cartBadge.textContent = count;
                cartBadge.classList.toggle('hidden', count === 0);
            }

            if (data.cart.items.length > 0) {
                // Cart has items, checkout modal can be shown when needed
                console.log('Cart loaded:', data.cart);
            }
        }
    })
    .catch(error => console.error('Error loading cart:', error));
}

// Show checkout modal from dashboard
function showDashboardCheckoutModal() {
    // Create modal HTML
    const modalHtml = `
        <div id="dashboard-checkout-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold text-gray-900">Complete Checkout</h2>
                        <button onclick="closeDashboardCheckoutModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>

                    <div id="checkout-content">
                        <!-- Content will be loaded here -->
                        <div class="text-center py-8">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue mx-auto mb-4"></div>
                            <p class="text-gray-600">Loading checkout...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // Add event listeners for closing modal
    const modal = document.getElementById('dashboard-checkout-modal');

    // Close modal when clicking outside
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeDashboardCheckoutModal();
        }
    });

    // Close modal when pressing ESC key
    const handleEscapeKey = function(e) {
        if (e.key === 'Escape') {
            closeDashboardCheckoutModal();
        }
    };
    document.addEventListener('keydown', handleEscapeKey);

    // Store the escape handler to remove it later
    modal._escapeHandler = handleEscapeKey;

    loadCheckoutContent();
}

// Close checkout modal
function closeDashboardCheckoutModal() {
    const modal = document.getElementById('dashboard-checkout-modal');
    if (modal) {
        // Remove escape key event listener
        if (modal._escapeHandler) {
            document.removeEventListener('keydown', modal._escapeHandler);
        }
        modal.remove();
    }
}

// Load checkout content
function loadCheckoutContent() {
    fetch('../api/cart.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const cart = data.cart;
            renderCheckoutContent(cart);
        } else {
            document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading cart</p></div>';
        }
    })
    .catch(error => {
        console.error('Error loading checkout:', error);
        document.getElementById('checkout-content').innerHTML = '<div class="text-center py-8"><p class="text-red-600">Error loading checkout</p></div>';
    });
}
</script>

</body>
</html>

// Render checkout content
function renderCheckoutContent(cart) {
    if (!cart.items || cart.items.length === 0) {
        document.getElementById('checkout-content').innerHTML = `
            <div class="text-center py-8">
                <i class="fas fa-shopping-cart fa-3x text-gray-300 mb-4"></i>
                <h5 class="text-gray-600 mb-2">Your cart is empty</h5>
                <p class="text-sm text-gray-500 mb-6">Add some courses to get started with your learning journey</p>
                <div class="flex flex-col sm:flex-row gap-3 justify-center">
                    <button onclick="closeDashboardCheckoutModal(); toggleAvailableCourses();" class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-indigo-700 font-medium">
                        <i class="fas fa-graduation-cap mr-2"></i>Browse Courses
                    </button>
                    <a href="../courses/catalog.php" class="bg-white text-primary border border-primary px-6 py-2 rounded-lg hover:bg-blue-50 font-medium">
                        <i class="fas fa-external-link-alt mr-2"></i>View Full Catalog
                    </a>
                </div>
            </div>
        `;
        return;
    }

    let itemsHtml = '';
    cart.items.forEach(item => {
        itemsHtml += `
            <div class="bg-gray-50 rounded-lg p-4 mb-3 border border-gray-200">
                <div class="flex items-start justify-between">
                    <div class="flex items-start space-x-3 flex-1">
                        <div class="flex-1">
                            <h4 class="text-sm font-medium text-gray-800">${item.title}</h4>
                            <p class="text-xs text-gray-500">${item.is_free ? 'Free' : formatCurrency(item.price, item.currency)}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });

    const checkoutHtml = `
        <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="font-medium text-gray-800">Cart Items (${cart.items.length})</h3>
                <div class="flex items-center space-x-3">
                    <button onclick="closeDashboardCheckoutModal(); toggleAvailableCourses();" class="text-sm text-blue-600 hover:text-blue-800 font-medium flex items-center">
                        <i class="fas fa-plus mr-1"></i>Add More Courses
                    </button>
                    <button onclick="clearCart()" class="text-xs text-gray-500 hover:text-red-600 font-medium flex items-center ml-4 px-2 py-1 border border-gray-300 rounded">
                        <i class="fas fa-trash mr-1"></i>Clear All
                    </button>
                </div>
            </div>
            ${itemsHtml}
        </div>

        <div class="bg-gray-50 p-4 rounded-lg mb-6">
            <div class="flex justify-between items-center">
                <span class="font-medium text-gray-700">Total Amount:</span>
                <span class="text-2xl font-bold text-primary">${formatCurrency(cart.total, cart.currency)}</span>
            </div>
        </div>

        <div class="text-center space-y-3">
            <button onclick="processFreeEnrollment()" class="w-full bg-green-600 text-white py-3 px-4 rounded-lg font-semibold hover:bg-green-700 transition duration-200">
                <i class="fas fa-graduation-cap mr-2"></i>Enroll Now
            </button>
        </div>
    `;

    document.getElementById('checkout-content').innerHTML = checkoutHtml;
}

// Format currency for JavaScript
function formatCurrency(amount, currency = 'USD') {
    const formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currency,
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
    return formatter.format(amount);
}

// Clear entire cart
function clearCart() {
    if (confirm('Are you sure you want to clear your entire cart?')) {
        fetch('../api/cart.php', {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('Cart cleared successfully', 'success');
                loadCheckoutContent(); // Reload the checkout modal
                loadCartContent(); // Update cart count badge
            } else {
                showToast('Error clearing cart: ' + data.error, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred. Please try again.', 'error');
        });
    }
}

// Process free enrollment from dashboard
function processFreeEnrollment() {
    fetch('../api/cart.php', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Successfully enrolled in courses!', 'success');
            closeDashboardCheckoutModal();
            loadCartContent(); // Reload cart count
            setTimeout(() => {
                location.reload(); // Reload page to show enrolled courses
            }, 1500);
        } else {
            showToast('Error: ' + (data.error || 'Enrollment failed'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred. Please try again.', 'error');
    });
}

function removeFromCart(courseId) {
    if (confirm('Remove this course from cart?')) {
        fetch('../api/cart.php?course_id=' + courseId, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        });
    }
}

// Toast notification system
function showToast(message, type = 'success') {
    // Remove existing toasts
    const existingToasts = document.querySelectorAll('.toast-notification');
    existingToasts.forEach(toast => toast.remove());

    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast-notification fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform translate-x-full transition-all duration-300 ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    toast.innerHTML = `
        <div class="flex items-center gap-3">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'}"></i>
            <span>${message}</span>
        </div>
    `;

    // Add to page
    document.body.appendChild(toast);

    // Animate in
    setTimeout(() => {
        toast.classList.remove('translate-x-full');
    }, 100);

    // Auto remove after 4 seconds
    setTimeout(() => {
        toast.classList.add('translate-x-full');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 4000);
}
</script>

<style>
.cart-item-image {
    border-radius: 4px;
}

.cart-summary {
    border: 1px solid #dee2e6;
}
</style>

    </main>
</div>

// Mobile Menu Functionality
const mobileMenuButton = document.getElementById('mobileMenuButton');
const closeMobileMenu = document.getElementById('closeMobileMenu');
const mobileMenu = document.getElementById('mobileMenu');

if (mobileMenuButton && closeMobileMenu && mobileMenu) {
    mobileMenuButton.addEventListener('click', () => {
        mobileMenu.classList.remove('-translate-x-full');
    });

    closeMobileMenu.addEventListener('click', () => {
        mobileMenu.classList.add('-translate-x-full');
    });

    // Close menu when a link is clicked
    mobileMenu.querySelectorAll('a').forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });
    });
}
