<?php
/**
 * Tom's Java Jive - Customer Wishlist
 */

$pageTitle = "My Wishlist - Tom's Java Jive";
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

CustomerAuth::require();
$customer = CustomerAuth::getFullUser();
$currentPage = 'wishlist';

// Handle remove action
if (isset($_POST['remove_wishlist'])) {
    $productId = $_POST['product_id'] ?? '';
    db()->query(
        "DELETE FROM wishlist WHERE customer_id = :cid AND product_id = :pid",
        ['cid' => $customer['customer_id'], 'pid' => $productId]
    );
    setFlash('success', 'Item removed from wishlist');
    redirect('/account/wishlist.php');
}

// Get wishlist items with product details
$wishlistItems = db()->fetchAll(
    "SELECT w.*, p.product_id, p.name, p.price, p.sale_price, p.images, p.stock, p.is_active
     FROM wishlist w
     JOIN products p ON w.product_id = p.product_id
     WHERE w.customer_id = :id
     ORDER BY w.created_at DESC",
    ['id' => $customer['customer_id']]
);

$extraHead = '<link rel="stylesheet" href="/assets/css/account.css?v='. filemtime(__DIR__ . '/../assets/css/account.css') .'">';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<div class="account-header">
    <h1>My Wishlist</h1>
    <p class="text-muted"><?= count($wishlistItems) ?> items saved</p>
</div>

<?php if (hasFlash('success')): ?>
    <div class="alert alert-success mb-2">
        <i class="fas fa-check-circle"></i> <?= getFlash('success') ?>
    </div>
<?php endif; ?>

<?php if (empty($wishlistItems)): ?>
    <div class="section-card">
        <div class="section-card-body text-center" style="padding: 3rem;">
            <i class="fas fa-heart" style="font-size: 3rem; color: var(--color-text-muted); margin-bottom: 1rem;"></i>
            <h3>Your wishlist is empty</h3>
            <p class="text-muted">Save items you love by clicking the heart icon on products.</p>
            <a href="/shop.php" class="btn btn-primary mt-1">Browse Products</a>
        </div>
    </div>
<?php else: ?>
    <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 1.5rem;">
        <?php foreach ($wishlistItems as $item): 
            $images = json_decode($item['images'] ?? '[]', true);
            $imageUrl = !empty($images) ? $images[0] : '/assets/images/placeholder-product.svg';
            $isAvailable = $item['is_active'] && $item['stock'] > 0;
        ?>
            <div class="section-card" style="overflow: hidden;">
                <a href="/product.php?id=<?= htmlspecialchars($item['product_id']) ?>">
                    <img src="<?= htmlspecialchars($imageUrl) ?>" 
                         alt="<?= htmlspecialchars($item['name']) ?>"
                         style="width: 100%; height: 200px; object-fit: cover;"
                         onerror="this.src='/assets/images/placeholder-product.svg'">
                </a>
                <div class="section-card-body">
                    <h4 style="margin: 0 0 0.5rem;">
                        <a href="/product.php?id=<?= htmlspecialchars($item['product_id']) ?>" style="color: inherit;">
                            <?= htmlspecialchars($item['name']) ?>
                        </a>
                    </h4>
                    
                    <div style="margin-bottom: 1rem;">
                        <?php if ($item['sale_price']): ?>
                            <span style="font-size: 1.25rem; font-weight: 600; color: var(--color-primary);">
                                <?= formatCurrency($item['sale_price']) ?>
                            </span>
                            <span style="text-decoration: line-through; color: var(--color-text-muted); margin-left: 0.5rem;">
                                <?= formatCurrency($item['price']) ?>
                            </span>
                        <?php else: ?>
                            <span style="font-size: 1.25rem; font-weight: 600;">
                                <?= formatCurrency($item['price']) ?>
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!$isAvailable): ?>
                        <p style="color: var(--color-error); font-size: 0.875rem; margin-bottom: 1rem;">
                            <i class="fas fa-times-circle"></i> Out of stock
                        </p>
                    <?php endif; ?>
                    
                    <div style="display: flex; gap: 0.5rem;">
                        <?php if ($isAvailable): ?>
                            <button class="btn btn-primary" style="flex: 1;" onclick="addToCart('<?= $item['product_id'] ?>')">
                                <i class="fas fa-shopping-cart"></i> Add to Cart
                            </button>
                        <?php else: ?>
                            <button class="btn btn-secondary" style="flex: 1;" disabled>
                                <i class="fas fa-shopping-cart"></i> Unavailable
                            </button>
                        <?php endif; ?>
                        
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="product_id" value="<?= $item['product_id'] ?>">
                            <button type="submit" name="remove_wishlist" class="btn btn-danger" title="Remove">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<script>
function addToCart(productId) {
    fetch('/api/cart.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'add', product_id: productId, quantity: 1 })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Added to cart!');
            // Update cart count if exists
            const cartCount = document.querySelector('.cart-count');
            if (cartCount) {
                cartCount.textContent = data.cart_count || '';
            }
        } else {
            alert(data.error || 'Failed to add to cart');
        }
    });
}
</script>

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