<?php
/**
 * @var \App\View\AppView $this
 * @var \Cake\Datasource\ResultSetInterface|\App\Model\Entity\Product[] $products
 * @var array $filters
 */
$this->assign('title', 'Products');

// Keep current filters in pagination links
$this->Paginator->options([
  'url' => [
    '?' => [
      'seasonal' => $filters['seasonal'] ?? '',
      'in_stock' => $filters['in_stock'] ?? '0',
      'sort'     => $filters['sort'] ?? 'newest',
    ]
  ]
]);

// Helper for image paths
$imgSrc = function($path) {
  $p = (string)$path;
  if ($p === '') return '/img/placeholder.jpg';
  if (preg_match('#^(https?:)?/#', $p)) return $p;
  return '/img/' . ltrim($p, '/');
};
?>

<section style="max-width:1200px;margin:0 auto;padding:16px;">
  <!-- Sticky top bar -->
  <div class="filters-sticky" style="position:sticky;top:0;z-index:50;background:var(--bg,#fff8f1);padding:8px 0;">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;">
      <h1 style="margin:8px 0 10px;font-size:28px;color:#402c1d;">Products</h1>
        <?= $this->Html->link('Add Product', ['controller' => 'Products', 'action' => 'add']) ?>
      <!-- Filter dropdown -->
      <div style="position:relative;">
        <button id="filterToggle"
          aria-haspopup="true" aria-expanded="false"
          style="
            display:inline-flex;align-items:center;gap:8px;
            padding:10px 14px;border:1px solid #e6e0da;border-radius:999px;
            background:#fff;cursor:pointer;
            box-shadow:0 2px 8px rgba(0,0,0,.04);
            color:#6b5e57;font-weight:600;
          ">
          <span>Filter</span>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>

        <div id="filterPanel"
          role="menu"
          style="
            display:none;position:absolute;right:0;margin-top:10px;background:#fff;
            border:1px solid #eee;border-radius:14px;
            box-shadow:0 12px 32px rgba(0,0,0,.12);padding:12px;z-index:60;min-width:280px;
          ">
          <form method="get" id="filtersForm" style="display:grid;gap:12px;">
            <!-- Seasonal -->
            <label style="display:grid;gap:6px;font-size:13px;color:#6b5e57;">
              <span style="font-weight:600;color:#3b2a1d;">Show</span>
              <select name="seasonal" style="padding:10px;border:1px solid #e6e6e6;border-radius:10px;">
                <option value=""  <?= ($filters['seasonal'] ?? '') === ''  ? 'selected' : '' ?>>All products</option>
                <option value="1" <?= ($filters['seasonal'] ?? '') === '1' ? 'selected' : '' ?>>Seasonal only</option>
              </select>
            </label>

            <!-- In stock -->
            <label style="display:grid;gap:6px;font-size:13px;color:#6b5e57;">
              <span style="font-weight:600;color:#3b2a1d;">Stock</span>
              <select name="in_stock" style="padding:10px;border:1px solid #e6e6e6;border-radius:10px;">
                <option value="0" <?= ($filters['in_stock'] ?? '0') === '0' ? 'selected' : '' ?>>All availability</option>
                <option value="1" <?= ($filters['in_stock'] ?? '0') === '1' ? 'selected' : '' ?>>In stock only</option>
              </select>
            </label>

            <!-- Sort -->
            <label style="display:grid;gap:6px;font-size:13px;color:#6b5e57;">
              <span style="font-weight:600;color:#3b2a1d;">Sort by</span>
              <select name="sort" style="padding:10px;border:1px solid #e6e6e6;border-radius:10px;">
                <option value="newest"     <?= ($filters['sort'] ?? 'newest') === 'newest' ? 'selected' : '' ?>>Newest</option>
                <option value="price_asc"  <?= ($filters['sort'] ?? '') === 'price_asc' ? 'selected' : '' ?>>Price: Low → High</option>
                <option value="price_desc" <?= ($filters['sort'] ?? '') === 'price_desc' ? 'selected' : '' ?>>Price: High → Low</option>
              </select>
            </label>

            <hr style="border:none;border-top:1px solid #f0ebe7;margin:4px 0;">

            <!-- Aligned Reset / Apply -->
            <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:4px;align-items:center;">
              <!-- Reset -->
              <a href="<?= $this->Url->build(['action' => 'index']) ?>"
                 style="
                   display:inline-flex;align-items:center;justify-content:center;
                   height:40px;padding:0 16px;margin:0;
                   border:1px solid #d9cfc8;border-radius:999px;box-sizing:border-box;
                   background:#faf7f4;color:#7a5b49;font-weight:600;font-size:14px;line-height:1;
                   text-decoration:none;transition:all .15s ease;
                 "
                 onmouseover="this.style.background='#f0ebe7';this.style.borderColor='#c8b9ae';"
                 onmouseout="this.style.background='#faf7f4';this.style.borderColor='#d9cfc8';">
                Reset
              </a>

              <!-- Apply -->
              <button type="submit"
                style="
                  display:inline-flex;align-items:center;justify-content:center;
                  height:40px;padding:0 20px;margin:0;
                  border:none;border-radius:999px;box-sizing:border-box;
                  background:#7a5b49;color:#fff;font-weight:600;font-size:14px;line-height:1;
                  cursor:pointer;transition:background .15s ease;
                  -webkit-appearance:none;appearance:none;
                "
                onmouseover="this.style.background='#694c39';"
                onmouseout="this.style.background='#7a5b49';">
                Apply
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Results mini-meta -->
    <div style="display:flex;align-items:center;gap:10px;color:#6b5e57;font-size:13px;margin-top:4px;">
      <span>Showing <?= count($products) ?> item<?= count($products) === 1 ? '' : 's' ?></span>
      <?php if (($filters['seasonal'] ?? '') === '1'): ?><span>• Seasonal</span><?php endif; ?>
      <?php if (($filters['in_stock'] ?? '0') === '1'): ?><span>• In stock</span><?php endif; ?>
      <?php if (($filters['sort'] ?? 'newest') !== 'newest'): ?><span>• Sorted</span><?php endif; ?>
    </div>
  </div>

  <?php if ($products->isEmpty()): ?>
    <p style="margin-top:16px;">No products match your filters. Try resetting.</p>
  <?php else: ?>
    <!-- Card grid -->
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:18px;margin-top:12px;">
      <?php foreach ($products as $p): ?>
        <article
          style="
            background:#fff;border:1px solid #eee;border-radius:16px;overflow:hidden;
            box-shadow:0 6px 18px rgba(0,0,0,.06);
            transition:transform .15s ease, box-shadow .15s ease;
          "
          onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 10px 24px rgba(0,0,0,.10)';"
          onmouseout="this.style.transform='translateY(0)';this.style.boxShadow='0 6px 18px rgba(0,0,0,.06)';"
        >
          <a href="<?= $this->Url->build(['action' => 'view', $p->id]) ?>" style="text-decoration:none;color:inherit;display:block;">
            <div style="aspect-ratio:4/3;overflow:hidden;background:#faf7f4;">
              <img
                src="<?= h($imgSrc($p->product_image_url)) ?>"
                alt="<?= h($p->name) ?>"
                style="width:100%;height:100%;object-fit:cover;"
              />
            </div>
            <div style="padding:14px 16px;">
              <h3 style="margin:0 0 6px;font-size:18px;color:#3b2a1d;"><?= h($p->name) ?></h3>
              <p style="margin:0 0 10px;color:#6b5e57;font-size:14px;min-height:42px;">
                <?= h(mb_strimwidth((string)$p->description, 0, 90, '…')) ?>
              </p>
              <div style="display:flex;justify-content:space-between;align-items:center;">
                <!-- ✅ Price or Not Available -->
                <?php if (!empty($p->is_available)): ?>
                  <strong style="font-size:16px;color:#2aa8a5;">
                    $<?= number_format((float)$p->price, 2) ?>
                  </strong>
                <?php else: ?>
                  <span style="color:#a22626; font-weight:600; font-size:14px;">
                    Not Available
                  </span>
                <?php endif; ?>

                <?php if ((int)$p->is_seasonal === 1): ?>
                  <span style="font-size:12px;padding:3px 10px;border-radius:999px;border:1px solid #e6d9cf;color:#7a5b49;">
                    Seasonal
                  </span>
                <?php endif; ?>
              </div>

              <!-- ✅ Allergens under product card -->
              <?php if (!empty($p->allergens)): ?>
                <div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;">
                  <?php foreach ($p->allergens as $allergen): ?>
                    <span style="font-size:11px;padding:3px 8px;border-radius:999px;
                                 background:#fff0f0;color:#a22626;">
                      <?= h($allergen->allergen_name) ?>
                    </span>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>

            </div>
          </a>
            <div style="padding:12px;border-top:1px solid #eee;display:flex;gap:8px;justify-content:space-between;align-items:center;">
                <?= $this->Form->create(null, [
                    'url' => ['controller' => 'Carts', 'action' => 'addItem', $p->id], // or $product->id
                    'type' => 'post'
                ]) ?>
                <?= $this->Form->number('qty', ['value'=>1, 'min'=>1, 'style'=>'width:64px;padding:6px;']) ?>
                <?= $this->Form->button('Add to cart') ?>
                <?= $this->Form->end() ?>

                <span style="font-size:12px;color:#6b5e57;">
                <?= $this->Number->currency($p->price) ?>
                </span>
            </div>
        </article>
      <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <div style="margin-top:22px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
      <?= $this->Paginator->prev('« Prev') ?>
      <?= $this->Paginator->numbers() ?>
      <?= $this->Paginator->next('Next »') ?>
    </div>
  <?php endif; ?>
</section>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const btn   = document.getElementById('filterToggle');
    const panel = document.getElementById('filterPanel');
    const form  = document.getElementById('filtersForm');

    if (!btn || !panel) return;

    const open  = () => { panel.style.display = 'block'; btn.setAttribute('aria-expanded', 'true'); };
    const close = () => { panel.style.display = 'none';  btn.setAttribute('aria-expanded', 'false'); };

    // Always start closed
    close();

    // Toggle
    btn.addEventListener('click', function (e) {
      e.preventDefault();
      (panel.style.display === 'block') ? close() : open();
    });

    // Click-away close
    document.addEventListener('click', function (e) {
      if (!panel.contains(e.target) && !btn.contains(e.target)) close();
    });

    // ESC closes
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') close();
    });

    // Close when form submits (Apply pressed)
    if (form) form.addEventListener('submit', function () { close(); });
  });
</script>
