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

// Get favorite products for logged in users
$favorite_product_ids = [];
if (isLoggedIn()) {
    $favorite_products = getFavoriteProducts($pdo, $_SESSION['user_id']);
    foreach ($favorite_products as $fav) {
        $favorite_product_ids[] = $fav['id'];
    }
}
?>

<div class="hero">
    <div class="container">
        <h1>Welcome to <?php echo SITE_NAME; ?></h1>
        <p>Your one-stop shop for all your needs</p>
        <a href="<?php echo SITE_URL; ?>/products/index.php" class="btn btn-primary btn-large">Shop Now</a>
    </div>
</div>

<div class="container">
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="message error">
            <?php echo htmlspecialchars($_SESSION['error_message']); ?>
            <?php unset($_SESSION['error_message']); ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="message success">
            <?php echo htmlspecialchars($_SESSION['success_message']); ?>
            <?php unset($_SESSION['success_message']); ?>
        </div>
    <?php endif; ?>
    
    <div class="section-title">
        <h2>Featured Products</h2>
    </div>
    
    <div class="products-grid">
        <?php 
        $all_products = getAllProducts($pdo);
        $featured_products = array_slice($all_products, 0, 4);
        foreach ($featured_products as $product): ?>
            <div class="product-card" data-product-id="<?php echo $product['id']; ?>">
                <div class="product-image">
                    <?php if (!empty($product['image'])): ?>
                        <img src="<?php echo SITE_URL . '/' . htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                    <?php else: ?>
                        <i class="fas fa-image" style="font-size: 3rem; color: #ccc;"></i>
                    <?php endif; ?>
                    <button class="favorite-btn <?php echo in_array($product['id'], $favorite_product_ids) ? 'active' : ''; ?>" data-product-id="<?php echo $product['id']; ?>">
                        <i class="fas fa-heart"></i>
                    </button>
                </div>
                <div class="product-info">
                    <h3><?php echo htmlspecialchars($product['name']); ?></h3>
                    <div class="product-price">$<?php echo number_format($product['price'], 2); ?></div>
                    <a href="<?php echo SITE_URL; ?>/products/view.php?id=<?php echo $product['id']; ?>" class="btn btn-primary btn-block">View Details</a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

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