<?php
require_once 'includes/db.php';
$page_title = 'Store';
require_once 'includes/header.php';

$categories = [];
try {
    $stmt_cats = $pdo->query("SELECT * FROM categories ORDER BY name ASC");
    if ($stmt_cats) {
        $categories = $stmt_cats->fetchAll();
    }
} catch (Exception $e) {}

$cat_param = isset($_GET['category']) ? trim($_GET['category']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$cat_id = 0;
if(!empty($cat_param)){
    foreach($categories as $c) {
        $c_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $c['name'])));
        if($c_slug === $cat_param || (string)$c['id'] === $cat_param) {
            $cat_id = $c['id'];
            break;
        }
    }
}

$products = [];
try {
    if (!empty($search)) {
        $stmt_prods = $pdo->prepare("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.status = 'active' AND (p.title LIKE ? OR p.description LIKE ? OR p.meta_keywords LIKE ?) ORDER BY p.id DESC");
        $search_term = "%$search%";
        $stmt_prods->execute([$search_term, $search_term, $search_term]);
    } elseif ($cat_id > 0) {
        $stmt_prods = $pdo->prepare("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.status = 'active' AND p.category_id = ? ORDER BY p.id DESC");
        $stmt_prods->execute([$cat_id]);
    } else {
        $stmt_prods = $pdo->query("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.status = 'active' ORDER BY p.id DESC");
    }
    
    if ($stmt_prods) {
        $products = $stmt_prods->fetchAll();
    }
} catch (Exception $e) {}

$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳';
if (is_numeric($currency)) {
    $currency = '৳';
}
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    .store-container {
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
        box-sizing: border-box;
    }

    h1, h2, h3, .product-title {
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
    }

    .category-box, .product-card, .info-card {
        box-shadow: none !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 8px !important;
        transition: all 0.3s ease-in-out !important;
        background: #ffffff !important;
    }
    
    .product-card {
        position: relative !important;
        display: flex;
        flex-direction: column;
        padding: 12px;
        text-decoration: none;
        overflow: hidden;
        height: auto;
    }
    
    .category-box:hover, .product-card:hover, .info-card:hover {
        transform: translateY(-2px) !important;
        border-color: #94a3b8 !important;
        background: #f8fafc !important;
    }
    
    .btn-buy {
        border-radius: 4px !important;
        box-shadow: none !important;
        transition: background 0.3s ease, color 0.3s ease !important;
        border: 1px solid transparent !important;
        background: #00059E !important;
        color: #ffffff !important;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        text-decoration: none;
        padding: 10px;
        margin-top: auto;
        font-weight: 500;
        font-family: 'Roboto', sans-serif !important;
    }
    
    .btn-buy:hover {
        background: #00037a !important;
        color: #ffffff !important;
    }

    .product-img {
        width: calc(100% + 24px);
        aspect-ratio: 1 / 1;
        height: auto !important;
        object-fit: cover !important; 
        background-color: #f1f5f9; 
        border-bottom: 1px solid #f1f5f9 !important;
        border-radius: 0 !important;
        transition: opacity 0.3s ease !important;
        margin: -12px -12px 10px -12px;
        padding: 0;
        box-sizing: border-box;
    }
    
    .product-card:hover .product-img {
        opacity: 0.9 !important;
    }

    .product-category-label {
        font-size: 0.75rem;
        color: #64748b;
        margin-bottom: 4px;
        text-transform: uppercase;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    .product-title {
        font-size: 1.1rem;
        color: #0f172a;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        font-weight: 700;
    }

    .product-price {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        font-family: 'Roboto', sans-serif !important;
    }

    .old-price {
        font-size: 0.8rem;
        color: #94a3b8;
        text-decoration: line-through;
        font-weight: 600;
    }

    .new-price {
        font-size: 1.15rem;
        font-weight: 800;
        color: #00059E;
    }
    
    .sale-badge {
        position: absolute !important;
        top: 10px !important;
        right: 10px !important;
        border-radius: 50% !important;
        box-shadow: none !important;
        background: #84cc16 !important;
        color: #fff !important;
        width: 40px !important;
        height: 40px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        font-size: 0.75rem !important;
        font-weight: 800 !important;
        z-index: 2 !important;
        font-family: 'Roboto', sans-serif !important;
    }

    .category-pill {
        padding: 6px 16px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
        white-space: nowrap;
        transition: 0.3s;
        text-decoration: none;
        font-family: 'Roboto', sans-serif !important;
    }

    .category-pill.active {
        background: #00059E;
        color: white;
    }

    .category-pill.inactive {
        background: #e2e8f0;
        color: #0f172a;
    }

    .category-pill.inactive:hover {
        background: #cbd5e1;
    }

    .product-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        margin-bottom: 30px;
    }
    
    @media (min-width: 768px) {
        .product-grid { grid-template-columns: repeat(3, 1fr); gap: 20px; }
    }
    
    @media (min-width: 1024px) {
        .product-grid { grid-template-columns: repeat(4, 1fr); }
    }
</style>

<div class="store-container" style="margin-top: 25px; margin-bottom: 80px;">
    
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h1 style="color: #00059E; font-size: 1.5rem; font-weight: 700; margin: 0;">
            <?php echo !empty($search) ? 'Search Results' : 'All Products'; ?>
        </h1>
        <span style="font-size: 0.85rem; color: #64748b; font-weight: 600; font-family: 'Roboto', sans-serif;"><?php echo count($products); ?> Items Found</span>
    </div>

    <div style="display: flex; gap: 10px; overflow-x: auto; padding-bottom: 15px; margin-bottom: 20px; scrollbar-width: none; -ms-overflow-style: none; width: 100%;">
        <style>
            .store-container > div::-webkit-scrollbar {
                display: none;
            }
        </style>
        <a href="/products" class="category-pill <?php echo ($cat_id == 0 && empty($search)) ? 'active' : 'inactive'; ?>">
            All
        </a>
        <?php foreach($categories as $c): 
            $c_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $c['name'])));
        ?>
            <a href="/products/category/<?php echo urlencode($c_slug); ?>" class="category-pill <?php echo $cat_id == $c['id'] ? 'active' : 'inactive'; ?>">
                <?php echo htmlspecialchars($c['name']); ?>
            </a>
        <?php endforeach; ?>
    </div>
    
    <?php if(count($products) > 0): ?>
        <div class="product-grid">
            <?php foreach($products as $prod): 
                $cat_name = !empty($prod['category_name']) ? $prod['category_name'] : 'Uncategorized';
                $cat_slug_url = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $cat_name)));
                $product_url = "/product/" . urlencode($cat_slug_url) . "/" . urlencode($prod['slug']);
            ?>
                <div class="product-card">
                    
                    <?php if($prod['old_price'] > 0 && $prod['old_price'] > $prod['price']): ?>
                        <?php $discount_pct = round((($prod['old_price'] - $prod['price']) / $prod['old_price']) * 100); ?>
                        <span class="sale-badge">-<?php echo $discount_pct; ?>%</span>
                    <?php endif; ?>
                    
                    <img src="<?php echo get_image_url('products/images', $prod['main_image']); ?>" alt="Product" class="product-img" loading="lazy">
                    
                    <div class="product-category-label"><?php echo htmlspecialchars($cat_name); ?></div>
                    <div class="product-title"><?php echo htmlspecialchars($prod['title']); ?></div>
                    
                    <div class="product-price">
                        <?php if($prod['old_price'] > 0 && $prod['old_price'] > $prod['price']): ?>
                            <span class="old-price"><?php echo $currency . number_format($prod['old_price'], 2); ?></span>
                        <?php endif; ?>
                        <span class="new-price"><?php echo $currency . number_format($prod['price'], 2); ?></span>
                    </div>
                    
                    <a href="<?php echo $product_url; ?>" class="btn-buy">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                        Buy Now
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div style="text-align: center; padding: 50px 20px; background: white; border-radius: 8px; border: 1px solid #e2e8f0;">
            <svg style="width: 50px; height: 50px; color: #cbd5e1; margin-bottom: 15px; margin-left: auto; margin-right: auto; display: block;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" /></svg>
            <h3 style="color: #0f172a; margin-bottom: 5px; font-weight: 700;">No Products Found</h3>
            <p style="color: #64748b; font-size: 0.9rem; font-family: 'Roboto', sans-serif;">Check back later or try a different search term.</p>
        </div>
    <?php endif; ?>

</div>

<?php require_once 'includes/footer.php'; ?>
<?php require_once 'includes/mobile-nav.php'; ?>
