<?php
// 1. INCLUDE THE DASHBOARD HEADER
include 'header.php';

// --- Page-Specific Logic Starts Here ---
// The $user_id variable is available from header.php

// 2. FETCH WISHLIST ITEMS
// This query efficiently fetches all wishlisted items and their details using LEFT JOINs
$stmt = $conn->prepare("
    SELECT 
        w.id as wishlist_id, w.item_id, w.item_type,
        COALESCE(t.title, h.name) as item_name,
        COALESCE(t.location, h.location) as item_location,
        COALESCE(t.image_url, h.main_image_url) as item_image,
        t.price as item_price
    FROM wishlist_items w
    LEFT JOIN tours t ON w.item_id = t.id AND w.item_type IN ('tour', 'service')
    LEFT JOIN hotels h ON w.item_id = h.id AND w.item_type = 'hotel'
    WHERE w.user_id = ?
    ORDER BY w.created_at DESC
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$wishlist_items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<div class="container my-5">
    <div class="dashboard-content">
        <h1 class="h2 mb-4">My Wishlist</h1>

        <?php if (!empty($wishlist_items)): ?>
        <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4" id="wishlist-container">
            <?php foreach ($wishlist_items as $item): ?>
                <div class="col" id="wishlist-item-<?php echo $item['wishlist_id']; ?>">
                    <div class="card h-100 tour-card shadow-sm">
                        <?php
                            $details_page = $item['item_type'] . '-details.php';
                            if ($item['item_type'] === 'service') {
                                $details_page = 'service-details.php';
                            }
                        ?>
                        <a href="../<?php echo $details_page; ?>?id=<?php echo $item['item_id']; ?>">
                            <img src="../<?php echo htmlspecialchars($item['item_image'] ?? 'https://via.placeholder.com/300x200.png?text=No+Image'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($item['item_name']); ?>">
                        </a>
                        <div class="card-body d-flex flex-column">
                            <span class="badge bg-primary align-self-start mb-2"><?php echo htmlspecialchars(ucfirst($item['item_type'])); ?></span>
                            <h5 class="card-title"><?php echo htmlspecialchars($item['item_name']); ?></h5>
                            <p class="card-text text-muted small"><i class="bi bi-geo-alt-fill"></i> <?php echo htmlspecialchars($item['item_location']); ?></p>
                            <div class="mt-auto d-flex justify-content-between align-items-center">
                                <a href="../<?php echo $details_page; ?>?id=<?php echo $item['item_id']; ?>" class="btn btn-primary">View Details</a>
                                <button class="btn btn-link text-danger remove-wishlist-btn" 
                                        data-wishlist-id="<?php echo $item['wishlist_id']; ?>" 
                                        data-item-id="<?php echo $item['item_id']; ?>" 
                                        data-item-type="<?php echo $item['item_type']; ?>" 
                                        title="Remove from Wishlist">
                                    <i class="bi bi-trash-fill"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
            <div class="text-center p-5 border rounded">
                <h3 class="text-muted">Your Wishlist is Empty</h3>
                <p>Click the <i class="bi bi-heart-fill text-danger"></i> heart icon on any tour, service, or hotel to save it for later.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// JavaScript to handle removing items from the wishlist page without reloading
document.querySelectorAll('.remove-wishlist-btn').forEach(button => {
    button.addEventListener('click', function() {
        const btn = this;
        const wishlistId = btn.dataset.wishlistId;
        const itemId = btn.dataset.itemId;
        const itemType = btn.dataset.itemType;
        
        if (confirm('Are you sure you want to remove this from your wishlist?')) {
            fetch('/api/toggle_wishlist.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ item_id: itemId, item_type: itemType })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.action === 'removed') {
                    // Fade out and remove the card from the page
                    const cardToRemove = document.getElementById(`wishlist-item-${wishlistId}`);
                    if (cardToRemove) {
                        cardToRemove.style.transition = 'opacity 0.5s';
                        cardToRemove.style.opacity = '0';
                        setTimeout(() => cardToRemove.remove(), 500);
                    }
                }
            });
        }
    });
});
</script>

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