<?php
/**
 * Shopping Cart Page - PREMIUM VERSION
 * Digital Marketplace
 */

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

$page_title = 'Shopping Cart';

// Handle cart updates
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update quantities
    if (isset($_POST['update_cart'])) {
        if (isset($_POST['quantities']) && is_array($_POST['quantities'])) {
            foreach ($_POST['quantities'] as $cart_id => $quantity) {
                update_cart_quantity($cart_id, max(1, (int)$quantity));
            }
        }
        set_flash_message('Cart updated successfully!', 'success');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    // Remove item
    if (isset($_POST['remove_item'])) {
        $cart_id = (int)$_POST['remove_item'];
        remove_from_cart($cart_id);
        set_flash_message('Item removed from cart.', 'success');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    // Clear cart
    if (isset($_POST['clear_cart'])) {
        clear_cart();
        set_flash_message('Cart cleared.', 'success');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    // Apply coupon
    if (isset($_POST['apply_coupon'])) {
        $coupon_code = sanitize($_POST['coupon_code'] ?? '');
        $coupon = get_coupon_by_code($coupon_code);
        
        if ($coupon) {
            $_SESSION['applied_coupon'] = $coupon_code;
            set_flash_message('Coupon applied successfully!', 'success');
        } else {
            unset($_SESSION['applied_coupon']);
            set_flash_message('Invalid or expired coupon code.', 'error');
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

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

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

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

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

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

<section class="section">
    <div class="container">
        <h1 class="mb-4" data-aos="fade-up">
            <i class="fas fa-shopping-cart me-2"></i>Shopping Cart
        </h1>
        
        <?php if (empty($cart_items)): ?>
            <!-- Empty Cart -->
            <div class="card" data-aos="fade-up">
                <div class="card-body text-center py-5">
                    <i class="fas fa-shopping-cart fa-4x text-muted mb-4"></i>
                    <h3>Your cart is empty</h3>
                    <p class="text-muted mb-4">Looks like you haven't added any products yet.</p>
                    <a href="<?php echo BASE_URL; ?>/products.php" class="btn btn-primary btn-lg">
                        <i class="fas fa-shopping-bag me-2"></i>Continue Shopping
                    </a>
                </div>
            </div>
        <?php else: ?>
            <form method="POST" data-aos="fade-up">
                <div class="row g-4">
                    <!-- Cart Items -->
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-box me-2"></i><?php echo $cart_count; ?> Item(s)</span>
                                <button type="submit" name="clear_cart" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to clear your cart?')">
                                    <i class="fas fa-trash me-1"></i>Clear Cart
                                </button>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th class="text-center">Price</th>
                                                <th class="text-center" style="width: 120px;">Quantity</th>
                                                <th class="text-end">Total</th>
                                                <th></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($cart_items as $item): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <img src="<?php echo get_product_image_url($item); ?>" 
                                                             alt="<?php echo sanitize($item['name']); ?>"
                                                             class="rounded me-3"
                                                             style="width: 60px; height: 60px; object-fit: cover;"
                                                             onerror="this.src='<?php echo ASSETS_URL; ?>/images/no-image.jpg'">
                                                        <div>
                                                            <h6 class="mb-1">
                                                                <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $item['slug']; ?>">
                                                                    <?php echo sanitize($item['name']); ?>
                                                                </a>
                                                            </h6>
                                                            <?php if ($item['license_type']): ?>
                                                            <small class="text-muted">
                                                                <span class="badge bg-secondary"><?php echo ucfirst($item['license_type']); ?></span>
                                                            </small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-center"><?php echo format_price($item['price']); ?></td>
                                                <td>
                                                    <input type="number" name="quantities[<?php echo $item['id']; ?>]" 
                                                           class="form-control text-center" 
                                                           value="<?php echo $item['quantity']; ?>" 
                                                           min="1" max="99">
                                                </td>
                                                <td class="text-end">
                                                    <strong><?php echo format_price($item['price'] * $item['quantity']); ?></strong>
                                                </td>
                                                <td class="text-end">
                                                    <button type="submit" name="remove_item" value="<?php echo $item['id']; ?>" 
                                                            class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Remove this item?')">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="card-footer">
                                <div class="d-flex justify-content-between align-items-center">
                                    <a href="<?php echo BASE_URL; ?>/products.php" class="btn btn-outline-light">
                                        <i class="fas fa-arrow-left me-2"></i>Continue Shopping
                                    </a>
                                    <button type="submit" name="update_cart" class="btn btn-primary">
                                        <i class="fas fa-sync-alt me-2"></i>Update Cart
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Coupon Code -->
                        <div class="card mt-4">
                            <div class="card-header">
                                <i class="fas fa-tag me-2"></i>Coupon Code
                            </div>
                            <div class="card-body">
                                <div class="input-group">
                                    <input type="text" name="coupon_code" class="form-control" 
                                           placeholder="Enter coupon code" 
                                           value="<?php echo $coupon_code ?? ''; ?>">
                                    <button type="submit" name="apply_coupon" class="btn btn-primary">
                                        <i class="fas fa-check me-2"></i>Apply
                                    </button>
                                </div>
                                <?php if ($coupon): ?>
                                <small class="text-success">
                                    <i class="fas fa-check-circle me-1"></i>
                                    Coupon applied: <?php echo $coupon['discount_value']; ?><?php echo $coupon['discount_type'] === 'percentage' ? '%' : CURRENCY_SYMBOL; ?> off
                                </small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Order Summary -->
                    <div class="col-lg-4">
                        <div class="card order-summary" data-aos="fade-left">
                            <div class="card-header">
                                <i class="fas fa-receipt me-2"></i>Order Summary
                            </div>
                            <div class="card-body">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Subtotal</span>
                                    <span><?php echo format_price($subtotal); ?></span>
                                </div>
                                
                                <?php if ($tax > 0): ?>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Tax (<?php echo $tax_rate; ?>%)</span>
                                    <span><?php echo format_price($tax); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($discount > 0): ?>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-success">Discount</span>
                                    <span class="text-success">-<?php echo format_price($discount); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <hr class="border-secondary">
                                
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <span class="h5 mb-0">Total</span>
                                    <span class="h3 mb-0 text-primary"><?php echo format_price($total); ?></span>
                                </div>
                                
                                <a href="<?php echo BASE_URL; ?>/checkout.php" class="btn btn-primary btn-lg w-100">
                                    <i class="fas fa-lock me-2"></i>Proceed to Checkout
                                </a>
                            </div>
                        </div>
                        
                        <!-- Secure Checkout -->
                        <div class="card mt-4 bg-transparent border-0">
                            <div class="card-body text-center">
                                <i class="fas fa-shield-alt fa-2x text-success mb-2"></i>
                                <p class="text-muted mb-0">
                                    <small>Secure checkout with SSL encryption</small>
                                </p>
                                <div class="mt-3">
                                    <i class="fab fa-cc-visa fa-2x me-2 text-muted"></i>
                                    <i class="fab fa-cc-mastercard fa-2x me-2 text-muted"></i>
                                    <i class="fab fa-cc-paypal fa-2x me-2 text-muted"></i>
                                    <i class="fab fa-cc-stripe fa-2x text-muted"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        <?php endif; ?>
    </div>
</section>

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

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