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

$ad_id = isset($_GET['ad-id']) ? (int)$_GET['ad-id'] : 0;
if (!$ad_id) { header('Location: browse.php'); exit; }

// Get ad + vendor + industry
$r = query($conn,
  "SELECT a.*, c.vendor, d.industry, d.id AS industry_id
   FROM ads a
   INNER JOIN vendors c ON a.vendor_id = c.id
   INNER JOIN industries d ON c.industry_id = d.id
   WHERE a.id = ? LIMIT 1", "d", [$ad_id]);
$ad = $r ? $r->fetch_assoc() : null;
if (!$ad) { header('Location: browse.php'); exit; }

// Exemplar image
$r = query($conn, "SELECT path FROM images WHERE id = ? LIMIT 1", "d", [$ad['exemplar']]);
$exemplar_path = $r ? $r->fetch_assoc()['path'] : '';
$exemplar_date = get_date_from_path($exemplar_path);

// All issue dates for this ad
$r = query($conn, "SELECT path FROM images WHERE ad_id = ? ORDER BY path", "d", [$ad_id]);
$dates = [];
if ($r) { while ($row = $r->fetch_assoc()) { $dates[] = get_date_from_path($row['path']); } }
$run_count = count($dates);
$first_date = $dates[0] ?? '—';
$last_date  = end($dates) ?: '—';
$date_range = ($first_date === $last_date) ? $first_date : "$first_date to $last_date";

// Year for "from the same year"
$year = substr($first_date, 0, 4);

// Previous / next ad IDs (simple: adjacent IDs that have an exemplar)
$r_prev = query($conn, "SELECT id FROM ads WHERE id < ? AND exemplar > 0 ORDER BY id DESC LIMIT 1", "d", [$ad_id]);
$prev_id = $r_prev ? $r_prev->fetch_assoc()['id'] : null;
$r_next = query($conn, "SELECT id FROM ads WHERE id > ? AND exemplar > 0 ORDER BY id ASC LIMIT 1", "d", [$ad_id]);
$next_id = $r_next ? $r_next->fetch_assoc()['id'] : null;

// Related ads from the same year (4, excluding current)
$r = query($conn,
  "SELECT a.id, a.transcription, e.path AS scan_path, c.vendor, d.industry,
     SUBSTRING(MIN(b.date), 1, 4) AS year
   FROM ads a
   INNER JOIN images b ON a.id = b.ad_id
   INNER JOIN images e ON a.exemplar = e.id
   INNER JOIN vendors c ON a.vendor_id = c.id
   INNER JOIN industries d ON c.industry_id = d.id
   WHERE SUBSTRING(b.date, 1, 4) = ? AND a.id != ? AND a.exemplar > 0
   GROUP BY a.id
   ORDER BY RAND()
   LIMIT 4", "sd", [$year, $ad_id]);
$related = [];
if ($r) { while ($row = $r->fetch_assoc()) { $related[] = $row; } }

// Citation
$page_url     = 'https://' . $_SERVER['HTTP_HOST'] . '/ad.php?ad-id=' . (int)$ad_id;
$last_modified = date('F j, Y', strtotime($ad['last_modified']));
$citation      = "Browne, Jeremy M. \"{$ad['vendor']}: appeared {$run_count} time" . ($run_count !== 1 ? 's' : '') . ", {$date_range}.\" "
               . "Exponent Advertisements. Last modified {$last_modified}. {$page_url}";

$page_title = $ad['vendor'] . ' · ' . $ad['industry'];
include('top.php');
?>
<main>

  <!-- BREADCRUMB -->
  <div class="breadcrumb-bar">
    <span>
      <a href="browse.php">Browse</a>
      &rarr; <a href="browse.php?industries[]=<?= $ad['industry_id'] ?>"><?= htmlspecialchars($ad['industry']) ?></a>
      &rarr; <a href="browse.php?year_from=<?= $year ?>&year_to=<?= $year ?>"><?= $year ?></a>
      &rarr; A-<?= str_pad($ad_id, 4, '0', STR_PAD_LEFT) ?>
    </span>
    <span>
      <?php if ($prev_id): ?>
        <a href="ad.php?ad-id=<?= $prev_id ?>">&larr; Previous</a> &nbsp;
      <?php endif; ?>
      <?php if ($next_id): ?>
        <a href="ad.php?ad-id=<?= $next_id ?>">Next &rarr;</a>
      <?php endif; ?>
    </span>
  </div>

  <!-- MAIN GRID -->
  <div class="ad-detail-layout">

    <!-- Scan column -->
    <div class="ad-scan-col">
      <div class="ad-scan-container">
        <div class="ad-scan-inner">
          <?php if ($exemplar_path): ?>
          <img src="<?= htmlspecialchars($exemplar_path) ?>"
               alt="Advertisement by <?= htmlspecialchars($ad['vendor']) ?> from the <?= htmlspecialchars($exemplar_date) ?> issue of the Woman's Exponent">
          <?php else: ?>
          <span style="color:var(--muted);font-family:var(--font-mono);font-size:11px;padding:40px">No scan available</span>
          <?php endif; ?>
        </div>
      </div>
      <div class="ad-scan-footer">
        <span>From the <?= htmlspecialchars($exemplar_date) ?> issue</span>
      </div>
    </div>

    <!-- Metadata column -->
    <div class="ad-meta-col">
      <p class="ad-eyebrow">A-<?= str_pad($ad_id, 4, '0', STR_PAD_LEFT) ?> · <?= htmlspecialchars(strtoupper($ad['industry'])) ?></p>
      <h1 class="ad-title"><?= htmlspecialchars($ad['vendor']) ?></h1>
      <p class="ad-vendor-year"><?= htmlspecialchars($ad['vendor']) ?>, <?= htmlspecialchars($year) ?></p>

      <div class="ad-metadata-table">
        <div class="ad-metadata-row">
          <span class="ad-meta-key">First issue</span>
          <span class="ad-meta-value"><?= htmlspecialchars($first_date) ?></span>
        </div>
        <?php if ($first_date !== $last_date): ?>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Last issue</span>
          <span class="ad-meta-value"><?= htmlspecialchars($last_date) ?></span>
        </div>
        <?php endif; ?>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Run</span>
          <span class="ad-meta-value"><?= $run_count ?> issue<?= $run_count !== 1 ? 's' : '' ?></span>
        </div>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Vendor</span>
          <span class="ad-meta-value"><?= htmlspecialchars($ad['vendor']) ?></span>
        </div>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Industry</span>
          <span class="ad-meta-value"><?= htmlspecialchars($ad['industry']) ?></span>
        </div>
        <?php if ($ad['street_address']): ?>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Address</span>
          <span class="ad-meta-value"><?= htmlspecialchars($ad['street_address']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($ad['telephone']): ?>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Telephone</span>
          <span class="ad-meta-value"><?= htmlspecialchars($ad['telephone']) ?></span>
        </div>
        <?php endif; ?>
        <div class="ad-metadata-row">
          <span class="ad-meta-key">Last updated</span>
          <span class="ad-meta-value"><?= $last_modified ?></span>
        </div>
      </div>

      <?php if ($ad['transcription']): ?>
      <div>
        <p class="block-eyebrow">Transcript</p>
        <pre class="ad-transcript-panel"><?= htmlspecialchars($ad['transcription']) ?></pre>
      </div>
      <?php endif; ?>

      <div>
        <p class="block-eyebrow">Cite this advertisement</p>
        <div class="ad-citation-panel">
          <span id="citation-text"><?= htmlspecialchars($citation) ?></span>
          <button class="btn-copy" data-target="citation-text">Copy</button>
        </div>
      </div>

    </div><!-- .ad-meta-col -->
  </div><!-- .ad-detail-layout -->

  <!-- RELATED ADS -->
  <?php if ($related): ?>
  <section class="ad-related">
    <div class="strip-header">
      <h2>From the same year</h2>
      <a href="browse.php?year_from=<?= $year ?>&year_to=<?= $year ?>" class="strip-link">
        <?= $year ?> &rarr;
      </a>
    </div>
    <div class="card-grid">
      <?php foreach ($related as $rel): ?>
      <a href="ad.php?ad-id=<?= $rel['id'] ?>" class="aa-card">
        <div class="aa-card-scan">
          <img src="<?= htmlspecialchars($rel['scan_path']) ?>"
               alt="Advertisement by <?= htmlspecialchars($rel['vendor']) ?>"
               loading="lazy">
        </div>
        <div>
          <div class="aa-card-id">A-<?= str_pad($rel['id'], 4, '0', STR_PAD_LEFT) ?> · <?= htmlspecialchars(substr($rel['industry'], 0, 4)) ?>.</div>
          <div class="aa-card-headline"><?= htmlspecialchars(mb_strimwidth($rel['transcription'], 0, 60, '…')) ?></div>
          <div class="aa-card-meta"><?= htmlspecialchars($rel['vendor']) ?> · <?= htmlspecialchars($rel['year']) ?></div>
        </div>
      </a>
      <?php endforeach; ?>
    </div>
  </section>
  <?php endif; ?>

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