<?php
require_once '../includes/config.php';
$pageTitle = "Produk";
include '../includes/header.php';

// Get category for filtering
$category_id = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

try {
    $conn = connectDB();
    
    // Get categories for filter menu
    $stmt = $conn->prepare("SELECT * FROM categories ORDER BY name");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Prepare query for products
    $query = "SELECT p.*, c.name as category_name FROM products p 
              LEFT JOIN categories c ON p.category_id = c.category_id 
              WHERE 1=1";
    $params = array();
    
    // Add category filter if selected
    if ($category_id > 0) {
        $query .= " AND p.category_id = :category_id";
        $params[':category_id'] = $category_id;
    }
    
    // Add search filter if provided
    if (!empty($search)) {
        $query .= " AND (p.name LIKE :search OR p.description LIKE :search)";
        $params[':search'] = "%$search%";
    }
    
    $query .= " ORDER BY p.name";
    
    $stmt = $conn->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Count total products
    $totalProducts = count($products);
    
    // Get category name for title if category filter is applied
    $categoryName = "";
    if ($category_id > 0) {
        foreach ($categories as $cat) {
            if ($cat['category_id'] == $category_id) {
                $categoryName = $cat['name'];
                break;
            }
        }
    }
    
    // Array of category icons (Font Awesome)
    $categoryIcons = [
        'Makanan Pokok' => 'fa-utensils',
        'Minuman' => 'fa-coffee',
        'Snack' => 'fa-cookie',
        'Kebutuhan Rumah Tangga' => 'fa-home',
        'Toiletries' => 'fa-soap'
    ];
    
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}
?>

<div class="container">
    <div class="products-header">
        <h1>
            <?php 
            if (!empty($categoryName)) {
                echo "Produk Kategori: " . $categoryName;
            } elseif (!empty($search)) {
                echo "Hasil Pencarian: " . $search;
            } else {
                echo "Semua Produk";
            }
            ?>
        </h1>
        
        <div class="product-filters">
            <div class="search-form">
                <form action="index.php" method="get">
                    <?php if ($category_id > 0): ?>
                    <input type="hidden" name="category" value="<?php echo $category_id; ?>">
                    <?php endif; ?>
                    <input type="text" name="search" placeholder="Cari produk..." value="<?php echo $search; ?>">
                    <button type="submit"><i class="fas fa-search"></i></button>
                </form>
            </div>
            
            <div class="category-filter">
                <a href="index.php" class="<?php echo ($category_id == 0) ? 'active' : ''; ?>">
                    <i class="fas fa-th-large"></i> Semua
                </a>
                <?php foreach ($categories as $category): 
                    $icon = $categoryIcons[$category['name']] ?? 'fa-tag';
                ?>
                    <a href="index.php?category=<?php echo $category['category_id']; ?>" 
                       class="<?php echo ($category_id == $category['category_id']) ? 'active' : ''; ?>">
                        <i class="fas <?php echo $icon; ?>"></i> <?php echo $category['name']; ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        
        <?php if ($totalProducts > 0): ?>
        <div class="product-counter">
            <span>Menampilkan <?php echo $totalProducts; ?> produk</span>
        </div>
        <?php endif; ?>
    </div>

    <?php if (isset($error)): ?>
        <div class="error">
            <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
        </div>
    <?php else: ?>
        <?php if (empty($products)): ?>
            <div class="no-products">
                <div class="empty-products-icon">
                    <i class="fas fa-box-open"></i>
                </div>
                <p>Tidak ada produk yang ditemukan.</p>
                <a href="index.php" class="btn"><i class="fas fa-redo"></i> Lihat Semua Produk</a>
            </div>
        <?php else: ?>
            <div class="products">
                <?php foreach ($products as $product): ?>
                    <div class="product-card">
                        <div class="product-img">
                            <?php if ($product['image_path']): ?>
                                <img src="<?php echo SITE_URL . $product['image_path']; ?>" alt="<?php echo $product['name']; ?>">
                            <?php else: ?>
                                <img src="<?php echo SITE_URL; ?>assets/img/no-image.jpg" alt="No Image">
                            <?php endif; ?>
                            
                            <?php if ($product['stock'] <= 5 && $product['stock'] > 0): ?>
                                <div class="product-badge">Stok Terbatas</div>
                            <?php elseif ($product['stock'] <= 0): ?>
                                <div class="product-badge" style="background-color: #f44336;">Stok Habis</div>
                            <?php endif; ?>
                        </div>
                        <div class="product-info">
                            <h3><?php echo $product['name']; ?></h3>
                            <div class="category">
                                <i class="fas <?php echo $categoryIcons[$product['category_name']] ?? 'fa-tag'; ?>"></i>
                                <?php echo $product['category_name']; ?>
                            </div>
                            <div class="price">Rp <?php echo number_format($product['price'], 0, ',', '.'); ?></div>
                            <a href="detail.php?id=<?php echo $product['product_id']; ?>" class="btn">
                                <i class="fas fa-eye"></i> Detail
                            </a>
                            <?php if ($product['stock'] > 0): ?>
                                <button class="add-to-cart btn" data-id="<?php echo $product['product_id']; ?>">
                                    <i class="fas fa-cart-plus"></i> Tambah ke Keranjang
                                </button>
                            <?php else: ?>
                                <button class="btn" disabled>
                                    <i class="fas fa-times-circle"></i> Stok Habis
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<style>
    .empty-products-icon {
        font-size: 60px;
        color: #ddd;
        margin-bottom: 20px;
    }
    
    .product-counter {
        text-align: center;
        margin: 10px 0 30px;
        color: var(--dark-gray);
        font-style: italic;
    }
</style>

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