<?php
// ========================================
// صفحه محصولات
// پروژه فروشگاه کیف‌لند
// ========================================

require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

$pageTitle = 'محصولات | کیف‌لند';
$settings = SiteSettings::getInstance();
$db = Database::getInstance()->getConnection();

Auth::trackVisit('products');

// فیلترها
$category_slug = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';
$min_price = $_GET['min_price'] ?? 0;
$max_price = $_GET['max_price'] ?? 100000000;
$sort = $_GET['sort'] ?? 'newest';
$page = $_GET['page'] ?? 1;
$per_page = 12;

// ساخت کوئری
$sql = "SELECT p.*, c.name as category_name, c.slug as category_slug 
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE p.is_active = 1";
$params = [];

// فیلتر دسته‌بندی
if($category_slug) {
    $sql .= " AND c.slug = ?";
    $params[] = $category_slug;
}

// جستجو
if($search) {
    $sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// فیلتر قیمت
$sql .= " AND p.price BETWEEN ? AND ?";
$params[] = $min_price;
$params[] = $max_price;

// مرتب‌سازی
switch($sort) {
    case 'price_asc': $sql .= " ORDER BY p.price ASC"; break;
    case 'price_desc': $sql .= " ORDER BY p.price DESC"; break;
    case 'popular': $sql .= " ORDER BY p.view_count DESC"; break;
    case 'rating': $sql .= " ORDER BY p.rating_avg DESC"; break;
    default: $sql .= " ORDER BY p.created_at DESC";
}

// شمارش کل محصولات
$count_sql = str_replace('p.*, c.name as category_name, c.slug as category_slug', 'COUNT(*)', $sql);
$stmt = $db->prepare($count_sql);
$stmt->execute($params);
$total_products = $stmt->fetchColumn();

// صفحه‌بندی
$total_pages = ceil($total_products / $per_page);
$page = max(1, min($page, $total_pages));
$offset = ($page - 1) * $per_page;

$sql .= " LIMIT $per_page OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();

// دسته‌بندی‌ها برای فیلتر
$categories = $db->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY sort_order")->fetchAll();

// دسته‌بندی فعلی
$current_category = null;
if($category_slug) {
    $stmt = $db->prepare("SELECT * FROM categories WHERE slug = ?");
    $stmt->execute([$category_slug]);
    $current_category = $stmt->fetch();
}

include 'includes/header.php';
?>

<section class="products-page">
    <div class="page-header">
        <h1><?= $current_category ? htmlspecialchars($current_category['name']) : 'همه محصولات' ?></h1>
        <?php if($current_category && $current_category['description']): ?>
        <p><?= htmlspecialchars($current_category['description']) ?></p>
        <?php endif; ?>
    </div>
    
    <div class="products-layout">
        <!-- سایدبار فیلتر -->
        <aside class="filter-sidebar">
            <div class="filter-section">
                <h3><i class="fas fa-filter"></i> فیلترها</h3>
                
                <form method="GET" class="filter-form">
                    <?php if($category_slug): ?>
                    <input type="hidden" name="category" value="<?= htmlspecialchars($category_slug) ?>">
                    <?php endif; ?>
                    
                    <div class="filter-group">
                        <label>جستجو</label>
                        <input type="text" name="search" placeholder="نام محصول..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label>محدوده قیمت</label>
                        <div style="display: flex; gap: 10px;">
                            <input type="number" name="min_price" placeholder="از" value="<?= $min_price ?>" min="0">
                            <input type="number" name="max_price" placeholder="تا" value="<?= $max_price ?>" min="0">
                        </div>
                    </div>
                    
                    <div class="filter-group">
                        <label>مرتب‌سازی</label>
                        <select name="sort">
                            <option value="newest" <?= $sort == 'newest' ? 'selected' : '' ?>>جدیدترین</option>
                            <option value="price_asc" <?= $sort == 'price_asc' ? 'selected' : '' ?>>ارزان‌ترین</option>
                            <option value="price_desc" <?= $sort == 'price_desc' ? 'selected' : '' ?>>گران‌ترین</option>
                            <option value="popular" <?= $sort == 'popular' ? 'selected' : '' ?>>محبوب‌ترین</option>
                            <option value="rating" <?= $sort == 'rating' ? 'selected' : '' ?>>بالاترین امتیاز</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fas fa-search"></i>
                        اعمال فیلتر
                    </button>
                    <a href="products.php<?= $category_slug ? '?category=' . $category_slug : '' ?>" class="btn btn-outline btn-block">
                        <i class="fas fa-redo"></i>
                        حذف فیلتر
                    </a>
                </form>
            </div>
            
            <div class="filter-section">
                <h3><i class="fas fa-tags"></i> دسته‌بندی‌ها</h3>
                <ul class="category-list">
                    <li>
                        <a href="products.php" class="<?= !$category_slug ? 'active' : '' ?>">
                            همه محصولات
                            <span>(<?= getProductCount() ?>)</span>
                        </a>
                    </li>
                    <?php foreach($categories as $cat): ?>
                    <li>
                        <a href="products.php?category=<?= $cat['slug'] ?>" class="<?= $category_slug == $cat['slug'] ? 'active' : '' ?>">
                            <?= htmlspecialchars($cat['name']) ?>
                            <span>(<?= getCategoryCount($cat['id']) ?>)</span>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </aside>
        
        <!-- لیست محصولات -->
        <main class="products-main">
            <div class="products-header">
                <p class="results-count"><?= $total_products ?> محصول یافت شد</p>
                <div class="view-toggle">
                    <button class="active"><i class="fas fa-th-large"></i></button>
                    <button><i class="fas fa-list"></i></button>
                </div>
            </div>
            
            <?php if(count($products) > 0): ?>
            <div class="product-grid">
                <?php foreach($products as $product): ?>
                <div class="product-card">
                    <?php if($product['discount_price']): ?>
                    <span class="badge badge-danger">
                        <?= round((($product['price'] - $product['discount_price']) / $product['price']) * 100) ?>٪ تخفیف
                    </span>
                    <?php endif; ?>
                    
                    <?php if($product['stock'] < 10 && $product['stock'] > 0): ?>
                    <span class="badge badge-warning" style="top: 40px;">موجودی محدود</span>
                    <?php elseif($product['stock'] == 0): ?>
                    <span class="badge badge-danger" style="top: 40px;">ناموجود</span>
                    <?php endif; ?>
                    
                    <a href="product-detail.php?id=<?= $product['id'] ?>" class="product-image">
                        <img src="uploads/products/<?= $product['image'] ?>" 
                             alt="<?= htmlspecialchars($product['name']) ?>" 
                             onerror="this.src='assets/images/no-image.svg'">
                    </a>
                    
                    <div class="product-info">
                        <span class="product-category">
                            <a href="products.php?category=<?= $product['category_slug'] ?>">
                                <?= htmlspecialchars($product['category_name']) ?>
                            </a>
                        </span>
                        <h3 class="product-title">
                            <a href="product-detail.php?id=<?= $product['id'] ?>">
                                <?= htmlspecialchars($product['name']) ?>
                            </a>
                        </h3>
                        
                        <?php if($product['rating_avg'] > 0): ?>
                        <div class="product-rating">
                            <?php for($i = 1; $i <= 5; $i++): ?>
                            <i class="fas fa-star" style="color: <?= $i <= round($product['rating_avg']) ? '#ffc107' : '#e0e0e0' ?>"></i>
                            <?php endfor; ?>
                            <span>(<?= $product['rating_count'] ?>)</span>
                        </div>
                        <?php endif; ?>
                        
                        <div class="product-price">
                            <div>
                                <?php if($product['discount_price']): ?>
                                <span class="old-price"><?= formatPrice($product['price']) ?></span>
                                <span class="price"><?= formatPrice($product['discount_price']) ?></span>
                                <?php else: ?>
                                <span class="price"><?= formatPrice($product['price']) ?></span>
                                <?php endif; ?>
                            </div>
                            <button class="btn-add-cart" onclick="addToCart(<?= $product['id'] ?>)" <?= $product['stock'] == 0 ? 'disabled' : '' ?>>
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <!-- صفحه‌بندی -->
            <?php if($total_pages > 1): ?>
            <div class="pagination">
                <?php if($page > 1): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" class="btn btn-outline">
                    <i class="fas fa-chevron-right"></i>
                </a>
                <?php endif; ?>
                
                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" 
                   class="btn <?= $i == $page ? 'btn-primary' : 'btn-outline' ?>">
                    <?= $i ?>
                </a>
                <?php endfor; ?>
                
                <?php if($page < $total_pages): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" class="btn btn-outline">
                    <i class="fas fa-chevron-left"></i>
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <?php else: ?>
            <div class="no-products">
                <i class="fas fa-box-open"></i>
                <h3>محصولی یافت نشد</h3>
                <p>متاسفانه محصولی با این مشخصات پیدا نشد</p>
                <a href="products.php" class="btn btn-primary">مشاهده همه محصولات</a>
            </div>
            <?php endif; ?>
        </main>
    </div>
</section>

<style>
.products-page { padding: 40px 5%; min-height: 80vh; }
.page-header { text-align: center; margin-bottom: 40px; }
.page-header h1 { font-size: 2.5rem; margin-bottom: 10px; }
.page-header p { color: var(--text-secondary); }
.products-layout { display: grid; grid-template-columns: 280px 1fr; gap: 30px; }
.filter-sidebar { background: var(--bg-card); padding: 20px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); height: fit-content; position: sticky; top: 100px; }
.filter-section { margin-bottom: 30px; padding-bottom: 30px; border-bottom: 1px solid var(--border-color); }
.filter-section h3 { font-size: 1.1rem; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
.filter-form { display: flex; flex-direction: column; gap: 20px; }
.filter-group { display: flex; flex-direction: column; gap: 8px; }
.filter-group label { font-size: 0.9rem; color: var(--text-secondary); }
.filter-group input, .filter-group select { padding: 10px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-secondary); color: var(--text-primary); }
.category-list { list-style: none; }
.category-list li { margin-bottom: 10px; }
.category-list a { display: flex; justify-content: space-between; padding: 10px; border-radius: var(--radius-sm); color: var(--text-secondary); transition: 0.3s; }
.category-list a:hover, .category-list a.active { background: rgba(16, 185, 129, 0.1); color: var(--primary); }
.category-list span { background: var(--bg-secondary); padding: 2px 10px; border-radius: 10px; font-size: 0.8rem; }
.products-main { min-width: 0; }
.products-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.results-count { color: var(--text-secondary); }
.view-toggle { display: flex; gap: 10px; }
.view-toggle button { padding: 10px; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: var(--radius-sm); color: var(--text-secondary); cursor: pointer; }
.view-toggle button.active { background: var(--primary); color: #fff; border-color: var(--primary); }
.no-products { text-align: center; padding: 80px 20px; }
.no-products i { font-size: 5rem; color: var(--text-secondary); margin-bottom: 20px; }
.no-products h3 { font-size: 1.5rem; margin-bottom: 10px; }
.no-products p { color: var(--text-secondary); margin-bottom: 20px; }
@media (max-width: 1024px) {
    .products-layout { grid-template-columns: 1fr; }
    .filter-sidebar { position: static; }
}
</style>

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