<?php
// cart.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';

// Get cart items
$cart_items = getCartItems();
$subtotal = getCartTotal();
$shipping_charge = floatval(getSetting($pdo, 'shipping_charge') ?: 70);
$discount = 0;
$total = $subtotal + $shipping_charge - $discount;

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

<style>
.cart-page { padding: 30px 0; }
.cart-page .page-title { font-size: 24px; font-weight: 700; color: #1e293b; margin-bottom: 25px; }
.cart-page .page-title span { color: #047dc3; }

.cart-table-wrap { background: #fff; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); overflow: hidden; padding: 20px; }
.cart-table { width: 100%; border-collapse: collapse; }
.cart-table thead { background: #f8fafc; border-bottom: 2px solid #e2e8f0; }
.cart-table thead th { padding: 14px 16px; text-align: left; font-weight: 600; font-size: 14px; color: #475569; text-transform: uppercase; letter-spacing: 0.5px; }
.cart-table tbody td { padding: 16px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
.cart-table tbody tr:last-child td { border-bottom: none; }

.cart-product { display: flex; align-items: center; gap: 15px; }
.cart-product img { width: 70px; height: 70px; object-fit: cover; border-radius: 8px; border: 1px solid #e2e8f0; flex-shrink: 0; }
.cart-product .product-info { flex: 1; }
.cart-product .product-info .product-name { font-size: 15px; font-weight: 600; color: #1e293b; transition: all 0.3s ease; }
.cart-product .product-info .product-name:hover { color: #047dc3; }
.cart-product .product-info .product-variant { font-size: 13px; color: #94a3b8; margin-top: 2px; }

.qty-control { display: flex; align-items: center; border: 2px solid #e2e8f0; border-radius: 8px; overflow: hidden; width: fit-content; background: #fff; }
.qty-control .qty-btn { width: 34px; height: 34px; border: none; background: transparent; font-size: 16px; cursor: pointer; transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; color: #64748b; }
.qty-control .qty-btn:hover { background: #047dc3; color: #fff; }
.qty-control .qty-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.qty-control .qty-input { width: 45px; height: 34px; border: none; text-align: center; font-size: 15px; font-weight: 600; color: #1e293b; background: #f8fafc; }

.price-current { font-size: 16px; font-weight: 600; color: #1e293b; }
.price-total { font-size: 16px; font-weight: 700; color: #047dc3; }

.btn-remove { background: none; border: none; color: #ef4444; font-size: 18px; cursor: pointer; transition: all 0.3s ease; padding: 5px 10px; border-radius: 6px; }
.btn-remove:hover { color: #dc2626; background: #fef2f2; }

.cart-summary { background: #fff; border-radius: 12px; padding: 25px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); position: sticky; top: 20px; }
.cart-summary .summary-title { font-size: 18px; font-weight: 700; color: #1e293b; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 2px solid #e2e8f0; }
.cart-summary .summary-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f1f5f9; font-size: 15px; }
.cart-summary .summary-row:last-child { border-bottom: none; }
.cart-summary .summary-row .label { color: #64748b; }
.cart-summary .summary-row .value { font-weight: 600; color: #1e293b; }
.cart-summary .summary-row.total { border-top: 2px solid #e2e8f0; padding-top: 15px; margin-top: 5px; font-size: 18px; }
.cart-summary .summary-row.total .label { font-weight: 700; color: #1e293b; }
.cart-summary .summary-row.total .value { font-weight: 700; color: #047dc3; }

.btn-checkout { display: block; width: 100%; padding: 14px; background: #047dc3; color: #fff; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; text-align: center; transition: all 0.3s ease; text-decoration: none; margin-top: 15px; }
.btn-checkout:hover { background: #0369a1; color: #fff; }
.btn-shop { display: inline-block; padding: 12px 30px; background: transparent; color: #047dc3; border: 2px solid #047dc3; border-radius: 8px; font-size: 15px; font-weight: 600; text-align: center; transition: all 0.3s ease; text-decoration: none; margin-top: 10px; }
.btn-shop:hover { background: #047dc3; color: #fff; }

.empty-cart { text-align: center; padding: 60px 20px; }
.empty-cart .empty-icon { font-size: 80px; color: #e2e8f0; margin-bottom: 20px; }
.empty-cart h3 { font-size: 24px; font-weight: 700; color: #1e293b; margin-bottom: 10px; }
.empty-cart p { color: #94a3b8; font-size: 16px; margin-bottom: 25px; }

.coupon-section { margin-top: 15px; padding-top: 15px; border-top: 1px solid #e2e8f0; }
.coupon-section .coupon-input-group { display: flex; gap: 10px; }
.coupon-section .coupon-input-group input { flex: 1; padding: 10px 15px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 14px; transition: all 0.3s ease; }
.coupon-section .coupon-input-group input:focus { border-color: #047dc3; outline: none; box-shadow: 0 0 0 3px rgba(4,125,195,0.1); }
.coupon-section .btn-apply { padding: 10px 25px; background: #047dc3; color: #fff; border: none; border-radius: 8px; font-weight: 500; cursor: pointer; transition: all 0.3s ease; white-space: nowrap; }
.coupon-section .btn-apply:hover { background: #0369a1; }

.toast-message { position: fixed; top: 20px; right: 20px; padding: 12px 24px; border-radius: 8px; color: #fff; z-index: 9999; font-size: 14px; animation: slideIn 0.3s ease; max-width: 400px; box-shadow: 0 5px 20px rgba(0,0,0,0.15); }
.toast-message.success { background: #22c55e; }
.toast-message.error { background: #ef4444; }
.toast-message.warning { background: #f59e0b; }

@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }

@media (max-width: 991px) { .cart-summary { position: static; margin-top: 20px; } }
@media (max-width: 768px) { 
    .cart-table-wrap { padding: 12px; }
    .cart-table thead { display: none; }
    .cart-table tbody td { display: block; padding: 10px 12px; border-bottom: none; text-align: center; }
    .cart-table tbody tr { display: block; border-bottom: 2px solid #e2e8f0; padding: 10px 0; }
    .cart-table tbody tr:last-child { border-bottom: none; }
    .cart-product { flex-direction: column; align-items: center; }
    .cart-product img { width: 100px; height: 100px; margin: 0 auto; }
    .cart-product .product-info { width: 100%; text-align: center; }
    .qty-control { margin: 0 auto; }
    .btn-remove { display: block; margin: 0 auto; }
    .cart-summary { padding: 20px; }
    .coupon-section .coupon-input-group { flex-direction: column; }
    .coupon-section .btn-apply { width: 100%; justify-content: center; }
}
@media (max-width: 480px) { 
    .cart-page .page-title { font-size: 18px; }
    .cart-table-wrap { padding: 8px; }
    .cart-product img { width: 80px; height: 80px; }
    .cart-product .product-info .product-name { font-size: 14px; }
}
</style>

<div class="cart-page">
    <div class="container">
        <div class="page-title">
            <i class="fa-solid fa-cart-shopping me-2"></i> Shopping <span>Cart</span>
        </div>
        
        <?php if (empty($cart_items)): ?>
        <div class="cart-table-wrap">
            <div class="empty-cart">
                <div class="empty-icon"><i class="fa-regular fa-circle-xmark"></i></div>
                <h3>Your Cart is Empty</h3>
                <p>Looks like you haven't added any items to your cart yet.</p>
                <a href="shop.php" class="btn-shop"><i class="fa-solid fa-arrow-left me-2"></i> Start Shopping</a>
            </div>
        </div>
        <?php else: ?>
        
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="cart-table-wrap">
                    <table class="cart-table">
                        <thead>
                            <tr>
                                <th style="width:40%;">Product</th>
                                <th style="width:20%;">Price</th>
                                <th style="width:25%;">Quantity</th>
                                <th style="width:15%;">Total</th>
                            </tr>
                        </thead>
                        <tbody id="cartItemsBody">
                            <?php foreach ($cart_items as $key => $item): ?>
                            <tr id="cartRow_<?php echo $key; ?>">
                                <td>
                                    <div class="cart-product">
                                        <img src="<?php echo ASSETS_URL; ?>images/products/<?php echo $item['image'] ?: 'default.jpg'; ?>" alt="<?php echo $item['name']; ?>">
                                        <div class="product-info">
                                            <a href="product.php?slug=<?php echo $item['slug'] ?? ''; ?>" class="product-name"><?php echo $item['name']; ?></a>
                                            <?php if (!empty($item['attributes'])): ?>
                                                <?php foreach ($item['attributes'] as $attr => $val): ?>
                                                <div class="product-variant"><?php echo $attr; ?>: <?php echo $val; ?></div>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="price-current" data-price="<?php echo $item['price']; ?>"><?php echo number_format($item['price']); ?> TK</span>
                                </td>
                                <td>
                                    <div class="qty-control">
                                        <button type="button" class="qty-btn" onclick="updateQty('<?php echo $key; ?>', -1)" <?php echo $item['quantity'] <= 1 ? 'disabled' : ''; ?>>
                                            <i class="fa-solid fa-minus"></i>
                                        </button>
                                        <input type="text" class="qty-input" id="qty_<?php echo $key; ?>" value="<?php echo $item['quantity']; ?>" readonly>
                                        <button type="button" class="qty-btn" onclick="updateQty('<?php echo $key; ?>', 1)">
                                            <i class="fa-solid fa-plus"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <span class="price-total" id="total_<?php echo $key; ?>"><?php echo number_format($item['price'] * $item['quantity']); ?> TK</span>
                                    <br>
                                    <button type="button" class="btn-remove" onclick="removeItem('<?php echo $key; ?>')" title="Remove item">
                                        <i class="fa-solid fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <div class="d-flex justify-content-between align-items-center mt-3 flex-wrap gap-2">
                        <a href="shop.php" class="btn-shop"><i class="fa-solid fa-arrow-left me-2"></i> Continue Shopping</a>
                        <button type="button" onclick="clearAllCart()" class="btn btn-outline-danger"><i class="fa-solid fa-trash me-2"></i> Clear Cart</button>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="cart-summary">
                    <div class="summary-title">Order Summary</div>
                    
                    <div class="summary-row">
                        <span class="label">Subtotal</span>
                        <span class="value" id="displaySubtotal"><?php echo number_format($subtotal); ?> TK</span>
                    </div>
                    <div class="summary-row">
                        <span class="label">Shipping</span>
                        <span class="value" id="displayShipping"><?php echo number_format($shipping_charge); ?> TK</span>
                    </div>
                    <div class="summary-row" id="discountRow" style="<?php echo $discount > 0 ? '' : 'display:none;'; ?>">
                        <span class="label">Discount</span>
                        <span class="value text-success" id="displayDiscount">-<?php echo number_format($discount); ?> TK</span>
                    </div>
                    <div class="summary-row total">
                        <span class="label">Total</span>
                        <span class="value" id="displayTotal"><?php echo number_format($total); ?> TK</span>
                    </div>
                    
                    <div class="coupon-section">
                        <div class="coupon-input-group">
                            <input type="text" id="couponInput" placeholder="Enter coupon code">
                            <button type="button" class="btn-apply" id="applyCouponBtn">Apply</button>
                        </div>
                        <div id="couponMessage" class="coupon-msg"></div>
                    </div>
                    
                    <a href="checkout.php" class="btn-checkout"><i class="fa-solid fa-lock me-2"></i> Proceed to Checkout</a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
// ========================================
// UPDATE QUANTITY - SIMPLE VERSION
// ========================================
function updateQty(key, change) {
    console.log('Update Qty - Key:', key, 'Change:', change);
    
    // Get current quantity
    var qtyInput = document.getElementById('qty_' + key);
    if (!qtyInput) {
        console.error('Quantity input not found for key:', key);
        return;
    }
    
    var currentQty = parseInt(qtyInput.value) || 1;
    var newQty = currentQty + change;
    
    // Validate
    if (newQty < 1) return;
    
    console.log('Current:', currentQty, 'New:', newQty);
    
    // Show loading on buttons
    var row = document.getElementById('cartRow_' + key);
    var buttons = row ? row.querySelectorAll('.qty-btn') : [];
    buttons.forEach(function(btn) {
        btn.disabled = true;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
    });
    
    // Create form data
    var formData = new FormData();
    formData.append('key', key);
    formData.append('qty', newQty);
    
    // Send AJAX request
    fetch('update-cart-ajax.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('Network error: ' + response.status);
        }
        return response.json();
    })
    .then(function(data) {
        console.log('Response:', data);
        
        if (data.success) {
            // Update quantity input
            qtyInput.value = newQty;
            
            // Update total price for this item
            var priceElement = row.querySelector('.price-current');
            var totalElement = document.getElementById('total_' + key);
            if (priceElement && totalElement) {
                var price = parseFloat(priceElement.getAttribute('data-price')) || 0;
                var newTotal = price * newQty;
                totalElement.textContent = newTotal.toFixed(0) + ' TK';
            }
            
            // Update subtotal and total
            updateTotals();
            
            // Update cart count in header
            var cartCount = document.getElementById('cartCount');
            if (cartCount) {
                cartCount.textContent = data.cart_count + ' items';
            }
            
            showToast('Cart updated!', 'success');
        } else {
            showToast(data.message || 'Failed to update cart', 'error');
        }
        
        // Reset buttons
        buttons.forEach(function(btn) {
            btn.disabled = false;
            btn.innerHTML = change > 0 ? '<i class="fa-solid fa-plus"></i>' : '<i class="fa-solid fa-minus"></i>';
        });
    })
    .catch(function(error) {
        console.error('Error:', error);
        showToast('Something went wrong. Please try again.', 'error');
        buttons.forEach(function(btn) {
            btn.disabled = false;
            btn.innerHTML = change > 0 ? '<i class="fa-solid fa-plus"></i>' : '<i class="fa-solid fa-minus"></i>';
        });
    });
}

// ========================================
// UPDATE TOTALS
// ========================================
function updateTotals() {
    var rows = document.querySelectorAll('#cartItemsBody tr');
    var subtotal = 0;
    
    rows.forEach(function(row) {
        var totalText = row.querySelector('.price-total');
        if (totalText) {
            var total = parseFloat(totalText.textContent.replace(/,/g, '').replace(' TK', '')) || 0;
            subtotal += total;
        }
    });
    
    var shipping = <?php echo $shipping_charge; ?>;
    var total = subtotal + shipping;
    
    document.getElementById('displaySubtotal').textContent = subtotal.toFixed(0) + ' TK';
    document.getElementById('displayTotal').textContent = total.toFixed(0) + ' TK';
}

// ========================================
// REMOVE ITEM
// ========================================
function removeItem(key) {
    if (!confirm('Remove this item from your cart?')) return;
    
    var formData = new FormData();
    formData.append('key', key);
    formData.append('qty', 0);
    
    fetch('update-cart-ajax.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        if (data.success) {
            var row = document.getElementById('cartRow_' + key);
            if (row) {
                row.style.transition = 'all 0.3s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    location.reload();
                }, 400);
            } else {
                location.reload();
            }
        } else {
            showToast(data.message || 'Failed to remove item', 'error');
        }
    })
    .catch(function(error) {
        showToast('Something went wrong. Please try again.', 'error');
    });
}

// ========================================
// CLEAR CART
// ========================================
function clearAllCart() {
    if (!confirm('Remove all items from your cart?')) return;
    
    fetch('clear-cart.php', {
        method: 'POST'
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        if (data.success) {
            location.reload();
        } else {
            showToast('Failed to clear cart', 'error');
        }
    })
    .catch(function(error) {
        showToast('Something went wrong. Please try again.', 'error');
    });
}

// ========================================
// TOAST NOTIFICATION
// ========================================
function showToast(message, type) {
    var colors = { success: '#22c55e', error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };
    
    var existingToast = document.querySelector('.toast-message');
    if (existingToast) existingToast.remove();
    
    var toast = document.createElement('div');
    toast.className = 'toast-message ' + type;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || colors.info};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
        max-width: 400px;
        font-size: 14px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

// ========================================
// APPLY COUPON
// ========================================
document.getElementById('applyCouponBtn').addEventListener('click', function() {
    var coupon = document.getElementById('couponInput').value.trim();
    if (!coupon) {
        showToast('Please enter a coupon code', 'warning');
        return;
    }
    
    var subtotal = parseFloat(document.getElementById('displaySubtotal').textContent.replace(/,/g, '')) || 0;
    
    var formData = new FormData();
    formData.append('coupon', coupon);
    formData.append('subtotal', subtotal);
    
    fetch('apply-coupon.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        var msgDiv = document.getElementById('couponMessage');
        if (data.success) {
            msgDiv.className = 'coupon-msg success';
            msgDiv.textContent = '✓ Coupon applied! You saved ' + data.discount_amount + ' TK';
            msgDiv.style.display = 'block';
            document.getElementById('discountRow').style.display = 'flex';
            document.getElementById('displayDiscount').textContent = '-' + data.discount_amount + ' TK';
            
            var total = parseFloat(document.getElementById('displayTotal').textContent.replace(/,/g, '')) - data.discount_amount;
            document.getElementById('displayTotal').textContent = total.toFixed(0) + ' TK';
            
            showToast(data.message, 'success');
        } else {
            msgDiv.className = 'coupon-msg error';
            msgDiv.textContent = '✗ ' + data.message;
            msgDiv.style.display = 'block';
            showToast(data.message, 'error');
        }
    })
    .catch(function(error) {
        showToast('Something went wrong. Please try again.', 'error');
    });
});

// ========================================
// INIT - Update totals on page load
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    updateTotals();
    
    // Add CSS for coupon messages
    var style = document.createElement('style');
    style.textContent = `
        .coupon-msg { padding: 8px 12px; border-radius: 6px; margin-top: 8px; display: none; font-size: 14px; }
        .coupon-msg.success { display: block; background: #f0fdf4; color: #166534; border: 1px solid #86efac; }
        .coupon-msg.error { display: block; background: #fef2f2; color: #991b1b; border: 1px solid #fca5a5; }
    `;
    document.head.appendChild(style);
});
</script>

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