<?php
/**
 * Products Page — Category → Sub-category → Brand → Product Filtering
 * Path: products.php
 */
include_once 'header.php';

$filter_cat  = intval($_GET['cat'] ?? 0);
$filter_sub  = intval($_GET['sub'] ?? 0);
$filter_comp = intval($_GET['comp'] ?? 0);

$categories    = get_categories();
$subcategories = $filter_cat ? get_subcategories($filter_cat) : [];
$companies     = $filter_sub ? get_companies_by_subcategory($filter_sub) : ($filter_cat ? get_companies_by_category($filter_cat) : []);

if ($filter_cat || $filter_sub || $filter_comp) {
    $products = get_products_filtered($filter_cat ?: null, $filter_comp ?: null, 0, $filter_sub ?: null);
} else {
    $products = [];
    foreach ($categories as $cat) {
        $items = get_products_filtered($cat['id'], null, 6);
        $products = array_merge($products, $items);
    }
}

$active_cat_name = '';
$active_sub_name = '';
$active_comp_name = '';

foreach ($categories as $c) {
    if ($c['id'] == $filter_cat) { $active_cat_name = $c['name']; break; }
}
foreach ($subcategories as $s) {
    if ($s['id'] == $filter_sub) { $active_sub_name = $s['name']; break; }
}
if ($filter_sub && !$active_sub_name) {
    $sub_row = get_subcategory_by_id($filter_sub);
    if ($sub_row) $active_sub_name = $sub_row['name'];
}
foreach ($companies as $co) {
    if ($co['id'] == $filter_comp) { $active_comp_name = $co['name']; break; }
}
if ($filter_comp && !$active_comp_name) {
    $comp_row = get_company_by_id($filter_comp);
    if ($comp_row) $active_comp_name = $comp_row['name'];
}

$active_company = $filter_comp ? get_company_by_id($filter_comp) : null;

function filter_url($cat = 0, $sub = 0, $comp = 0) {
    $params = [];
    if ($cat)  $params['cat']  = $cat;
    if ($sub)  $params['sub']  = $sub;
    if ($comp) $params['comp'] = $comp;
    return 'products.php' . ($params ? '?' . http_build_query($params) : '');
}
?>

<section class="relative bg-gradient-to-r from-slate-950 to-blue-900 text-white py-14 md:py-20">
    <div class="max-w-7xl mx-auto px-4 text-center">
        <nav class="text-xs text-sky-400 font-bold uppercase mb-3">
            <a href="index.php" class="hover:text-white">Home</a> <span class="mx-2">/</span> Products
        </nav>
        <h1 class="text-3xl md:text-5xl font-black uppercase">Our Engineered Products</h1>
        <div class="w-16 h-1 bg-secondary mx-auto mt-4"></div>
        <p class="text-gray-300 text-sm max-w-lg mx-auto mt-4">ক্যাটাগরি → সাব-ক্যাটাগরি → ব্র্যান্ড → প্রডাক্ট</p>
    </div>
</section>

<section class="py-10 bg-white border-b border-gray-100 shadow-sm">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-4">
        <!-- Step 1: Categories -->
        <div>
            <p class="text-[10px] font-black uppercase text-gray-400 tracking-wider mb-3">Step 1 — Category</p>
            <div class="flex gap-2 overflow-x-auto pb-2">
                <a href="products.php" class="flex-shrink-0 px-4 py-2 rounded-full text-xs font-bold uppercase transition-all <?php echo !$filter_cat ? 'bg-primary text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-blue-50 hover:text-primary'; ?>">
                    All
                </a>
                <?php foreach ($categories as $cat): ?>
                <a href="<?php echo filter_url($cat['id']); ?>"
                    class="flex-shrink-0 px-4 py-2.5 rounded-full text-xs font-bold uppercase transition-all flex items-center gap-2 <?php echo ($filter_cat == $cat['id']) ? 'bg-primary text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-blue-50 hover:text-primary'; ?>">
                    <i class="fa-solid <?php echo htmlspecialchars($cat['icon'] ?? 'fa-box'); ?>"></i>
                    <?php echo htmlspecialchars($cat['name']); ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Step 2: Sub-categories -->
        <?php if ($filter_cat && !empty($subcategories)): ?>
        <div class="pt-4 border-t border-gray-100">
            <p class="text-[10px] font-black uppercase text-gray-400 tracking-wider mb-3">Step 2 — Sub-category</p>
            <div class="flex gap-2 flex-wrap">
                <a href="<?php echo filter_url($filter_cat); ?>"
                    class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all <?php echo !$filter_sub ? 'bg-secondary text-white' : 'bg-gray-100 text-gray-600 hover:bg-sky-50'; ?>">
                    All Sub-categories
                </a>
                <?php foreach ($subcategories as $sub): ?>
                <a href="<?php echo filter_url($filter_cat, $sub['id']); ?>"
                    class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all <?php echo ($filter_sub == $sub['id']) ? 'bg-secondary text-white' : 'bg-gray-100 text-gray-600 hover:bg-sky-50'; ?>">
                    <?php echo htmlspecialchars($sub['name']); ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Step 3: Brands -->
        <?php if (($filter_sub || $filter_cat) && !empty($companies)): ?>
        <div class="pt-4 border-t border-gray-100">
            <p class="text-[10px] font-black uppercase text-gray-400 tracking-wider mb-3">Step 3 — Brand</p>
            <div class="flex gap-2 flex-wrap">
                <a href="<?php echo filter_url($filter_cat, $filter_sub); ?>"
                    class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all <?php echo !$filter_comp ? 'bg-accent text-white' : 'bg-gray-100 text-gray-600 hover:bg-amber-50'; ?>">
                    All Brands
                </a>
                <?php foreach ($companies as $co): ?>
                <a href="<?php echo filter_url($filter_cat, $filter_sub, $co['id']); ?>"
                    class="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all <?php echo ($filter_comp == $co['id']) ? 'bg-accent text-white' : 'bg-gray-100 text-gray-600 hover:bg-amber-50'; ?>">
                    <?php echo htmlspecialchars($co['name']); ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<section class="py-12 md:py-16 bg-gray-50 min-h-[400px]">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        <?php if ($active_company && !empty($active_company['catalog_url'])): ?>
        <div class="mb-8 relative overflow-hidden rounded-2xl bg-gradient-to-r from-primary via-blue-800 to-blue-900 text-white p-6 md:p-8 shadow-lg">
            <div class="absolute right-0 top-0 opacity-10 text-8xl p-4 pointer-events-none"><i class="fa-solid fa-book-open"></i></div>
            <div class="relative z-10 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <p class="text-sky-200 text-xs font-bold uppercase tracking-wider mb-1">Official Catalog</p>
                    <h3 class="text-xl md:text-2xl font-black uppercase"><?php echo htmlspecialchars($active_company['name']); ?> Catalog দেখুন</h3>
                    <p class="text-sky-100/80 text-sm mt-1">সম্পূর্ণ প্রোডাক্ট ক্যাটালগ নতুন ট্যাবে খুলবে</p>
                </div>
                <a href="catalog.php?comp=<?php echo intval($active_company['id']); ?>" target="_blank" rel="noopener"
                   class="inline-flex items-center justify-center gap-2 bg-white text-primary hover:bg-secondary hover:text-white font-black text-xs uppercase px-6 py-3.5 rounded-xl transition-all shadow-md flex-shrink-0">
                    <i class="fa-solid fa-book-open"></i> View Catalog
                </a>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($filter_cat || $filter_sub || $filter_comp): ?>
        <div class="mb-8 flex items-center gap-2 flex-wrap">
            <span class="text-xs text-gray-500">Showing:</span>
            <?php if ($active_cat_name): ?>
            <span class="text-xs font-bold bg-primary/10 text-primary px-3 py-1 rounded-full"><?php echo htmlspecialchars($active_cat_name); ?></span>
            <?php endif; ?>
            <?php if ($active_sub_name): ?>
            <i class="fa-solid fa-chevron-right text-gray-300 text-xs"></i>
            <span class="text-xs font-bold bg-secondary/10 text-secondary px-3 py-1 rounded-full"><?php echo htmlspecialchars($active_sub_name); ?></span>
            <?php endif; ?>
            <?php if ($active_comp_name): ?>
            <i class="fa-solid fa-chevron-right text-gray-300 text-xs"></i>
            <span class="text-xs font-bold bg-accent/10 text-amber-700 px-3 py-1 rounded-full"><?php echo htmlspecialchars($active_comp_name); ?></span>
            <?php endif; ?>
            <span class="text-xs text-gray-400 ml-2">(<?php echo count($products); ?> products)</span>
        </div>
        <?php else: ?>
        <p class="text-sm text-gray-500 mb-8 text-center">ডিফল্ট: সব ক্যাটাগরির ৬টি করে প্রডাক্ট দেখানো হচ্ছে</p>
        <?php endif; ?>

        <?php if (empty($products)): ?>
        <div class="text-center py-20 bg-white rounded-3xl border border-gray-100">
            <i class="fa-solid fa-box-open text-4xl text-gray-200 mb-4 block"></i>
            <h3 class="font-bold text-gray-600 uppercase">No Products Found</h3>
            <a href="products.php" class="mt-4 inline-block text-secondary font-bold text-sm hover:underline">← View All Products</a>
        </div>
        <?php else: ?>

        <?php
        function render_product_card($product) {
            $img_src = $product['image_url'] ?: 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?w=600';
        ?>
        <div class="bg-white rounded-2xl overflow-hidden border border-gray-100 hover:shadow-xl hover:-translate-y-1 transition-all group flex flex-col">
            <div class="h-56 overflow-hidden bg-gray-200 relative">
                <img src="<?php echo htmlspecialchars($img_src); ?>" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" alt="">
                <?php if (!empty($product['company_name'])): ?>
                <span class="absolute top-3 left-3 bg-white/90 backdrop-blur text-[10px] font-bold text-primary px-2 py-1 rounded-full"><?php echo htmlspecialchars($product['company_name']); ?></span>
                <?php endif; ?>
            </div>
            <div class="p-5 flex-1 flex flex-col justify-between space-y-3">
                <div>
                    <h3 class="font-black text-primary uppercase text-sm group-hover:text-secondary transition-colors"><?php echo htmlspecialchars($product['title']); ?></h3>
                    <p class="text-xs text-gray-500 mt-2 line-clamp-2"><?php echo htmlspecialchars($product['description']); ?></p>
                </div>
                <a href="products-details.php?slug=<?php echo urlencode($product['slug']); ?>" class="text-secondary font-bold text-xs uppercase inline-flex items-center pt-3 border-t border-gray-100">
                    View Details <i class="fa-solid fa-arrow-right ml-2"></i>
                </a>
            </div>
        </div>
        <?php
        }

        if (!$filter_cat && !$filter_sub && !$filter_comp):
            $grouped = [];
            foreach ($products as $p) {
                $key = $p['category_name'] ?? 'Other';
                $grouped[$key][] = $p;
            }
            foreach ($grouped as $cat_name => $cat_products): ?>
        <div class="mb-12">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-lg font-black text-primary uppercase"><?php echo htmlspecialchars($cat_name); ?></h2>
                <?php
                $cat_id_for_link = 0;
                foreach ($categories as $c) { if ($c['name'] === $cat_name) { $cat_id_for_link = $c['id']; break; } }
                if ($cat_id_for_link): ?>
                <a href="<?php echo filter_url($cat_id_for_link); ?>" class="text-secondary text-xs font-bold hover:underline">View All →</a>
                <?php endif; ?>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($cat_products as $product) render_product_card($product); ?>
            </div>
        </div>
        <?php endforeach; else: ?>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($products as $product) render_product_card($product); ?>
        </div>
        <?php endif; endif; ?>
    </div>
</section>

<?php include_once 'footer.php'; ?>
