<?php
require_once __DIR__ . '/includes/header.php';

// Fetch all product details for items in the wishlist
$wishlist_items = [];

if (isset($_SESSION['customer_id'])) {
    // Database wishlist
    try {
        $stmt = $pdo->prepare("SELECT p.*, c.name as category_name 
                                FROM wishlist w 
                                JOIN products p ON w.product_id = p.id 
                                LEFT JOIN categories c ON p.category_id = c.id
                                WHERE w.user_id = ? 
                                ORDER BY w.created_at DESC");
        $stmt->execute([$_SESSION['customer_id']]);
        $wishlist_items = $stmt->fetchAll();
    } catch (Exception $e) {
        $wishlist_items = [];
    }
} elseif (isset($_SESSION['wishlist']) && !empty($_SESSION['wishlist'])) {
    // Session wishlist
    $placeholders = implode(',', array_fill(0, count($_SESSION['wishlist']), '?'));
    try {
        $stmt = $pdo->prepare("SELECT p.*, c.name as category_name 
                                FROM products p 
                                LEFT JOIN categories c ON p.category_id = c.id 
                                WHERE p.id IN ($placeholders)");
        $stmt->execute($_SESSION['wishlist']);
        $wishlist_items = $stmt->fetchAll();
    } catch (Exception $e) {
        $wishlist_items = [];
    }
}
?>

<!-- Banner -->
<section class="py-4 bg-black border-bottom border-dark">
    <div class="container text-center">
        <h1 class="text-white fw-bold mb-0">Private Wishlist</h1>
        <p class="text-warning small text-uppercase fw-bold mb-0 mt-1" style="letter-spacing: 2px;">Your Curated Boutique Selection</p>
    </div>
</section>

<!-- Wishlist Content -->
<section class="py-5" style="background-color: var(--bg-dark); min-height: 60vh;">
    <div class="container">
        
        <?php if (empty($wishlist_items)): ?>
            <!-- Empty Wishlist -->
            <div class="text-center py-5">
                <div class="py-5" style="background-color: var(--bg-card); border-radius: 15px; border: 1px solid rgba(255,255,255,0.05); max-width: 600px; margin: 0 auto;">
                    <i class="fa-regular fa-heart text-warning display-1 mb-4"></i>
                    <h3 class="text-white fw-bold">Your Wishlist is Empty</h3>
                    <p class="text-gray small px-4 mb-4">Save your favorite designer blazer, bespoke coat, or luxury accessory items in your private collection to purchase them later.</p>
                    <a href="shop.php" class="btn btn-warning rounded-pill px-5 py-3 fw-bold text-uppercase fs-7 text-black" style="letter-spacing: 1px;">Browse Catalog</a>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-4 justify-content-center">
                <?php foreach ($wishlist_items as $item): ?>
                    <div id="wishlist-row-<?php echo $item['id']; ?>" class="col-lg-4 col-md-6">
                        <div class="product-card">
                            <div class="product-img-wrapper">
                                <a href="product.php?id=<?php echo $item['id']; ?>">
                                    <img src="assets/images/<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" loading="lazy">
                                </a>
                                <!-- Remove Action -->
                                <button type="button" class="wishlist-btn text-warning" onclick="removeFromWishlist(<?php echo $item['id']; ?>)" title="Remove item">
                                    <i class="fa-solid fa-heart"></i>
                                </button>
                            </div>
                            <div class="product-details position-relative">
                                <div class="mb-1 text-muted text-uppercase small" style="font-size: 0.7rem; letter-spacing: 1px;">
                                    <?php echo htmlspecialchars($item['category_name'] ?? 'Couture'); ?>
                                </div>
                                <h4 class="product-name fs-6">
                                    <a href="product.php?id=<?php echo $item['id']; ?>" class="text-white text-decoration-none hover-gold">
                                        <?php echo htmlspecialchars($item['name']); ?>
                                    </a>
                                </h4>
                                <div class="product-price">LKR <?php echo number_format($item['price'], 2); ?></div>
                                
                                <!-- Move to Cart Action -->
                                <button type="button" class="cart-icon-btn add-to-cart-btn" onclick="moveToBag(<?php echo $item['id']; ?>)" title="Add to Bag">
                                    <i class="fa-solid fa-bag-shopping text-dark"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
    </div>
</section>

<script>
function removeFromWishlist(productId) {
    if (confirm('Are you sure you want to remove this item from your wishlist?')) {
        fetch('wishlist_action.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=remove&product_id=${productId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                window.showToast('Item removed from wishlist.');
                
                // Update badge
                let badge = document.querySelector('.wishlist-badge');
                if (badge) {
                    if (data.wishlist_count > 0) {
                        badge.textContent = data.wishlist_count;
                    } else {
                        badge.style.display = 'none';
                    }
                }
                
                // Remove product block from screen
                const el = document.getElementById(`wishlist-row-${productId}`);
                if (el) {
                    el.style.opacity = 0;
                    setTimeout(() => {
                        el.remove();
                        // If no more items on screen, reload to show empty state
                        if (document.querySelectorAll('.product-card').length === 0) {
                            window.location.reload();
                        }
                    }, 300);
                }
            } else {
                window.showToast(data.message, 'error');
            }
        })
        .catch(err => {
            console.error(err);
            window.showToast('Could not remove item. Please try again.', 'error');
        });
    }
}

function moveToBag(productId) {
    // Add to cart with default Size M, color Midnight Black
    fetch('cart_action.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `action=add&product_id=${productId}&quantity=1&size=M&color=Midnight%20Black`
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            // Update cart badge
            let cartBadge = document.querySelector('.cart-badge');
            if (cartBadge) {
                cartBadge.textContent = data.cart_count;
            } else {
                const cartLink = document.querySelector('.fa-bag-shopping').parentElement;
                const badgeSpan = document.createElement('span');
                badgeSpan.className = 'position-absolute top-0 start-100 translate-middle badge rounded-circle cart-badge';
                badgeSpan.textContent = data.cart_count;
                cartLink.appendChild(badgeSpan);
            }
            
            window.showToast('Masterpiece successfully added to shopping bag!');
            
            // Remove from wishlist database-wise/session-wise as it is moved
            fetch('wishlist_action.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=remove&product_id=${productId}`
            })
            .then(res => res.json())
            .then(d => {
                if (d.status === 'success') {
                    // Update badge
                    let wBadge = document.querySelector('.wishlist-badge');
                    if (wBadge) {
                        if (d.wishlist_count > 0) {
                            wBadge.textContent = d.wishlist_count;
                        } else {
                            wBadge.style.display = 'none';
                        }
                    }
                    
                    const el = document.getElementById(`wishlist-row-${productId}`);
                    if (el) {
                        el.style.opacity = 0;
                        setTimeout(() => {
                            el.remove();
                            if (document.querySelectorAll('.product-card').length === 0) {
                                window.location.reload();
                            }
                        }, 300);
                    }
                }
            });
        } else {
            window.showToast(data.message || 'Error moving to bag.', 'error');
        }
    })
    .catch(err => {
        console.error(err);
        window.showToast('Something went wrong. Please try again.', 'error');
    });
}
</script>

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