<?php
require_once 'includes/User.php';
require_once 'includes/cart.php';
require_once 'includes/db_config.php';
require_once 'includes/pricing.php';

function formatSelectedOptions($opts) {
    if (!$opts) return '';
    
    $arr = [];
    foreach ($opts as $type => $data) {
        if ($type === 'addons' && is_array($data)) {
            foreach ($data as $addon) {
                $display = $addon['name'] ?? 'Add-on';
                if (isset($addon['price']) && $addon['price'] > 0) {
                    $display .= ' (+SAR ' . number_format($addon['price'], 2) . ')';
                }
                $arr[] = $display;
            }
        } elseif (is_array($data)) {
            $display = ucfirst(str_replace('_', ' ', $type)) . ': ' . ($data['name'] ?? '');
            
            
            $price_value = $data['price'] ?? $data['price_modifier'] ?? 0;
            if ($price_value > 0) {
                $display .= ' (+SAR ' . number_format($price_value, 2) . ')';
            } elseif ($price_value < 0) {
                $display .= ' (SAR ' . number_format($price_value, 2) . ')';
            }
            $arr[] = $display;
        }
    }
    return implode(', ', $arr);
}

if (!User::isLoggedIn()) { 
    header("Location: login.php"); 
    exit(); 
}

$me = User::getCurrentUser();

$hasSub = false;
$subInfo = null;
try {
    $db = getDBConnection();
    $stmt = $db->prepare("
        SELECT * FROM subscriptions 
        WHERE user_id = ? AND status = 'active' AND end_date >= CURDATE() AND usage_count < max_usage
        ORDER BY created_at DESC LIMIT 1
    ");
    $stmt->execute([$me['id']]);
    $subInfo = $stmt->fetch(PDO::FETCH_ASSOC);
    $hasSub = !empty($subInfo);
} catch (PDOException $e) {
    $hasSub = false;
}


$items = getCartItems();
safe_session_start();
$cart_items = isset($_SESSION['cart_items']) ? $_SESSION['cart_items'] : [];

$details = [];
$total = 0;
$tot = 0;
if (!empty($items)) {
    try {
        $db = getDBConnection();
        
        $ph = str_repeat('?,', count($items) - 1) . '?';
        $sql = "SELECT id, name, price, category, image FROM services WHERE id IN ($ph)";
        
        $ids = array_column($items, 'service_id');
        $stmt = $db->prepare($sql);
        $stmt->execute($ids);
        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $svc_map = [];
        foreach ($services as $service) { 
            $svc_map[$service['id']] = $service; 
        }
        
        foreach ($items as $item) {
            $service_id = $item['service_id'];
            if (isset($svc_map[$service_id])) {
                $service = $svc_map[$service_id];
                $base_price = $service['price'];
                $options_price = 0;
                
                $options_text = '';
                if (isset($item['selected_options']) && !empty($item['selected_options'])) {
                    $opts = is_string($item['selected_options']) ? 
                        json_decode($item['selected_options'], true) : $item['selected_options'];
                    
                    if ($opts) {
                        $options_text = formatSelectedOptions($opts);
                        foreach ($opts as $key => $opt_data) {
                            if ($key === 'addons' && is_array($opt_data)) {
                                foreach ($opt_data as $addon) {
                                    if (isset($addon['price'])) {
                                        $options_price += floatval($addon['price']);
                                    }
                                }
                            } elseif (is_array($opt_data)) {
                                if (isset($opt_data['price'])) {
                                    $options_price += floatval($opt_data['price']);
                                } elseif (isset($opt_data['price_modifier'])) {
                                    $options_price += floatval($opt_data['price_modifier']);
                                }
                            }
                        }
                    }
                }
                
                if (TieredPricing::isTieredService($service_id)) {
                    $tiered_total = TieredPricing::calculateTotalWithTiers($service_id, $item['quantity'], $base_price);
                    $item_total = $tiered_total + $options_price;
                } else {
                    $item_total = ($base_price + $options_price) * $item['quantity'];
                }
                $total += $item_total;
                $tot += $item_total;
                
                $tier_info = TieredPricing::getTierInfo($service_id, $item['quantity']);
                
                $details[] = [
                    'service_id' => $service_id,
                    'name' => $service['name'],
                    'price' => $base_price,
                    'options_price' => $options_price,
                    'image' => $service['image'] ?? null,
                    'quantity' => $item['quantity'],
                    'total_price' => $item_total,
                    'options_text' => $options_text,
                    'type' => 'regular',
                    'category' => isset($service['category']) ? $service['category'] : 'general',
                    'tier_info' => $tier_info
                ];
            }
        }
    } catch (PDOException $e) {
        $error = 'Error loading cart: ' . $e->getMessage();
    }
}

if (!empty($cart_items)) {
    try {
        if (!isset($db)) {
        }
        
        $service_ids = array_unique(array_column($cart_items, 'service_id'));
        if (!empty($service_ids)) {
            $ph = str_repeat('?,', count($service_ids) - 1) . '?';
            $stmt = $db->prepare("SELECT id, name, description, price, category, image FROM services WHERE id IN (" . implode(',', array_fill(0, count($service_ids), '?')) . ")");
            $stmt->execute($service_ids);
            $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $service_map = [];
            foreach ($services as $svc) { 
                $service_map[$svc['id']] = $svc; 
            }
            
            $options_sql = "SELECT * FROM service_options WHERE service_id IN ($ph)";
            $options_st = $db->prepare($options_sql);
            $options_st->execute($service_ids);
            $options_rows = $options_st->fetchAll(PDO::FETCH_ASSOC);
            
            $options_map = [];
            foreach ($options_rows as $option) {
                $options_map[$option['id']] = $option;
            }
            
            foreach ($cart_items as $index => $item) {
                $sid = $item['service_id'];
                if (isset($service_map[$sid])) {
                    $svc = $service_map[$sid];
                    $base_price = $svc['price'];
                    $quantity = $item['quantity'];
                    
                    if (TieredPricing::isTieredService($sid)) {
                        $total_price = TieredPricing::calculateTotalWithTiers($sid, $quantity, $base_price);
                    } else {
                        $total_price = $base_price * $quantity;
                    }
                    
                    $selected_options = json_decode($item['selected_options'], true);
                    $options_text = '';
                    
                    if ($selected_options) {
                        $options_text = formatSelectedOptions($selected_options);
                        foreach ($selected_options as $option_data) {
                            if (isset($option_data['price_modifier'])) {
                                if (TieredPricing::isTieredService($sid)) {
                                    $total_price += $option_data['price_modifier'];
                                } else {
                                    $total_price += $option_data['price_modifier'] * $quantity;
                                }
                            }
                        }
                    }
                    
                    $tot += $total_price;
                    
                    $tier_info = TieredPricing::getTierInfo($sid, $quantity);
                    
                    $details[] = [
                        'service_id' => $sid,
                        'cart_index' => $index,
                        'name' => $svc['name'],
                        'price' => $base_price,
                        'quantity' => $quantity,
                        'total_price' => $total_price,
                        'selected_options' => $selected_options,
                        'options_text' => implode(', ', $options_text),
                        'image' => $svc['image'] ?? null,
                        'type' => 'custom',
                        'category' => isset($svc['category']) ? $svc['category'] : 'general',
                        'tier_info' => $tier_info
                    ];
                }
            }
        }
    } catch (PDOException $e) {
        $error = "Error fetching enhanced cart items: " . $e->getMessage();
    }
}

$discount_amount = 0;
$offer_title = '';
$offer_id = null;
$customer_type = 'new';

if ($tot > 0) {
    try {
        $stmt = $db->prepare("
            SELECT u.*, 
                   COUNT(o.id) as order_count,
                   CASE 
                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                       WHEN COUNT(o.id) > 0 THEN 'normal'
                       ELSE 'new'
                   END as customer_type
            FROM users u 
            LEFT JOIN orders o ON u.id = o.user_id 
            WHERE u.id = ?
            GROUP BY u.id
        ");
        $stmt->execute([$me['id']]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $customer_type = $user_data['customer_type'] ?? 'new';
        
        $stmt = $db->prepare("
            SELECT * FROM offers 
            WHERE status = 'active' 
            AND start_date <= CURDATE() 
            AND end_date >= CURDATE()
            AND (target_customers = 'all' OR target_customers = ?)
            AND min_order_amount <= ?
            AND (usage_limit IS NULL OR used_count < usage_limit)
            ORDER BY discount_value DESC
            LIMIT 1
        ");
        $stmt->execute([$customer_type, $tot]);
        $offer = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($offer) {
            if ($offer['discount_type'] === 'percentage') {
                $discount_amount = ($tot * $offer['discount_value']) / 100;
                if ($offer['max_discount_amount'] && $discount_amount > $offer['max_discount_amount']) {
                    $discount_amount = $offer['max_discount_amount'];
                }
            } else {
                $discount_amount = $offer['discount_value'];
            }
            $discount_amount = min($discount_amount, $tot);
            $offer_title = $offer['title'];
            $offer_id = $offer['id'];
        }
    } catch (PDOException $e) {
        error_log("Error applying discount: " . $e->getMessage());
    }
}

$discounted_total = $tot - $discount_amount;
$tax = $discounted_total * 0.08;
$grand = $discounted_total + $tax;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Cart - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
</head>
<body>
    <div class="cart-container">
        <div class="cart-header">
            <div class="cart-title-section">
                <h2><i class="fas fa-shopping-cart"></i> My Cart</h2>
                <p>Welcome, <?php echo htmlspecialchars($me['name']); ?></p>
            </div>
        </div>
        
        <?php if ($discount_amount > 0): ?>
        <div class="customer-offer-info" style="background: linear-gradient(135deg, #e6f7fb 0%, #c1e1f1 100%); color: #333; padding: 1rem; border-radius: 10px; margin-bottom: 1.5rem; border: 2px solid #00aaff; box-shadow: 0 4px 15px rgba(0,170,255,0.2);">
            <div style="display: flex; align-items: center; margin-bottom: 0.5rem;">
                <span style="font-size: 1.5rem; margin-right: 0.5rem;">🎉</span>
                <h4 style="margin: 0; font-size: 1.1rem; color: #00aaff; font-weight: bold;">Special Offer for You!</h4>
            </div>
            <p style="margin: 0; font-size: 0.9rem; color: #333;">
                <?php 
                    echo "As a " . ($customer_type == 'new' ? 'new' : ($customer_type == 'regular' ? 'valued' : ($customer_type == 'subscribed' ? 'subscribed' : 'regular'))) . " customer";
                    echo ", you get discount: <strong style='color: #00aaff;'>" . htmlspecialchars($offer_title) . "</strong>";
                ?>
            </p>
        </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <p class="error-message"><?php echo htmlspecialchars($error); ?></p>
        <?php endif; ?>
        
        <?php if (empty($details)): ?>
            <div class="empty-cart">
                <div class="empty-cart-icon">
                    <i class="fas fa-shopping-cart"></i>
                </div>
                <h3>Your cart is empty</h3>
                <p>Add some services to get started</p>
                <a href="service.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Browse Services
                </a>
            </div>
        <?php else: ?>
            <div class="cart-content">
                <div class="cart-items-section">
                    <div class="section-header">
                        <h3><i class="fas fa-list"></i> Order Items</h3>
                        <span class="items-count"><?php echo count($details); ?> item(s)</span>
                    </div>
                    
                    <div class="enhanced-cart-items">
                        <?php foreach ($details as $item): ?>
                        <div class="cart-item-card" <?php if ($item['type'] === 'custom'): ?>data-cart-index="<?php echo $item['cart_index']; ?>"<?php endif; ?>>
                            <div class="item-image">
                                <?php if (!empty($item['image'])): ?>
                                    <img src="<?php echo htmlspecialchars($item['image']); ?>" 
                                         alt="<?php echo htmlspecialchars($item['name']); ?>"
                                         onerror="this.src='img/default-service.png'">
                                <?php else: ?>
                                    <div class="no-image">
                                        <i class="fas fa-image"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="item-content">
                                <div class="item-header">
                                    <h4>
                                        <a href="service.php?service_id=<?php echo $item['service_id']; ?>" 
                                           style="color: #007cba; text-decoration: none; transition: color 0.3s ease;"
                                           onmouseover="this.style.color='#005a8b'"
                                           onmouseout="this.style.color='#007cba'">
                                            <?php echo htmlspecialchars($item['name']); ?>
                                        </a>
                                    </h4>
                                    <span class="item-price">SAR <?php echo number_format($item['total_price'], 2); ?></span>
                                </div>
                                
                                <div class="item-details">
                                    <div class="item-info">
                                        <?php if (isset($item['tier_info']) && $item['tier_info']): ?>
                                        <div class="tiered-pricing-info" style="background: #f0f8ff; padding: 0.75rem; border-radius: 8px; margin-bottom: 0.5rem; border-left: 4px solid #00aaff;">
                                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                                                <span style="font-weight: 600; color: #00aaff;">Price</span>
                                                <span style="font-size: 0.85rem; color: #666;">Tier: <?php echo $item['tier_info']['current_tier']; ?></span>
                                            </div>
                                            <div style="font-size: 0.9rem; color: #333;">
                                                Current Price: <strong>SAR <?php echo number_format($item['tier_info']['current_price'], 2); ?></strong> per piece
                                                <?php if ($item['tier_info']['savings'] > 0): ?>
                                                <span style="color: #28a745; margin-left: 0.5rem;">
                                                    (Save SAR <?php echo number_format($item['tier_info']['savings'], 2); ?>)
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                            <?php if ($item['tier_info']['next_tier_at']): ?>
                                            <div style="font-size: 0.85rem; color: #666; margin-top: 0.25rem;">
                                                Next discount at <?php echo $item['tier_info']['next_tier_at']; ?> pieces: SAR <?php echo number_format($item['tier_info']['next_tier_price'], 2); ?> each
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php else: ?>
                                        <span class="base-priceCART">Base Price: SAR <?php echo number_format($item['price'], 2); ?></span>
                                        <?php endif; ?>
                                        
                                        <?php if (isset($item['options_price']) && $item['options_price'] > 0): ?>
                                        <span class="options-priceCART" style="color: #00aaff; font-size: 0.9rem;">
                                            + Options: SAR <?php echo number_format($item['options_price'], 2); ?>
                                        </span>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($item['options_text'])): ?>
                                        <div class="selected-options" style="margin: 0.5rem 0; padding: 0.5rem; background: #f8f9fa; border-radius: 5px; border-left: 3px solid #007cba;">
                                            <strong style="color: #007cba;">Selected Options:</strong><br>
                                            <?php 
                                            $options_array = explode(', ', $item['options_text']);
                                            foreach ($options_array as $option) {
                                                echo '<span style="display: inline-block; margin: 2px 5px 2px 0; padding: 2px 8px; background: #e9ecef; border-radius: 12px; font-size: 0.85rem;">' . htmlspecialchars($option) . '</span>';
                                            }


                                         if (!empty($item['pickup_option']) && $item['pickup_option'] === 'pickup') {
                                                   echo '<div style="margin-top:6px; font-size:0.9rem;">';
                                                   echo '<strong>Pickup Option:</strong> Pickup<br>';
                                                   if (!empty($item['pickup_address'])) {
                                                       echo '<strong>Pickup Address:</strong> ' . nl2br(htmlspecialchars($item['pickup_address']));
                                                   }
                                                   echo '</div>';
                                               }
                                            ?>


                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="quantity-section">
                                            <span class="quantity-label">
                                                <?php 
                                                if (isset($item['category'])) {
                                                    echo $item['category'] === 'washing' ? 'Weight:' : 
                                                         ($item['category'] === 'ironing' ? 'Pieces:' : 'Quantity:');
                                                } else {
                                                    echo 'Quantity:';
                                                }
                                                ?>
                                            </span>
                                            <div class="quantity-control">
                                                <?php if ($item['type'] === 'custom'): ?>
                                                    <button class="quantity-btn" onclick="updateCartQuantity(<?php echo $item['cart_index']; ?>, -1)">-</button>
                                                    <span class="quantity-display"><?php echo $item['quantity']; ?></span>
                                                    <button class="quantity-btn" onclick="updateCartQuantity(<?php echo $item['cart_index']; ?>, 1)">+</button>
                                                <?php else: ?>
                                                    <button class="quantity-btn" onclick="updateQuantity(<?php echo $item['service_id']; ?>, -1)">-</button>
                                                    <span class="quantity-display"><?php echo $item['quantity']; ?></span>
                                                    <button class="quantity-btn" onclick="updateQuantity(<?php echo $item['service_id']; ?>, 1)">+</button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="item-actions">
                                        <?php if ($item['type'] === 'custom'): ?>
                                            <button class="remove-btn" onclick="removeCartItem(<?php echo $item['cart_index']; ?>)">
                                                <i class="fas fa-trash"></i> Remove
                                            </button>
                                        <?php else: ?>
                                            <button class="remove-btn" onclick="removeFromCart(<?php echo $item['service_id']; ?>)">
                                                <i class="fas fa-trash"></i> Remove
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="cart-sidebar">
            
                    <?php if ($discount_amount > 0): ?>
                    <div class="discount-info" style="background: #f0f8ff; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #00aaff; box-shadow: 0 2px 8px rgba(0,170,255,0.1);">
                        <h4 style="color: #00aaff; margin: 0 0 0.5rem 0; font-size: 1rem;">🎉 Discount Applied!</h4>
                        <p style="margin: 0; color: #333;"><strong style="color: #00aaff;"><?php echo htmlspecialchars($offer_title); ?></strong></p>
                        <p style="margin: 0.25rem 0 0 0; color: #00aaff; font-weight: 600;">You save: SAR <?php echo number_format($discount_amount, 2); ?></p>
                    </div>
                    <?php endif; ?>
            
                    <div class="summary-section">
                        <h3><i class="fas fa-calculator"></i> Order Summary</h3>
                    </div>
                    
                    <div class="cart-summary">
                <div class="summary-row">
                    <span>Subtotal:</span>
                    <span>SAR <?php echo number_format($tot, 2); ?></span>
                </div>
                <?php if ($discount_amount > 0): ?>
                <div class="summary-row" style="color: #00aaff;">
                    <span>Discount (<?php echo htmlspecialchars($offer_title); ?>):</span>
                    <span>-SAR <?php echo number_format($discount_amount, 2); ?></span>
                </div>
                <?php endif; ?>
                <div class="summary-row">
                    <span>Tax (8%):</span>
                    <span>SAR <?php echo number_format($tax, 2); ?></span>
                </div>
                <div class="summary-row total-row">
                    <span>Total:</span>
                    <span>SAR <?php echo number_format($grand, 2); ?></span>
                </div>
                
                <?php if ($hasSub): ?>
                <div class="sub-notice">
                    <div class="sub-notice-content">
                        <div class="sub-notice-hdr">
                            <i class="fas fa-crown"></i>
                            <span>Express Delivery Available!</span>
                        </div>
                        <p>You can use your <strong><?php echo htmlspecialchars($subInfo['plan_name']); ?></strong> for express delivery (same day to 48 hours) during checkout.</p>
                        <div class="sub-notice-details">
                            <span><i class="fas fa-check"></i> Remaining: <?php echo ($subInfo['max_usage'] - $subInfo['usage_count']); ?></span>
                            <span><i class="fas fa-calendar"></i> Valid Until: <?php echo date('M j, Y', strtotime($subInfo['end_date'])); ?></span>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                        <div class="cart-actions">
                            <a href="/allura/service.php" class="btn">
                                <i class="fas fa-arrow-left"></i> Continue Shopping
                            </a>
                            <a href="/allura/checkout.php" class="btn btn-primary">
                                <i class="fas fa-credit-card"></i> Proceed to Checkout
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="/allura/js/cart.js"></script>
    <script>
        function calculateTieredTotal(serviceId, quantity) {
            const tieredServices = [1, 2];
            
            if (!tieredServices.includes(serviceId)) {
                return null;
            }
            
            if (quantity <= 4) {
                return 20.00;
            }
            
            if (quantity >= 5 && quantity < 15) {
                return 18.00;
            }
            
            if (quantity >= 15 && quantity < 20) {
                return 17.00;
            }
            
            if (quantity == 20) {
                return 16.00;
            }
            
            if (quantity > 20) {
                const baseTotal = 16.00;
                const extraQuantity = quantity - 20;
                const extraGroups = Math.ceil(extraQuantity / 5);
                const extraCost = extraGroups * 5;
                return baseTotal + extraCost;
            }
            
            return 20.00;
        }

        function updateCartQuantity(cartIndex, change) {
            const cartItems = <?php echo json_encode($cart_items); ?>;
            const currentQuantity = parseFloat(cartItems[cartIndex]?.quantity || 1);
            const newQuantity = currentQuantity + change;

            if (newQuantity < 1) {
                return; 
            }

            const quantityDisplay = document.querySelector(`[data-cart-index="${cartIndex}"] .quantity-display`);
            if (quantityDisplay) {
                quantityDisplay.textContent = newQuantity;
            }

            const serviceId = parseInt(cartItems[cartIndex]?.service_id);
            const tieredServices = [1, 2];
            
            if (tieredServices.includes(serviceId)) {
                const newTotal = calculateTieredTotal(serviceId, newQuantity);
                const optionsPrice = parseFloat(cartItems[cartIndex]?.options_price || 0);
                const finalTotal = newTotal + optionsPrice;
                
                const itemPriceElement = document.querySelector(`[data-cart-index="${cartIndex}"] .item-price`);
                const tierInfoElement = document.querySelector(`[data-cart-index="${cartIndex}"] .tiered-pricing-info`);
                
                if (itemPriceElement && newTotal) {
                    itemPriceElement.textContent = `SAR ${finalTotal.toFixed(2)}`;
                }
                
                if (tierInfoElement) {
                    let tierText = '';
                    if (newQuantity <= 4) {
                        tierText = '1-4 pieces';
                    } else if (newQuantity >= 5 && newQuantity < 15) {
                        tierText = '5-14 pieces';
                    } else if (newQuantity >= 15 && newQuantity < 20) {
                        tierText = '15-19 pieces';
                    } else if (newQuantity == 20) {
                        tierText = '20 pieces';
                    } else {
                        tierText = '20+ pieces';
                    }
                    
                    const tierSpan = tierInfoElement.querySelector('[style*="color: #666"]');
                    if (tierSpan) {
                        tierSpan.textContent = `Tier: ${tierText}`;
                    }
                    
                    const priceSpan = tierInfoElement.querySelector('strong');
                    if (priceSpan && newTotal) {
                        priceSpan.textContent = `SAR ${newTotal.toFixed(2)}`;
                    }
                }
            }

            const formData = new FormData();
            formData.append('action', 'update_cart');
            formData.append('cart_index', cartIndex);
            formData.append('change', change);

            fetch('/php/cart_handler.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateCartTotals();
                } else {
                    alert('Error updating quantity: ' + data.message);
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while updating quantity');
                location.reload();
            });
        }

        function updateCartTotals() {
            fetch('/php/cart_handler.php?action=get_details')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const summaryRows = document.querySelectorAll('.summary-row');
                    
                    summaryRows.forEach((row, index) => {
                        const lastSpan = row.querySelector('span:last-child');
                        if (lastSpan) {
                            if (index === 0) {
                                lastSpan.textContent = `SAR ${data.totalAmount.toFixed(2)}`;
                            } else if (row.textContent.includes('Tax')) {
                                lastSpan.textContent = `SAR ${data.taxAmount.toFixed(2)}`;
                            }
                        }
                    });
                    
                    const totalElement = document.querySelector('.total-row span:last-child');
                    if (totalElement) {
                        totalElement.textContent = `SAR ${data.finalTotal.toFixed(2)}`;
                    }
                }
            })
            .catch(error => {
                console.error('Error updating totals:', error);
            });
        }
        
        function removeCartItem(cartIndex) {
            if (confirm('Are you sure you want to remove this item from your cart?')) {
                const formData = new FormData();
                formData.append('action', 'remove_cart_item');
                formData.append('cart_index', cartIndex);
                
                fetch('/php/cart_handler.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload(); 
                    } else {
                        alert('Error removing item: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while removing item');
                });
            }
        }
        
        function showNotification(type, message) {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#d4edda' : '#f8d7da'};
                color: ${type === 'success' ? '#155724' : '#721c24'};
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                z-index: 1000;
                max-width: 300px;
                animation: slideIn 0.3s ease;
            `;
            
            notification.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i>
                <span style="margin-left: 8px;">${message}</span>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.remove();
            }, 4000);
        }
        
        const shoeImages = {
            'heels': 'img/Heels.png',
            'sports': 'img/Sports.png',
            'formal': 'img/Formal.png',
            'casual': 'img/Casual.png'
        };
        
        function updateCartShoeImages() {
            const cartItems = document.querySelectorAll('.cart-item-card');
            
            cartItems.forEach(item => {
                const itemImage = item.querySelector('.item-image img');
                const selectedOptions = item.querySelector('.selected-options');
                
                if (itemImage && selectedOptions) {
                    const optionsText = selectedOptions.textContent;
                    
                    let shoeType = null;
                    if (optionsText.includes('Heels')) {
                        shoeType = 'heels';
                    } else if (optionsText.includes('Sports')) {
                        shoeType = 'sports';
                    } else if (optionsText.includes('Formal')) {
                        shoeType = 'formal';
                    } else if (optionsText.includes('Casual')) {
                        shoeType = 'casual';
                    }
                    
                    if (shoeType && shoeImages[shoeType]) {
                        itemImage.src = shoeImages[shoeType];
                    }
                }
            });
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            updateCartShoeImages();
        });
    </script>
    
    <style>
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</body>
</html>