<?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;

// 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';
include 'includes/header.php';
?>

<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>
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.');
        });
    }
}
</script>

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

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

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