<?php
include('php/db_connect_localhost.php');
include('php/useful.php');

// ── Parameters ──────────────────────────────────────────────────
$q          = trim($_GET['q'] ?? '');
$year_from  = (int)($_GET['year_from'] ?? 1872);
$year_to    = (int)($_GET['year_to']   ?? 1914);
$sort       = $_GET['sort'] ?? 'year-asc';
$view       = in_array($_GET['view'] ?? '', ['card','list']) ? $_GET['view'] : 'card';
$page       = max(1, (int)($_GET['page'] ?? 1));
$per_page   = $view === 'list' ? 25 : 16;

// Clamp years
$year_from = max(1872, min(1914, $year_from));
$year_to   = max($year_from, min(1914, $year_to));

// Selected industry IDs (array of ints)
$all_industries = get_industries($conn);
$industry_ids_input = $_GET['industries'] ?? [];
if (!is_array($industry_ids_input)) $industry_ids_input = [];
$selected_ids = array_map('intval', $industry_ids_input);
$has_industry_filter = count($selected_ids) > 0;

// ── Build query ─────────────────────────────────────────────────
if ($sort === 'year-desc') {
  $order_clause = 'MIN(b.date) DESC';
} elseif ($sort === 'vendor') {
  $order_clause = 'c.vendor ASC';
} else {
  $order_clause = 'MIN(b.date) ASC';
}

$params = [];
$format = '';

$where_parts = ['a.exemplar > 0'];

// Text search
if ($q !== '') {
  $where_parts[] = 'LOWER(a.transcription) LIKE ?';
  $params[] = '%' . strtolower($q) . '%';
  $format .= 's';
}

$year_from_str = $year_from . '-01-01';
$year_to_str   = $year_to   . '-12-31';

// Industry filter
if ($has_industry_filter) {
  $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));
  $where_parts[] = "c.industry_id IN ($placeholders)";
  foreach ($selected_ids as $id) { $params[] = $id; $format .= 'd'; }
}

$where_sql = implode(" AND\n      ", $where_parts);

// Count query for pagination
$count_sql = "SELECT COUNT(DISTINCT a.id) AS n
  FROM ads a
  INNER JOIN images b ON a.id = b.ad_id
  INNER JOIN vendors c ON a.vendor_id = c.id
  INNER JOIN industries d ON c.industry_id = d.id
  WHERE $where_sql
  AND b.date >= ? AND b.date <= ?";
$count_params = array_merge($params, [$year_from_str, $year_to_str]);
$count_format = $format . 'ss';
$count_result = query($conn, $count_sql, $count_format, $count_params);
$total = $count_result ? (int)$count_result->fetch_assoc()['n'] : 0;
$total_pages = max(1, (int)ceil($total / $per_page));
$page = min($page, $total_pages);
$offset = ($page - 1) * $per_page;

// Main results query
$results_sql = "SELECT
    a.id,
    a.transcription,
    MIN(b.date) AS first_date,
    MAX(b.date) AS last_date,
    COUNT(DISTINCT b.id) AS run_count,
    c.vendor,
    d.industry,
    d.id AS industry_id,
    e.path AS scan_path,
    SUBSTRING(MIN(b.date), 1, 4) AS year
  FROM ads a
  INNER JOIN images b ON a.id = b.ad_id
  INNER JOIN vendors c ON a.vendor_id = c.id
  INNER JOIN industries d ON c.industry_id = d.id
  INNER JOIN images e ON a.exemplar = e.id
  WHERE $where_sql
  AND b.date >= ? AND b.date <= ?
  GROUP BY a.id
  ORDER BY $order_clause
  LIMIT $per_page OFFSET $offset";
$results_params = array_merge($params, [$year_from_str, $year_to_str]);
$results_format = $format . 'ss';
$results_result = query($conn, $results_sql, $results_format, $results_params);
$ads = [];
if ($results_result) { while ($row = $results_result->fetch_assoc()) { $ads[] = $row; } }

// Per-industry counts (for the sidebar, unfiltered by industry)
$industry_counts = [];
$ic_params = [];
$ic_format = '';
$ic_where = 'a.exemplar > 0';
if ($q !== '') {
  $ic_where .= ' AND LOWER(a.transcription) LIKE ?';
  $ic_params[] = '%' . strtolower($q) . '%';
  $ic_format  .= 's';
}
$ic_where .= ' AND b.date >= ? AND b.date <= ?';
$ic_params[] = $year_from_str;
$ic_params[] = $year_to_str;
$ic_format  .= 'ss';
$ic_result = query($conn, "SELECT d.id, COUNT(DISTINCT a.id) AS n
  FROM ads a
  INNER JOIN images b ON a.id = b.ad_id
  INNER JOIN vendors c ON a.vendor_id = c.id
  INNER JOIN industries d ON c.industry_id = d.id
  WHERE $ic_where
  GROUP BY d.id", $ic_format, $ic_params);
if ($ic_result) { while ($ic_row = $ic_result->fetch_assoc()) {
  $industry_counts[$ic_row['id']] = $ic_row['n'];
}}

// Build URL helper (preserves all params, swaps one)
function browse_url(array $overrides = []): string {
  global $q, $year_from, $year_to, $selected_ids, $sort, $view, $page;
  $base = [
    'q'          => $q,
    'year_from'  => $year_from,
    'year_to'    => $year_to,
    'sort'       => $sort,
    'view'       => $view,
    'page'       => $page,
  ];
  if ($selected_ids) $base['industries'] = $selected_ids;
  $merged = array_merge($base, $overrides);
  return 'browse.php?' . http_build_query($merged);
}

// Build filter summary text
$summary_parts = ["$total result" . ($total !== 1 ? 's' : '')];
if ($q !== '') $summary_parts[] = "q=&ldquo;" . htmlspecialchars($q) . "&rdquo;";
if ($year_from !== 1872 || $year_to !== 1914) $summary_parts[] = "years $year_from&ndash;$year_to";
if ($has_industry_filter) {
  $names = [];
  foreach ($all_industries as $ind) {
    if (in_array($ind['industry_id'], $selected_ids)) { $names[] = $ind['industry']; }
  }
  $summary_parts[] = 'industries: ' . implode(', ', $names);
}

$page_title = 'Browse';
include('top.php');
?>
<main>
  <form class="browse-layout" action="browse.php" method="GET" id="browse-form">

    <!-- ── FILTER RAIL ── -->
    <aside class="browse-rail">
      <p class="eyebrow">Refine</p>

      <div class="rail-field">
        <label class="rail-label" for="rail-search">Search text</label>
        <input class="rail-text-input" type="search" id="rail-search" name="q"
          value="<?= htmlspecialchars($q) ?>" placeholder="Keywords in transcript&hellip;">
      </div>

      <div class="rail-field">
        <span class="rail-label" id="years-label">Years</span>
        <div class="year-range-wrap" role="group" aria-labelledby="years-label">
          <div class="year-range-track">
            <div class="year-range-fill"></div>
          </div>
          <input type="range" id="year-from" name="year_from" aria-label="From year" data-handle="min"
            min="1872" max="1914" value="<?= $year_from ?>" step="1">
          <input type="range" id="year-to" name="year_to" aria-label="To year" data-handle="max"
            min="1872" max="1914" value="<?= $year_to ?>" step="1">
        </div>
        <div class="year-range-labels"><span>1872</span><span>1914</span></div>
        <div class="year-range-selected"><?= $year_from ?> &rarr; <?= $year_to ?></div>
      </div>

      <input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>">
      <div style="margin-top:20px">
        <button type="submit" class="btn-submit" style="width:100%">Apply filters &rarr;</button>
      </div>

      <div class="rail-field">
        <label class="rail-label">Industries</label>
        <div class="industry-list-controls">
          <a href="#" onclick="document.querySelectorAll('.industry-cb').forEach(function(c){c.checked=true}); return false;">All</a>
          <a href="#" onclick="document.querySelectorAll('.industry-cb').forEach(function(c){c.checked=false}); return false;">None</a>
        </div>
        <?php foreach ($all_industries as $ind):
          $checked = !$has_industry_filter || in_array($ind['industry_id'], $selected_ids);
          $count   = $industry_counts[$ind['industry_id']] ?? 0;
        ?>
        <div class="industry-check-row">
          <input class="industry-cb" type="checkbox" name="industries[]"
            id="ind-<?= $ind['industry_id'] ?>"
            value="<?= $ind['industry_id'] ?>"
            <?= $checked ? 'checked' : '' ?>>
          <label for="ind-<?= $ind['industry_id'] ?>"><?= htmlspecialchars($ind['industry']) ?></label>
          <span class="industry-count"><?= number_format($count) ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </aside>

    <!-- ── RESULTS AREA ── -->
    <div class="browse-results">

      <div class="browse-results-header">
        <h1>Browse the archive</h1>
        <div class="view-toggle">
          <button type="button" data-view="card" aria-pressed="<?= $view === 'card' ? 'true' : 'false' ?>" class="<?= $view === 'card' ? 'active' : '' ?>">Cards</button>
          <button type="button" data-view="list" aria-pressed="<?= $view === 'list' ? 'true' : 'false' ?>" class="<?= $view === 'list' ? 'active' : '' ?>">List</button>
        </div>
      </div>

      <div class="filter-summary">
        <span class="filter-summary-left"><?= implode(' · ', $summary_parts) ?></span>
        <span class="filter-summary-right">
          Sort:
          <a href="<?= browse_url(['sort'=>'year-asc',  'page'=>1]) ?>" class="<?= $sort==='year-asc'  ? 'active-sort' : '' ?>">year &uarr;</a>
          &middot;
          <a href="<?= browse_url(['sort'=>'year-desc', 'page'=>1]) ?>" class="<?= $sort==='year-desc' ? 'active-sort' : '' ?>">year &darr;</a>
          &middot;
          <a href="<?= browse_url(['sort'=>'vendor',    'page'=>1]) ?>" class="<?= $sort==='vendor'    ? 'active-sort' : '' ?>">vendor</a>
        </span>
      </div>

      <?php if (empty($ads)): ?>
        <p class="no-results">No advertisements found. Try broadening your filters.</p>
      <?php elseif ($view === 'list'): ?>

        <!-- LIST VIEW -->
        <div role="grid" aria-label="Browse results">
        <div class="list-header" role="row">
          <span role="columnheader">ID</span>
          <span role="columnheader">Year</span>
          <span role="columnheader">Ad / Vendor</span>
          <span role="columnheader">Industry</span>
          <span role="columnheader">Run</span>
          <span role="columnheader"><span class="sr-only">View</span></span>
        </div>
        <?php foreach ($ads as $ad): ?>
        <a href="ad.php?ad-id=<?= $ad['id'] ?>" class="aa-row" role="row">
          <span class="aa-row-id" role="gridcell">A-<?= str_pad($ad['id'], 4, '0', STR_PAD_LEFT) ?></span>
          <span class="aa-row-year" role="gridcell"><?= htmlspecialchars($ad['year']) ?></span>
          <span class="aa-row-title" role="gridcell">
            <div class="aa-row-headline"><?= htmlspecialchars(mb_strimwidth($ad['transcription'], 0, 60, '…')) ?></div>
            <div class="aa-row-vendor"><?= htmlspecialchars($ad['vendor']) ?></div>
          </span>
          <span class="aa-row-industry" role="gridcell"><?= htmlspecialchars($ad['industry']) ?></span>
          <span class="aa-row-dims" role="gridcell"><?= $ad['run_count'] ?> issue<?= $ad['run_count'] != 1 ? 's' : '' ?></span>
          <span class="aa-row-action" role="gridcell">View &rarr;</span>
        </a>
        <?php endforeach; ?>
        </div>

      <?php else: ?>

        <!-- CARD VIEW -->
        <div class="card-grid" id="browse-results-area">
          <?php foreach ($ads as $ad): ?>
          <a href="ad.php?ad-id=<?= $ad['id'] ?>" class="aa-card">
            <div class="aa-card-scan">
              <img src="<?= htmlspecialchars($ad['scan_path']) ?>"
                   alt="Advertisement by <?= htmlspecialchars($ad['vendor']) ?>, <?= htmlspecialchars($ad['year']) ?>"
                   loading="lazy">
            </div>
            <div>
              <div class="aa-card-id">A-<?= str_pad($ad['id'], 4, '0', STR_PAD_LEFT) ?> · <?= htmlspecialchars(substr($ad['industry'], 0, 4)) ?>.</div>
              <div class="aa-card-headline"><?= htmlspecialchars(mb_strimwidth($ad['transcription'], 0, 60, '…')) ?></div>
              <div class="aa-card-meta"><?= htmlspecialchars($ad['vendor']) ?> · <?= htmlspecialchars($ad['year']) ?></div>
            </div>
          </a>
          <?php endforeach; ?>
        </div>

      <?php endif; ?>

      <!-- PAGINATION -->
      <?php if ($total_pages > 1): ?>
      <nav aria-label="Page navigation">
        <ul class="pagination">
          <li>
            <?php if ($page > 1): ?>
              <a href="<?= browse_url(['page' => $page - 1]) ?>">&larr;</a>
            <?php else: ?>
              <span class="disabled">&larr;</span>
            <?php endif; ?>
          </li>
          <?php
          // Show: 1 … prev current next … last
          $pages_to_show = [];
          $pages_to_show[] = 1;
          if ($page > 3) $pages_to_show[] = '…';
          for ($p = max(2, $page-1); $p <= min($total_pages-1, $page+1); $p++) $pages_to_show[] = $p;
          if ($page < $total_pages - 2) $pages_to_show[] = '…';
          if ($total_pages > 1) $pages_to_show[] = $total_pages;

          foreach ($pages_to_show as $p):
            if ($p === '…'):
          ?>
          <li><span>&hellip;</span></li>
          <?php elseif ($p === $page): ?>
          <li><span class="current"><?= $p ?></span></li>
          <?php else: ?>
          <li><a href="<?= browse_url(['page' => $p]) ?>"><?= $p ?></a></li>
          <?php endif; endforeach; ?>
          <li>
            <?php if ($page < $total_pages): ?>
              <a href="<?= browse_url(['page' => $page + 1]) ?>">&rarr;</a>
            <?php else: ?>
              <span class="disabled">&rarr;</span>
            <?php endif; ?>
          </li>
        </ul>
      </nav>
      <?php endif; ?>

    </div><!-- .browse-results -->
  </form>
</main>

<script>
// Sync view-toggle button clicks to the hidden input and re-submit
document.querySelectorAll('.view-toggle button').forEach(function(btn) {
  btn.addEventListener('click', function() {
    document.querySelector('input[name="view"]').value = btn.dataset.view;
    document.getElementById('browse-form').submit();
  });
});
</script>

<?php include('bottom.html'); ?>
