<?php 
include 'includes/header.php';

/* DB CONNECTION */
$conn = mysqli_connect("localhost","root","","ecommerce");
if(!$conn){ die("DB Error"); }

/* GET FILTERS */
$brands_selected     = $_GET['brand'] ?? [];
$categories_selected = $_GET['category'] ?? [];
$detection_selected  = $_GET['detection'] ?? [];
$tags_selected       = $_GET['tag'] ?? [];
$min_price = $_GET['min_price'] ?? '';
$max_price = $_GET['max_price'] ?? '';

/* Ensure arrays for multi-select */
$brands_selected = is_array($brands_selected) ? $brands_selected : [$brands_selected];
$categories_selected = is_array($categories_selected) ? $categories_selected : [$categories_selected];
$detection_selected = is_array($detection_selected) ? $detection_selected : [$detection_selected];
$tags_selected = is_array($tags_selected) ? $tags_selected : [$tags_selected];

/* WHERE CONDITION */
$where = "1";

if(!empty($brands_selected)){
    $brand_conditions = array_map(fn($b)=> "brand='$b'", $brands_selected);
    $where .= " AND (".implode(" OR ", $brand_conditions).")";
}

if(!empty($categories_selected)){
    $cat_conditions = array_map(fn($c)=> "FIND_IN_SET('$c', REPLACE(categories,'|',','))", $categories_selected);
    $where .= " AND (".implode(" OR ", $cat_conditions).")";
}

if(!empty($detection_selected)){
    $det_conditions = array_map(fn($d)=> "FIND_IN_SET('$d', REPLACE(detection_systems,'|',','))", $detection_selected);
    $where .= " AND (".implode(" OR ", $det_conditions).")";
}

if(!empty($tags_selected)){
    $tag_conditions = array_map(fn($t)=> "FIND_IN_SET('$t', REPLACE(tags,'|',','))", $tags_selected);
    $where .= " AND (".implode(" OR ", $tag_conditions).")";
}

if($min_price!='' && $max_price!=''){
    $where .= " AND price BETWEEN $min_price AND $max_price";
}

/* PRODUCTS */
$products = mysqli_query($conn,"SELECT * FROM products WHERE $where ORDER BY position ASC");


/* FILTER DATA */
$brands     = mysqli_query($conn,"SELECT DISTINCT brand FROM products");
$categories = mysqli_query($conn,"SELECT categories FROM products");
$detections = mysqli_query($conn,"SELECT detection_systems FROM products");
$tags = ['New Arrival','Best Seller','Deals'];

?>

<div class="container mt-4 mb-4">
<div class="row">

<!-- ================= LEFT FILTERS ================= -->
<div class="col-md-3">

<form id="filterForm" method="GET">

<div class="accordion" id="filterAccordion">

<!-- Categories -->
<div class="accordion-item">
    <h2 class="accordion-header" id="headingCategories">
        <button class="accordion-button <?= !empty($categories_selected) ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseCategories" aria-expanded="<?= !empty($categories_selected) ? 'true' : 'false' ?>" aria-controls="collapseCategories">
            Categories
        </button>
    </h2>
    <div id="collapseCategories" class="accordion-collapse collapse <?= !empty($categories_selected) ? 'show' : '' ?>" aria-labelledby="headingCategories">
        <div class="accordion-body">
            <?php
            $catArr=[];
            mysqli_data_seek($categories,0);
            while($c=mysqli_fetch_assoc($categories)){
                foreach(explode('|',$c['categories']) as $cat){
                    $catArr[trim($cat)] = 1;
                }
            }
            foreach(array_keys($catArr) as $cat){
            ?>
            <div class="form-check">
                <input class="form-check-input filter-checkbox" type="checkbox" name="category[]" value="<?= $cat ?>" <?= in_array($cat,$categories_selected)?'checked':'' ?>>
                <label class="form-check-label"><?= $cat ?></label>
            </div>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Brands -->
<div class="accordion-item">
    <h2 class="accordion-header" id="headingBrands">
        <button class="accordion-button <?= !empty($brands_selected) ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseBrands" aria-expanded="<?= !empty($brands_selected) ? 'true' : 'false' ?>" aria-controls="collapseBrands">
            Brands
        </button>
    </h2>
    <div id="collapseBrands" class="accordion-collapse collapse <?= !empty($brands_selected) ? 'show' : '' ?>" aria-labelledby="headingBrands">
        <div class="accordion-body">
            <?php
            mysqli_data_seek($brands,0);
            while($b=mysqli_fetch_assoc($brands)){
            ?>
            <div class="form-check">
                <input class="form-check-input filter-checkbox" type="checkbox" name="brand[]" value="<?= $b['brand'] ?>" <?= in_array($b['brand'],$brands_selected)?'checked':'' ?>>
                <label class="form-check-label"><?= $b['brand'] ?></label>
            </div>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Detection Systems -->
<div class="accordion-item">
    <h2 class="accordion-header" id="headingDetections">
        <button class="accordion-button <?= !empty($detection_selected) ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDetections" aria-expanded="<?= !empty($detection_selected) ? 'true' : 'false' ?>" aria-controls="collapseDetections">
            Detection Systems
        </button>
    </h2>
    <div id="collapseDetections" class="accordion-collapse collapse <?= !empty($detection_selected) ? 'show' : '' ?>" aria-labelledby="headingDetections">
        <div class="accordion-body">
            <?php
            $detArr=[];
            mysqli_data_seek($detections,0);
            while($d=mysqli_fetch_assoc($detections)){
                foreach(explode('|',$d['detection_systems']) as $dt){
                    $detArr[trim($dt)] = 1;
                }
            }
            foreach(array_keys($detArr) as $dt){
            ?>
            <div class="form-check">
                <input class="form-check-input filter-checkbox" type="checkbox" name="detection[]" value="<?= $dt ?>" <?= in_array($dt,$detection_selected)?'checked':'' ?>>
                <label class="form-check-label"><?= $dt ?></label>
            </div>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Tags -->
<div class="accordion-item">
    <h2 class="accordion-header" id="headingTags">
        <button class="accordion-button <?= !empty($tags_selected) ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTags" aria-expanded="<?= !empty($tags_selected) ? 'true' : 'false' ?>" aria-controls="collapseTags">
            Tags
        </button>
    </h2>
    <div id="collapseTags" class="accordion-collapse collapse <?= !empty($tags_selected) ? 'show' : '' ?>" aria-labelledby="headingTags">
        <div class="accordion-body">
            <?php foreach($tags as $t){ ?>
            <div class="form-check">
                <input class="form-check-input filter-checkbox" type="checkbox" name="tag[]" value="<?= $t ?>" <?= in_array($t,$tags_selected)?'checked':'' ?>>
                <label class="form-check-label"><?= ucfirst(str_replace('_',' ',$t)) ?></label>
            </div>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Price -->
<!-- <div class="accordion-item">
    <h2 class="accordion-header" id="headingPrice">
        <button class="accordion-button <?= ($min_price!='' || $max_price!='') ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePrice" aria-expanded="<?= ($min_price!='' || $max_price!='') ? 'true' : 'false' ?>" aria-controls="collapsePrice">
            Price
        </button>
    </h2>
    <div id="collapsePrice" class="accordion-collapse collapse <?= ($min_price!='' || $max_price!='') ? 'show' : '' ?>" aria-labelledby="headingPrice">
        <div class="accordion-body">
            <input type="number" name="min_price" class="form-control mb-2" placeholder="Min" value="<?= $min_price ?>">
            <input type="number" name="max_price" class="form-control mb-2" placeholder="Max" value="<?= $max_price ?>">
        </div>
    </div>
</div> -->

</div> 
<!-- accordion -->

</form>

</div>

<!-- ================= PRODUCTS ================= -->
<div class="col-md-9">
<div class="row" id="productsContainer">

<?php if(mysqli_num_rows($products)==0){ ?>
<p>No products found.</p>
<?php } ?>

<?php while($p=mysqli_fetch_assoc($products)){ ?>
<div class="col-md-4 mb-4">
<div class="card h-100">

<img src="uploads/products/<?= ltrim($p['main_image'], '/') ?>" class="card-img-top" style="height:200px;object-fit:cover">

<div class="card-body">
<h6><?= $p['product_name'] ?></h6>
<p class="mb-1">₹ <?= number_format($p['price'],2) ?></p>

<?php if(strpos($p['tags'],'Best Seller')!==false){ ?>
<span class="badge bg-success">Best Seller</span>
<?php } ?>

<?php if(strpos($p['tags'],'New Arrival')!==false){ ?>
<span class="badge bg-primary">New</span>
<?php } ?>

<?php if(strpos($p['tags'],'Deals')!==false){ ?>
<span class="badge bg-warning text-dark">Deal</span>
<?php } ?>


<div class="mt-2">
<a href="product-details.php?id=<?= $p['id'] ?>" class="btn btn-primary btn-sm">View</a>
<a href="checkout.php?product_id=<?= $p['id'] ?>" class="btn btn-success btn-sm">Buy</a>
</div>
</div>

</div>
</div>
<?php } ?>

</div>
</div>

</div>
</div>

<script>
// auto-submit when checkbox changes
document.querySelectorAll('.filter-checkbox').forEach(cb=>{
    cb.addEventListener('change',()=>{
        document.getElementById('filterForm').submit();
    });
});
</script>

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