<?php
session_start();
require_once __DIR__ . '/wishlist_handler.php';

$userId = $_SESSION['user_id'] ?? 'guest_' . md5($_SERVER['REMOTE_ADDR']);
$wishlistIds = getWishlistItems($userId);

// Load products
$products = [];
$productsFile = __DIR__ . '/data/products.json';
if (file_exists($productsFile)) {
    $prods = json_decode(file_get_contents($productsFile), true) ?: [];
    foreach ($prods as $p) {
        $products[$p['id']] = $p;
    }
}

$wishlistProducts = [];
foreach ($wishlistIds as $id) {
    if (isset($products[$id])) {
        $wishlistProducts[] = $products[$id];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Wishlist - Esa's Fashion</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<?php include __DIR__ . '/header.php'; ?>

<main class="container" style="margin-top:24px; margin-bottom:24px;">
    <h2>My Wishlist</h2>
    
    <?php if (empty($wishlistProducts)): ?>
        <p style="text-align:center; color:#666; margin-top:40px;">Your wishlist is empty. <a href="shop.php" style="display:inline-block; background:#F07E2D; color:white; padding:10px 25px; text-decoration:none; border-radius:4px; font-weight:600; margin-left:10px;">Continue Shopping</a></p>
    <?php else: ?>
        <div class="product-grid" style="margin-top:24px;">
            <?php foreach ($wishlistProducts as $prod): 
                require_once __DIR__ . '/config/image_config.php';
                $imageUrl = !empty($prod['image']) ? getImageForSection($prod['image'], 'wishlist') : 'pics_ecom/placeholder.png';
            ?>
                <div class="product-display-wrapper" style="position: relative;">
                    <a href="product.php?id=<?php echo $prod['id']; ?>" class="product" style="text-decoration: none; color: inherit;">
                        <img src="<?php echo htmlspecialchars($imageUrl); ?>" alt="<?php echo htmlspecialchars($prod['title']); ?>">
                        <h3><?php echo htmlspecialchars($prod['title']); ?></h3>
                        <p class="price">$<?php 
                            $displayPrice = isset($prod['sale_price']) ? $prod['sale_price'] : ($prod['price'] ?? '0');
                            echo htmlspecialchars($displayPrice); 
                        ?></p>
                    </a>
                    <button onclick="removeFromWishlist(<?php echo $prod['id']; ?>)" 
                            style="position: absolute; top: 10px; right: 10px; background: #fff; border: none; width: 36px; height: 36px; border-radius: 50%; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: flex; align-items: center; justify-content: center; color: #F07E2D; font-size: 18px; transition: all 0.3s ease;"
                            onmouseover="this.style.background='#F07E2D'; this.style.color='#fff';"
                            onmouseout="this.style.background='#fff'; this.style.color='#F07E2D';"
                            title="Remove from Wishlist">
                        <i class="fa-solid fa-trash"></i>
                    </button>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</main>

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

<script>
function removeFromWishlist(productId) {
    if (!confirm('Are you sure you want to remove this item from your wishlist?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'wishlist');
    formData.append('product_id', productId);
    
    fetch('wishlist_handler.php', {
        method: 'POST',
        body: formData
    }).then(r => r.json()).then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error removing item from wishlist');
        }
    }).catch(error => {
        console.error('Error:', error);
        alert('Error removing item from wishlist');
    });
}
</script>
</body>
</html>
