<?php include 'include/header.php'; ?>
<?php
include 'db.php';

// ================= FILTER LOGIC =================
$where = [];
$category_filter = $_GET['category'] ?? '';
$min_price = $_GET['min'] ?? '';
$max_price = $_GET['max'] ?? '';

// CATEGORY
if($category_filter){
    $where[] = "category_id = '".intval($category_filter)."'";
}

// PRICE
if($min_price){
    $where[] = "price >= '".intval($min_price)."'";
}
if($max_price){
    $where[] = "price <= '".intval($max_price)."'";
}

// FINAL QUERY
$whereSQL = count($where) ? "WHERE ".implode(" AND ", $where) : "";

// PRODUCTS
$result = $conn->query("
    SELECT p.*, 
    (SELECT image_name FROM product_images 
     WHERE product_id = p.id LIMIT 1) as hover_image
    FROM products p
    $whereSQL
    ORDER BY p.id DESC
");

// PRICE RANGE
$priceData = $conn->query("
    SELECT MIN(price) as min_price, MAX(price) as max_price FROM products
")->fetch_assoc();

// CATEGORY LIST
$categories = $conn->query("SELECT * FROM category");
?>

<div class="container py-5" style="background: #fffafa;">

    <div class="row">

        <!-- ================= LEFT FILTER ================= -->
        <div class="col-md-3 mt-5 mb-5">
            <div class="filter-card">
                <form method="GET" id="filterForm">

                    <p class="fw-bold">Filter:</p>
                    <div class="filter-box">
                        <div class="filter-title">Price</div>

                        <p style="font-size:13px;color:#777;">
                            Max Price: Rs. <?= $priceData['max_price'] ?>
                        </p>

                        <div class="d-flex gap-2">
                            <input type="number" name="min" placeholder="From"
                                value="<?= htmlspecialchars($min_price) ?>" class="form-control" onkeyup="autoSubmit()">

                            <input type="number" name="max" placeholder="To" value="<?= htmlspecialchars($max_price) ?>"
                                class="form-control" onkeyup="autoSubmit()">
                        </div>
                    </div>
                    <!-- CATEGORY -->
                    <div class="filter-box">
                        <div class="filter-title">Category</div>

                        <?php while($cat = $categories->fetch_assoc()): ?>
                        <div class="form-check">
                            <input type="radio" name="category" value="<?= $cat['id'] ?>"
                                <?= ($category_filter == $cat['id']) ? 'checked' : '' ?> onchange="autoSubmit()">
                            <label><?= $cat['cat_title'] ?></label>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- PRICE -->


                    <!-- RESET -->
                    <a href="?" class="btn btn-outline-secondary w-100 mt-2">Reset</a>

                </form>
            </div>
        </div>

        <!-- ================= PRODUCTS ================= -->
        <div class="col-md-9 mt-5 mb-5">
            <div class="row g-4">

                <?php if($result && $result->num_rows > 0): ?>
                <?php while($row = $result->fetch_assoc()): ?>

                <div class="col-md-4 col-6">
                    <div class="product-card">

                        <div class="product-image-box">

                            <a href="product/<?= $row['slug'] ?>">
                                <!-- MAIN IMAGE -->
                                <?php if(!empty($row['pro_image']) && file_exists("assets/images/products/".$row['pro_image'])): ?>
                                <img src="assets/images/products/<?= $row['pro_image'] ?>" class="main-img">
                                <?php else: ?>
                                <img src="https://via.placeholder.com/300x300" class="main-img">
                                <?php endif; ?>

                                <!-- HOVER IMAGE -->
                                <?php if(!empty($row['hover_image']) && file_exists("assets/images/products/gallery/".$row['hover_image'])): ?>
                                <img src="assets/images/products/gallery/<?= $row['hover_image'] ?>" class="hover-img">
                                <?php endif; ?>

                                <!-- DISCOUNT -->
                                <?php if(!empty($row['sale_price']) && $row['price'] > $row['sale_price']): ?>
                                <div class="sale-badge">
                                    Rs. <?= $row['price'] - $row['sale_price'] ?> off
                                </div>
                                <?php endif; ?>
                            </a>

                        </div>
                        <p class="mt-2">
                            <a href="product/<?= $row['slug'] ?>" style="text-decoration:none;color:black;">
                                <?= htmlspecialchars($row['pro_title']) ?>
                            </a>
                        </p>
                        <div>
                            <?php if(!empty($row['sale_price']) && $row['price'] > $row['sale_price']): ?>
                            <span class="old-price">Rs. <?= $row['price'] ?></span>
                            <span class="new-price"> Rs. <?= $row['sale_price'] ?></span>
                            <?php else: ?>
                            <span class="new-price">Rs. <?= $row['price'] ?></span>
                            <?php endif; ?>
                        </div>

                        <button class="cart-btn mt-2">Add to cart</button>

                    </div>
                </div>

                <?php endwhile; ?>
                <?php else: ?>
                <div class="col-12 text-center">
                    <p>No products found</p>
                </div>
                <?php endif; ?>

            </div>
        </div>

    </div>
</div>

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

<!-- ================= JS ================= -->
<script>
let timer;

function autoSubmit() {
    clearTimeout(timer);
    timer = setTimeout(() => {
        document.getElementById('filterForm').submit();
    }, 400);
}
</script>