<?php
$this->assign('title', 'Products');

$isAdmin   = $this->Identity?->get('role') === 'admin' || $this->Identity?->get('is_admin') === true;
$qParams   = $this->request->getQueryParams();
$category  = $category   ?? ($qParams['category']  ?? '');
$sort      = $sort       ?? ($qParams['sort']      ?? '');
$direction = strtolower($direction ?? ($qParams['direction'] ?? 'asc'));
$minQ      = ($min ?? '') !== '' ? $min : ($qParams['min'] ?? '');
$maxQ      = ($max ?? '') !== '' ? $max : ($qParams['max'] ?? '');
$searchVal = $searchTerm ?? ($qParams['q'] ?? '');
?>
<style>
@media (max-width:600px){
  .catalogue{padding:16px 12px}
  .header-line{flex-direction:column;align-items:flex-start;gap:12px}
  .search-wrap{width:100%}
  .sort-form{width:100%;flex-direction:column;align-items:flex-start;gap:8px;margin-top:8px}
  .sidebar{padding:12px}
  .sidebar h3{font-size:11px}
  .filter-group{margin-top:12px;padding-top:12px}
  .grid{gap:16px}
  .card .body{padding:10px 12px}
  .price{font-size:14px}
  .name{font-size:14px}
  .paginator a, .paginator span{padding:6px 8px;font-size:13px}
  .search-wrap input{padding:8px 32px 8px 10px}
  .search-wrap button, .filter-group button{padding:6px 8px}
  #priceRange{width:100%}
}

:root{--bg:#f5efe3;--card:#fff;--ink:#2c231b;--muted:#8f8478;--pill:#efe7d9;--shadow:0 8px 24px rgba(0,0,0,.06)}
body{background:var(--bg)}
.ffont {
  font-family: 'Playfair Display', serif;
}
.catalogue{max-width:1200px;margin:0 auto;padding:32px 24px}
.header-line{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:16px}
.title{font:700 34px/1.1 "Playfair Display",serif;color:var(--ink);margin:0}
.row{display:grid;grid-template-columns:260px 1fr;gap:32px}
.paginator {
  display: flex;
  gap: 8px;
  margin-top: 24px;
  flex-wrap: wrap;
  list-style: none; /* Add this */
  padding: 0; /* Add this to remove default padding */
}
.sidebar{background:#f7f2e9;border-radius:12px;padding:16px}
.sidebar h3{font:600 12px/1 Inter,system-ui;letter-spacing:.08em;color:#6b5d4a;margin:10px 0}
.sidebar a{display:block;padding:8px 10px;border-radius:8px;text-decoration:none;color:#3a2f26}
.sidebar a.active{background:var(--pill);font-weight:600}
.filter-group{margin-top:16px;border-top:1px solid #eadfcd;padding-top:16px}
.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:32px}
.card{background:var(--card);border-radius:16px;box-shadow:var(--shadow);overflow:hidden}
.media{width:100%;aspect-ratio:1/1;background:#fff;display:flex;align-items:center;justify-content:center}
.media img{max-width:85%;max-height:85%;object-fit:contain;object-position:center;display:block;margin:0 auto;margin-top:30px}
.media a{display:flex;align-items: center;justify-content: center;width: 100%;height: 100%;padding:0;border-radius:8px;text-decoration:none;color:#3a2f26;}
.media a img {max-width:85%;max-height:85%;object-fit:contain;object-position:center;display: block;border-radius: 8px}
.body{padding:14px 16px}
.badge{display:inline-block;background:#f4efe7;color:#8a6f4e;font-size:12px;padding:4px 8px;border-radius:999px;margin:12px 0 0 12px;position:absolute}
.name{display:flex;align-items:center;gap:8px;font-size:16px;margin:6px 0 2px;color:var(--ink)}
.cart-icon{font-size:18px;text-decoration:none}
.price{font-weight:700;margin:0 0 6px;color:var(--ink)}
.price s{color:#9a8f84;font-weight:400;margin-right:8px}
.admin{font-size:13px;color:var(--muted)}
.search-wrap{position:relative;min-width:320px}
.search-wrap input{width:100%;padding:10px 38px 10px 14px;border:1px solid #e3d7c3;border-radius:12px;background:#fff}
.search-wrap button, .filter-group button{position:absolute;right:6px;top:50%;transform:translateY(-50%);border:0;background:#2c231b;color:#fff;border-radius:10px;padding:8px 10px;cursor:pointer}
.filter-group button{position:static;transform:none}
.sort-form select{padding:8px 10px;border-radius:10px;border:1px solid #e3d7c3;background:#fff}
.paginator{display:flex;gap:8px;margin-top:24px;flex-wrap:wrap}
.paginator a,.paginator span{padding:8px 10px;border:1px solid #e3d7c3;border-radius:8px;text-decoration:none;color:#3a2f26}
.paginator .current{background:var(--pill);font-weight:700}
.filter-group .button-group{display:flex;align-items:center;gap:8px;margin-top:10px}
.filter-group .reset-link{display:inline-block;padding:8px 10px;color:#3a2f26;text-decoration:none}
@media (max-width:980px){.row{grid-template-columns:1fr}.grid{grid-template-columns:1fr}}
input[type="range"] {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 8px;
  background: #eadfcd;
  border-radius: 4px;
  outline: none;
}
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  background: var(--ink);
  border-radius: 50%;
  cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
  width: 16px;
  height: 16px;
  background: var(--ink);
  border-radius: 50%;
  cursor: pointer;
}
</style>
<div class="ffont">
<div class="catalogue">
  <div class="header-line">
    <h1 class="title">Products</h1>
    <div class="search-wrap">
      <?= $this->Form->create(null, ['type'=>'get', 'id'=>'searchForm']) ?>
        <?= $this->Form->control('q', [
              'label'=>false,
              'value'=>$searchVal,
              'placeholder'=>'Search products…'
        ]) ?>
        <?= $this->Form->hidden('category',  ['value'=>$category]) ?>
        <?= $this->Form->hidden('min',       ['value'=>$minQ]) ?>
        <?= $this->Form->hidden('max',       ['value'=>$maxQ]) ?>
        <?= $this->Form->hidden('sort',      ['value'=>$sort]) ?>
        <?= $this->Form->hidden('direction', ['value'=>$direction]) ?>
        <button type="submit">Search</button>
      <?= $this->Form->end() ?>
    </div>
    <div class="sort-form">
      <?= $this->Form->create(null, ['type'=>'get', 'id'=>'sortForm', 'style'=>'display:flex;gap:8px;align-items:center']) ?>
        <?= $this->Form->select('sort', [
              ''=>'Sort: Recommended','price'=>'Price','name'=>'Name','created'=>'Newest'
            ], ['value'=>$sort]) ?>
        <?= $this->Form->select('direction', ['asc'=>'Asc','desc'=>'Desc'], ['value'=>$direction]) ?>
        <?= $this->Form->hidden('category', ['value'=>$category]) ?>
        <?= $this->Form->hidden('min',      ['value'=>$minQ]) ?>
        <?= $this->Form->hidden('max',      ['value'=>$maxQ]) ?>
        <?= $this->Form->hidden('q',        ['value'=>$searchVal]) ?>
      <?= $this->Form->end() ?>
    </div>
  </div>

  <div class="row">
    <aside class="sidebar">
      <h2>Browse by</h2>
      <?php
        $cats = [''=>'All Products','Blends'=>'Blends','Sale'=>'Sale','Single-Origin'=>'Single-Origin','Sustainable'=>'Sustainable'];
        foreach ($cats as $val=>$label):
          $params = array_merge($qParams, ['category'=>$val ?: null, 'page'=>null]);
          $active = ($category === $val) || ($val==='' && $category==='');
      ?>
        <a class="<?= $active ? 'active' : '' ?>" href="<?= $this->Url->build(['?' => $params]) ?>">
          <?= h($label) ?>
        </a>
      <?php endforeach; ?>
      <div class="filter-group">
        <h2>Filter by</h2>
        <?= $this->Form->create(null, ['type'=>'get', 'id'=>'priceForm']) ?>
          <div style="font:600 12px/1 Inter;color:#6b5d4a;margin-bottom:6px">Price</div>
          <div style="display:flex;justify-content:space-between;margin-bottom:6px">
            <span>$<span id="minLabel"><?= h($minQ !== '' ? $minQ : (int)$priceMin) ?></span></span>
            <span>$<span id="maxLabel"><?= h($maxQ !== '' ? $maxQ : (int)$priceMax) ?></span></span>
          </div>
          <input type="range" id="priceRange" min="<?= (int)$priceMin ?>" max="<?= (int)$priceMax ?>" value="<?= h($maxQ !== '' ? $maxQ : (int)$priceMax) ?>">
          <?= $this->Form->hidden('min', ['id'=>'minField','value'=>$minQ !== '' ? $minQ : (int)$priceMin]) ?>
          <?= $this->Form->hidden('max', ['id'=>'maxField','value'=>$maxQ !== '' ? $maxQ : (int)$priceMax]) ?>
          <?= $this->Form->hidden('category',  ['value'=>$category]) ?>
          <?= $this->Form->hidden('q',         ['value'=>$searchVal]) ?>
          <?= $this->Form->hidden('sort',      ['value'=>$sort]) ?>
          <?= $this->Form->hidden('direction', ['value'=>$direction]) ?>
          <div class="button-group">
            <?= $this->Form->button('Apply Filters', ['class' => 'filter-button']) ?>
            <a href="<?= $this->Url->build(['controller'=>'ProductBrowser','action'=>'index']) ?>" class="reset-link">Reset</a>
          </div>
        <?= $this->Form->end() ?>
      </div>
      <?php if ($isAdmin): ?>
      <div class="filter-group">
        <h2>Admin</h2>
        <?= $this->Html->link('➕ Add Product', ['action'=>'add']) ?>
      </div>
      <?php endif; ?>
    </aside>
    <section>
      <div class="grid">
        <?php foreach ($products as $p): ?>
    <?php
    $images = is_array($p->image_url) ? $p->image_url : json_decode($p->image_url, true);
    $firstImage = isset($images[0]) ? str_replace('\\', '', $images[0]) : 'placeholder.png';
    $firstImage = preg_replace('#^/team212-app_fit3047/img/#', '', $firstImage);
    $hasSale = isset($p->sale_price) && $p->sale_price !== null && (float)$p->sale_price < (float)$p->price;
    $link = $this->Url->build(['controller' => 'Products', 'action' => 'detail', $p->id]);
    ?>
    <article class="card",style="transition:0.3s;">
        <?php if ($hasSale): ?><span class="badge">Sale</span><?php endif; ?>
        <div class="media">
            <a href="<?= $link ?>" style="display:block;">
                <img src="<?= $this->Url->image('products/' . basename($firstImage)) ?>" alt="<?= h($p->name) ?>" style="width:100%;height:100%;object-fit:contain;">
            </a>
        </div>
        <div class="body">
            <div class="name"><?= h($p->name) ?></div>
            <div class="price">
                <?php if ($hasSale): ?>
                    <s>$<?= number_format($p->price,2) ?></s> $<?= number_format($p->sale_price,2) ?>
                <?php else: ?>
                    $<?= number_format($p->price,2) ?>
                <?php endif; ?>
            </div>
        </div>
    </article>
<?php endforeach; ?>
      </div>
      <div class="paginator">
        <?= $this->Paginator->first('« First') ?>
        <?= $this->Paginator->prev('‹ Prev') ?>
        <?= $this->Paginator->numbers() ?>
        <?= $this->Paginator->next('Next ›') ?>
        <?= $this->Paginator->last('Last »') ?>
      </div>
    </section>
  </div>
</div>
</div>
<script>
(function(){
  const form = document.getElementById('sortForm');
  if(!form) return;
  form.querySelectorAll('select').forEach(s => s.addEventListener('change', () => form.submit()));
})();

(function(){
  const priceR = document.getElementById('priceRange');
  const minF = document.getElementById('minField');
  const maxF = document.getElementById('maxField');
  const minL = document.getElementById('minLabel');
  const maxL = document.getElementById('maxLabel');
  if(!priceR) return;
  priceR.addEventListener('input', () => {
    maxF.value = priceR.value;
    maxL.textContent = priceR.value;
    minF.value = priceR.min;
    minL.textContent = priceR.min;
  });
})();
</script>
<style>
    div a div:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 12px rgba(0,0,0,0.5);
    }
</style>