<?php
session_start();
require 'config/db.php';
require_once 'includes/functions.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit();
}

$user_id = $_SESSION['user_id'];

// Fetch Wishlist Items
$stmt = $pdo->prepare("
    SELECT w.id as wid, p.* FROM wishlist w 
    JOIN products p ON w.product_id = p.id 
    WHERE w.user_id = ? 
    ORDER BY w.created_at DESC
");
$stmt->execute([$user_id]);
$wishlist = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container" style="padding-top: 40px; min-height: 70vh;">
    <h1>My Wishlist ❤️</h1>
    
    <?php if(empty($wishlist)): ?>
        <div style="text-align: center; padding: 50px;">
            <i class="far fa-heart" style="font-size: 50px; color: #ddd;"></i>
            <p style="color: #666;">Your wishlist is empty.</p>
            <a href="index.php" class="btn btn-primary" style="width: auto; display: inline-block;">Browse Shop</a>
        </div>
    <?php else: ?>
        <div class="product-grid" style="margin-top: 30px;">
            <?php foreach ($wishlist as $product): 
                // Get Price
                $pStmt = $pdo->prepare("SELECT MIN(price) as min_price FROM product_variants WHERE product_id = ?");
                $pStmt->execute([$product['id']]);
                $price = $pStmt->fetchColumn() ?: 0;
            ?>
                <div class="card">
                    <a href="product.php?id=<?php echo $product['id']; ?>">
                        <img src="<?php echo $product['thumbnail_url']; ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                    </a>
                    <h3><?php echo htmlspecialchars($product['name']); ?></h3>
                    
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
                        <span class="price" style="font-size: 18px; color: #2c3e50; font-weight: bold;">
                            <?php echo convertPrice($price); ?>
                        </span>
                        
                        <a href="wishlist_action.php?remove=<?php echo $product['wid']; ?>" 
                           style="color: #e74c3c; font-size: 14px; text-decoration: none;"
                           onclick="return confirm('Remove from wishlist?')">
                           <i class="fas fa-trash"></i> Remove
                        </a>
                    </div>

                    <a href="product.php?id=<?php echo $product['id']; ?>" class="btn-view">Buy Now</a>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ?>