<?php
include "db.php";
include "header.php";

/* Fetch categories */
$categories = $pdo->query("SELECT * FROM categories ORDER BY category_name")->fetchAll();

/* Filters */
$cat_ids = $_GET['cat'] ?? []; 
// $sort variable is now irrelevant, but we keep its definition for URL purposes if needed later.
$sort = ""; // Removed sorting logic, default to empty sort parameter.

// Ensure $cat_ids is always an array
if (!is_array($cat_ids)) {
    $cat_ids = [$cat_ids];
}

/* Base query */
$sql = "
    SELECT p.*, c.category_name 
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE 1
";

/* Category filter */
$params = [];
if (!empty($cat_ids)) {
    // Create placeholders (?, ?, ...) for the IN clause
    $placeholders = implode(',', array_fill(0, count($cat_ids), '?'));
    $sql .= " AND p.category_id IN ($placeholders) ";
    $params = array_merge($params, $cat_ids);
}

/* Sorting: Removed price-based sorting. Default to ID descending. */
$sql .= " ORDER BY p.id DESC ";


$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Products</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">


<style>
/* Color Palette */
:root {
    --primary-color: #002344; /* Dark Blue */
    --secondary-color: #f4a261; /* A contrasting accent color (orange/copper) */
    --background-color: #f0f4f8; /* Light grayish-blue background */
    --card-background: #ffffff;
    --text-color-dark: #333333;
    --text-color-light: #ffffff;
    --border-color: #dddddd;
    --shadow-color: rgba(0, 0, 0, 0.08);
    --new-tag-bg: #ffe08a; /* Yellow for 'NEW' tag */
    --new-tag-text: #8c5d00;
    --sidebar-width: 250px;
    --card-min-width: 240px; /* Base card width */
    --grid-gap: 20px;
    /* (4 * 240px) + (3 * 20px gap) = 1020px */
    --max-grid-width: 1020px; 
}

body {
    font-family: 'Poppins', sans-serif;
    background: var(--background-color);
    margin: 0;
    padding: 0px;
    color: var(--text-color-dark);
}

h2 {
    color: var(--primary-color);
    font-weight: 700;
    margin-bottom: 20px;
    font-size: 28px;
}

/* --- MAIN LAYOUT (Sidebar + Content) --- */
.page-content-wrapper {
    display: flex;
    gap: var(--grid-gap);
    max-width: 1400px; 
    margin: 0 auto;
}

/* --- SIDEBAR (Category Filters) --- */
.sidebar {
    width: var(--sidebar-width);
    flex-shrink: 0;
}

.filter-box {
    background: var(--card-background);
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 15px var(--shadow-color);
    margin-bottom: 20px;
}

.filter-box h3 {
    color: var(--primary-color);
    font-size: 16px;
    font-weight: 600;
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
    margin-bottom: 15px;
}

.category-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.category-list label {
    display: flex;
    align-items: center;
    padding: 8px 0;
    font-size: 14px;
    cursor: pointer;
    transition: color 0.2s;
}

.category-list label:hover {
    color: var(--primary-color);
}

.category-list input[type="checkbox"] {
    appearance: none;
    width: 16px;
    height: 16px;
    border: 2px solid var(--primary-color);
    border-radius: 4px;
    margin-right: 10px;
    position: relative;
    cursor: pointer;
    transition: background-color 0.2s, border-color 0.2s;
    flex-shrink: 0;
}

.category-list input[type="checkbox"]:checked {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.category-list input[type="checkbox"]:checked::after {
    content: '\f00c'; 
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    color: white;
    font-size: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

/* --- PRODUCT CONTENT AREA --- */
.content-area {
    flex-grow: 1;
}

/* --- SORTING FORM CONTAINER (Now Empty) --- */
/* The .sort-box element is completely removed from the HTML, 
   so no need to change its CSS unless the margin is still desired.
   We will keep the margin on the content area to prevent the grid 
   from sitting too high. */
.grid-wrapper {
    margin-top: 0px; /* Adjusted to remove the space left by the sort box */
    display: flex;
    justify-content: center; /* Ensures the grid is centered in the content area */
}


/* --- PRODUCT GRID --- */
.grid {
    /* Max width set for 4 cards to prevent stretching on wide screens */
    max-width: var(--max-grid-width); 
    display: grid;
    
    /* Sets the max column width to the card's min width to prevent stretching 
       when there are only 1 or 2 items, forcing them to remain their normal size and be centered. */
    grid-template-columns: repeat(auto-fit, minmax(var(--card-min-width), var(--card-min-width)));
    
    gap: var(--grid-gap);
    width: 100%; 
}

/* --- PRODUCT CARD STYLES (Retained) --- */
.card {
    background: var(--card-background);
    border-radius: 12px;
    box-shadow: 0 4px 15px var(--shadow-color);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    transition: transform 0.3s, box-shadow 0.3s;
    position: relative;
    max-width: 100%; 
}

.card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.card-image-container {
    position: relative;
    width: 100%;
    height: 200px;
    overflow: hidden;
    background-color: #f8f8f8;
    display: flex;
    justify-content: center;
    align-items: center;
}

.card-image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.new-tag {
    position: absolute;
    top: 10px;
    left: 10px;
    background: var(--new-tag-bg);
    color: var(--new-tag-text);
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    z-index: 10;
}

.card-content {
    padding: 15px;
    display: flex;
    flex-direction: column;
    flex-grow: 1;
}

.title {
    font-weight: 600;
    font-size: 16px;
    color: var(--text-color-dark);
    margin-bottom: 5px;
}

.cat {
    font-size: 13px;
    color: #777;
    margin-bottom: 10px;
    line-height: 1.4;
    min-height: 36px;
}

.price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: auto;
    padding-top: 10px;
}

.price {
    font-size: 18px;
    font-weight: 700;
    color: var(--primary-color);
}

.rating {
    display: flex;
    align-items: center;
    gap: 4px;
    color: var(--secondary-color);
    font-size: 13px;
    font-weight: 500;
}
.rating i {
    color: var(--secondary-color);
}


.quick-shop-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--card-background);
    color: var(--primary-color);
    border: 1px solid var(--primary-color);
    padding: 8px 15px;
    border-radius: 8px;
    text-decoration: none;
    font-size: 14px;
    font-weight: 600;
    transition: background 0.3s, color 0.3s, border-color 0.3s;
    margin-top: 15px;
    width: 100%;
    box-sizing: border-box;
}

.quick-shop-btn i {
    margin-right: 8px;
}

.quick-shop-btn:hover {
    background: var(--primary-color);
    color: var(--text-color-light);
    box-shadow: 0 4px 10px rgba(0, 35, 68, 0.2);
}


/* Mobile adjustments */
@media (max-width: 900px) {
    .page-content-wrapper {
        flex-direction: column;
        gap: 0;
    }
    .sidebar {
        width: 100%;
        margin-bottom: 20px;
    }
    /* On smaller screens, we re-introduce 1fr to allow 2-column layout to fill space */
    .grid {
        max-width: 100%;
        grid-template-columns: repeat(auto-fit, minmax(var(--card-min-width), 1fr)); 
    }
    .grid-wrapper {
        justify-content: start; 
    }
}

@media (max-width: 500px) {
    .grid {
        grid-template-columns: 1fr; /* Single column on phones */
    }
}
</style>
</head>
<body>

<h2>🛒 Products</h2>

<div class="page-content-wrapper">

    <div class="sidebar">
        <form method="GET">
            <div class="filter-box">
                <h3>Filter by Category</h3>
                <ul class="category-list">
                    <li>
                        <label>
                            <input type="checkbox" name="cat[]" value="" onchange="window.location.href='products.php'" <?= empty($cat_ids) ? 'checked' : '' ?> style="display: none;"> 
                            <span onclick="window.location.href='products.php'" style="display:block; width:100%; font-weight:<?= empty($cat_ids) ? '600' : '400' ?>;">All Categories</span>
                        </label>
                    </li>
                    <?php foreach($categories as $c): ?>
                        <li>
                            <label>
                                <input type="checkbox" name="cat[]" value="<?= $c['id'] ?>" onchange="this.form.submit()" <?= in_array($c['id'], $cat_ids) ? 'checked' : '' ?>>
                                <?= htmlspecialchars($c['category_name']) ?>
                            </label>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </form>
    </div>

    <div class="content-area">
        
        <div class="grid-wrapper">
            <div class="grid">
            <?php 
            if (count($products) > 0) {
                foreach($products as $p): 
                    $images = json_decode($p['images'], true);
                    $img = (!empty($images) && is_array($images) ? ($images[0] ?? "noimage.jpg") : "noimage.jpg");
                    
                    $price_variants = json_decode($p['price_variants'], true);
                    $display_price = "N/A";
                    if (!empty($price_variants)) {
                        if (isset($price_variants['250g']['with'])) {
                            // Display the formatted price string
                            $display_price = "Rs. " . number_format($price_variants['250g']['with'], 2);
                        } elseif (is_array(reset($price_variants)) && isset(reset($price_variants)['with'])) {
                             $display_price = "Rs. " . number_format(reset($price_variants)['with'], 2);
                        }
                    }

                    $rating = rand(44, 50) / 10; 
                    $is_new = (rand(0, 1) == 1); 
            ?>
            <div class="card">
                <div class="card-image-container">
                    <img src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($p['product_name']) ?>">
                    <?php if ($is_new): ?>
                        <span class="new-tag">NEW</span>
                    <?php endif; ?>
                </div>
                <div class="card-content">
                    <div class="title"><?= htmlspecialchars($p['product_name']) ?></div>
                    <div class="cat"><?= htmlspecialchars($p['category_name']) ?></div> 
                    
                    <div class="price-row">
                        <div class="price"><?= $display_price ?></div>
                        <div class="rating">
                            <i class="fas fa-star"></i> <?= number_format($rating, 1) ?>
                        </div>
                    </div>
                    <a class="quick-shop-btn" href="product.php?id=<?= $p['id'] ?>">
                        <i class="fas fa-shopping-bag"></i> Quick Shop
                    </a>
                </div>
            </div>
            <?php 
                endforeach; 
            } else {
                echo "<p style='grid-column: 1 / -1; text-align: center; color: #555;'>No products found matching your criteria.</p>";
            }
            ?>
            </div>
        </div>

    </div>
</div>

</body>
</html>

<?php include "footer.php"; ?>