<?php
require_once __DIR__ . '/functions.php';

$base_url = defined('BASE_URL') ? BASE_URL : '/';
$siteName = getSiteSetting('site_name') ?: 'Mutalex Academy';
$currentYear = date('Y');
?>
</main>

    <!-- Footer Section -->
    <footer class="footer">
        <?php if (!isset($use_tailwind) || !$use_tailwind): ?>
        <div class="container">
        <?php endif; ?>
            <div class="footer-content <?php if (isset($use_tailwind) && $use_tailwind): ?>footer-fullwidth<?php endif; ?>">
                <div class="footer-section">
                    <h3><?php echo htmlspecialchars($siteName); ?></h3>
                    <p>Your source for news, articles, and journals.</p>
                </div>
                <div class="footer-section">
                    <h4>Categories</h4>
                    <ul class="footer-links">
                        <li><a href="<?php echo BASE_URL; ?>courses/catalog.php">Courses</a></li>
                        <li><a href="<?php echo BASE_URL; ?>category?cat=news">News</a></li>
                        <li><a href="<?php echo BASE_URL; ?>category?cat=articles">Articles</a></li>
                        <li><a href="<?php echo BASE_URL; ?>category?cat=journals">Journals</a></li>
                        <li><a href="<?php echo BASE_URL; ?>survey.php">Survey</a></li>
                        <li><a href="<?php echo BASE_URL; ?>login.php">Login</a></li>
                    </ul>
                </div>
                <div class="footer-section">
                    <h4>Connect</h4>
                    <div class="social-links">
                        <a href="#"><i class="fab fa-twitter"></i></a>
                        <a href="#"><i class="fab fa-facebook"></i></a>
                        <a href="#"><i class="fab fa-linkedin"></i></a>
                    </div>
                </div>
            </div>
            <div class="footer-bottom">
                <p>&copy; <?php echo $currentYear; ?> <?php echo htmlspecialchars($siteName); ?>. All rights reserved.</p>
            </div>
        <?php if (!isset($use_tailwind) || !$use_tailwind): ?>
        </div>
        <?php endif; ?>
    </footer>

    <!-- Cart Modal -->
    <div class="modal fade" id="cartModal" tabindex="-1" aria-labelledby="cartModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cartModalLabel">
                        <i class="fas fa-shopping-cart me-2"></i>Shopping Cart
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="cartModalBody">
                    <!-- Cart content will be loaded here -->
                    <div class="text-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Continue Shopping</button>
                    <a href="<?php echo BASE_URL; ?>student/checkout.php" class="btn btn-primary" id="checkoutBtn" style="display: none;">Proceed to Checkout</a>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/js/main.js"></script>
    <script>
    // Cart Modal Functionality
    document.addEventListener('DOMContentLoaded', function() {
        const cartModal = document.getElementById('cartModal');
        const cartModalBody = document.getElementById('cartModalBody');
        const checkoutBtn = document.getElementById('checkoutBtn');

        // Format currency function
        function formatCurrency(amount, currency = 'USD') {
            if (amount == 0) return 'Free';
            return new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: currency
            }).format(amount);
        }

        cartModal.addEventListener('show.bs.modal', function() {
            loadCart();
        });

        function loadCart() {
            fetch('<?php echo BASE_URL; ?>api/cart.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        renderCart(data.cart);
                    } else {
                        cartModalBody.innerHTML = '<div class="alert alert-danger">Error loading cart</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    cartModalBody.innerHTML = '<div class="alert alert-danger">Error loading cart</div>';
                });
        }

        function renderCart(cart) {
            if (!cart || cart.items.length === 0) {
                cartModalBody.innerHTML = `
                    <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="<?php echo BASE_URL; ?>courses/catalog.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left me-2"></i>Browse Courses
                        </a>
                    </div>
                `;
                checkoutBtn.style.display = 'none';
                return;
            }

            let html = `
                <div class="mb-4">
                    <h5 class="mb-3">Order Summary</h5>
                    <div class="cart-items">
            `;

            cart.items.forEach(item => {
                html += `
                    <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">
                            ${item.thumbnail ? `<img src="${item.thumbnail}" alt="" class="cart-item-image me-3" style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;">` : ''}
                            <div>
                                <h6 class="mb-1">${item.title}</h6>
                                <small class="text-muted">
                                    ${item.is_free ? '<span class="badge bg-success">Free</span>' : `<span class="text-primary fw-bold">${formatCurrency(item.price, item.currency)}</span>`}
                                </small>
                            </div>
                        </div>
                        <button class="btn btn-sm btn-outline-danger" onclick="removeFromCart('${item.item_id}', '${item.item_type}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
            });

            html += `
                    </div>
                </div>
                <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">${formatCurrency(cart.total, cart.currency)}</span>
                    </div>
                    ${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>' : ''}
                </div>
            `;

            cartModalBody.innerHTML = html;
            checkoutBtn.style.display = cart.total > 0 ? 'inline-block' : 'none';
        }

        window.removeFromCart = function(itemId, itemType) {
            if (confirm('Remove this item from cart?')) {
                fetch('<?php echo BASE_URL; ?>api/cart.php?item_id=' + itemId + '&item_type=' + itemType, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        loadCart(); // Reload cart
                        updateCartCount(); // Update cart count in header
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred. Please try again.');
                });
            }
        };

        function updateCartCount() {
            fetch('<?php echo BASE_URL; ?>api/cart.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.cart) {
                        const cartCount = data.cart.item_count || 0;
                        const cartCountElement = document.querySelector('.cart-count');
                        if (cartCountElement) {
                            if (cartCount > 0) {
                                cartCountElement.textContent = cartCount;
                                cartCountElement.style.display = 'inline-flex';
                            } else {
                                cartCountElement.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(error => console.error('Error updating cart count:', error));
        }
    });
    </script>
</body>
</html>