<?php
/**
 * The whole site, really: one coupon week in one of four states.
 *
 * /                      THE current week. Canonical to itself, always.
 * /week-16-2026/         while 16 is current: 301 to "/"
 *                        once superseded: a real page, canonical to itself
 * /week-4-2026-aussie/   summer season, same rules
 *
 * Why it is this way round. It used to be the opposite — "/" served the
 * current week but declared the week URL as its canonical. Two URLs then
 * served identical HTML, Google picked "/" anyway ("Duplicate, Google chose
 * different canonical"), and every Saturday "/" changed its canonical to the
 * next week, so Google re-evaluated the homepage from scratch and it dropped
 * out of the top ten. Now no two URLs ever serve the same content, and the
 * homepage's identity never changes.
 */
require __DIR__ . '/inc/boot.php';

$week   = isset($_GET['week'])   ? (int)$_GET['week']   : null;
$year   = isset($_GET['year'])   ? (int)$_GET['year']   : null;
$season = isset($_GET['season']) ? preg_replace('/[^a-z]/', '', strtolower($_GET['season'])) : 'english';

$w = ($week && $year) ? Week::load($sb, $season, $year, $week) : Week::current($sb);

if (!$w) {
    http_response_code(404);
    pageHead('Week not found – PoolsAgents', 'No coupon for that week.',
             $config['site']['base'] . '/');
    echo '<div class="wrap"><h1>No coupon for that week</h1>'
       . '<p>Try the <a href="/archive/">archive</a>.</p></div>';
    pageFoot();
    exit;
}

/* Is the week being viewed the one currently on "/"? */
$isHome    = !($week && $year);
$curWeek   = $isHome ? $w : Week::current($sb);
$isCurrent = $curWeek
          && (int)$curWeek->week === (int)$w->week
          && (int)$curWeek->year === (int)$w->year
          && $curWeek->season === $w->season;

/* A week URL for the CURRENT week is a duplicate of "/". Send it there, keeping
   any query string so campaign tags survive. Once the next week opens, this
   condition stops matching and the same URL becomes a real page. */
if (!$isHome && $isCurrent) {
    $qs = (string)(isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
    // the rewrite adds week/year/season to the query; strip those, keep the rest
    parse_str($qs, $q);
    unset($q['week'], $q['year'], $q['season']);
    $rest = http_build_query($q);
    header('Location: /' . ($rest !== '' ? '?' . $rest : ''), true, 301);
    exit;
}

$state   = $w->state();
$summary = $w->summary();
$multi   = $w->isMultiDay();      // Saturday + Sunday coupons need day labels
$isLive  = $w->isLive();
$canon   = $isHome ? $config['site']['base'] . '/' : $w->url($config['site']['base']);
list($bannerTitle, $bannerNote) = stateBanner($state);

// Week pages carry the week; the homepage additionally targets the evergreen
// phrasing people actually search ("pool draws this week").
$title  = $state === Week::SETTLED
        ? $w->title() . ' pools results and draws – PoolsAgents'
        : ($isHome
            ? 'Pool draws this week — ' . $w->title() . ' coupon priced – PoolsAgents'
            : $w->title() . ' coupon: draw prices – PoolsAgents');

$desc = $state === Week::SETTLED
      ? 'Full classified results for ' . $w->title() . ': '
        . $summary['draws'] . ' draws from '
        . $summary['total'] . ' matches, with the prices quoted beforehand.'
      : 'All ' . $summary['total'] . ' matches on the ' . $w->title()
        . ' coupon, ranked by the market\'s chance of a draw.';

// Structured data. Dataset rather than SportsEvent: what this page publishes
// is a priced coupon, and Dataset is what assistants and Google surface for
// "where can I find X data" queries — which is the intent we want to own.
$jsonld = array(
    '@context' => 'https://schema.org',
    '@graph'   => array(
        array(
            '@type'       => 'Dataset',
            'name'        => $w->title() . ' football pools coupon: draw probabilities',
            'description' => $desc,
            'url'         => $canon,
            'creator'     => array('@type' => 'Organization', 'name' => 'PoolsAgents'),
            // Search Console flags Dataset items without one. Points at the
            // reuse terms on /about/ rather than claiming an open licence we
            // cannot grant: the prices underneath belong to the bookmakers.
            'license'     => $config['site']['base'] . '/about/#data',
            'temporalCoverage' => (string)$w->year,
            'variableMeasured' => array('draw probability', 'best available draw price'),
            'isAccessibleForFree' => true,
            // ISO 8601 with a timezone; the DB value has a space and no zone
            'dateModified' => gmdate('c', strtotime($w->lastUpdated() . ' UTC')),
        ),
        array(
            '@type' => 'BreadcrumbList',
            'itemListElement' => array(
                array('@type' => 'ListItem', 'position' => 1, 'name' => 'Archive',
                      'item' => $config['site']['base'] . '/archive/'),
                array('@type' => 'ListItem', 'position' => 2, 'name' => $w->title(),
                      'item' => $canon),
            ),
        ),
    ),
);

// week strip under the header: the one piece of context every page needs
$subhead = array(
    'week' => 'Week ' . (int)$w->week,
    'ctx'  => ucfirst($w->season) . ' · ' . pa_localTime($w->rows[0]['kickoff_utc'], 'D j M'),
    'meta' => $state === Week::PRICED
            ? (int)$summary['priced'] . ' of ' . (int)$summary['total'] . ' priced · updated '
              . pa_localTime($w->lastUpdated())
            : (int)$summary['settled'] . ' of ' . (int)$summary['total'] . ' settled',
);

$og = $config['site']['base'] . '/og.php?week=' . (int)$w->week
    . '&year=' . (int)$w->year . '&season=' . urlencode($w->season);

// This page is laid out as a dashboard: the coupon first, the detail below. The globals tell the shared header and footer
// to put the navigation in a bottom tab bar on phones and to leave the house banner for this page to place.
$GLOBALS['pa_dash'] = true; $GLOBALS['pa_dash_here'] = 'week'; 
//$GLOBALS['pa_defer_promo'] = true;
require_once __DIR__ . '/inc/promo.php';
pageHead($title, $desc, $canon, $isLive, $jsonld, 'week', $subhead, $og);
?>
<div class="wrap dashwrap">

<?php $closes = $w->closesAt(); ?>

<?php /* No data-closes once the kick-off is past: there is nothing to count
         down to, and the client would only find an expired clock. */
      $cdOn = ($state === Week::PRICED && $closes && $closes > time()); ?>
<div class="hero <?= e($state) ?>"<?= $cdOn ? ' data-closes="' . (int)$closes . '"' : '' ?>>
  <div class="hero-in">
    <div class="hero-top">
      <span class="tagpill">
        <?php if ($isLive): ?><span class="dot"></span><?php endif; ?>
        <?= $state === Week::PRICED ? 'Week ' . (int)$w->week . ' closes in'
           : ($state === Week::SETTLED ? 'Week ' . (int)$w->week . ' · final'
           : 'Week ' . (int)$w->week . ' · live now') ?>
      </span>
      <span class="stamp" id="stamp">updated <?= e(fmtDate($w->lastUpdated())) ?></span>
    </div>

    <?php if ($cdOn): ?>
      <div class="clock" id="clock">
        <div class="unit"><b data-d>–</b><small>DAYS</small></div>
        <div class="unit"><b data-h>–</b><small>HRS</small></div>
        <div class="unit"><b data-m>–</b><small>MINS</small></div>
        <div class="unit"><b data-s>–</b><small>SECS</small></div>
      </div>
    <?php endif; ?>

    <?php $mx = 0.0; foreach ($w->rows as $r) { if ($r['p_draw'] !== null && (float)$r['p_draw'] > $mx) { $mx = (float)$r['p_draw']; } } ?>
    <div class="figs">
    <?php if ($state === Week::PRICED): ?>
      <div><b class="ok"><?= number_format($summary['exp_draws'], 1) ?></b><small>EXPECTED DRAWS</small></div>
      <div><b><?= round($mx * 100) ?>%</b><small>STRONGEST</small></div>
      <div><b><?= (int)$summary['priced'] ?><i>/<?= (int)$summary['total'] ?></i></b><small>PRICED</small></div>
    <?php else: ?>
      <div><b class="ok"><?= (int)$summary['draws'] ?></b><small>DRAWS</small></div>
      <div><b><?= $summary['settled'] > 0 ? round($summary['draws'] / $summary['settled'] * 100) : 0 ?>%</b><small>DRAW RATE</small></div>
      <div><b><?= (int)$summary['settled'] ?><i>/<?= (int)$summary['total'] ?></i></b><small>SETTLED</small></div>
    <?php endif; ?>
    </div>

    <?php /* On a phone the week's date is already in the strip under the header, so outside a live week this line is hidden there. */ ?>
    <p class="herometa<?= $state === Week::LIVE ? '' : ' hm-ctx' ?>">
      <?php if ($state === Week::LIVE): $up = $w->upcomingByDay(); ?>
        <?= (int)($summary['kicked'] - $summary['settled']) ?> in play ·
        <?= (int)$summary['settled'] ?> finished ·
        <?php if ($multi && $up['later'] > 0): ?>
          <?= (int)$up['today'] ?> later today · <?= (int)$up['later'] ?> tomorrow
        <?php else: ?>
          <?= (int)($summary['total'] - $summary['kicked']) ?> to come
        <?php endif; ?>
      <?php else: ?>
        <?= e(ucfirst($w->season)) ?> · <?= e(fmtDate($closes ? gmdate('Y-m-d H:i:s', $closes) : null, 'D j M')) ?>
      <?php endif; ?>
    </p>
  </div>
</div>

<div class="dash <?= $state === Week::PRICED ? 'dash-priced' : 'dash-results' ?>">
<?php if ($state === Week::PRICED): ?>
<?php /* "My coupon". Everything inside is written by live.js from numbers kept
         in the visitor's own browser — no account, nothing sent to us. It stays
         hidden until they choose some, so it costs a first-time visitor
         nothing. The point is that the site should know what THEIR week looks
         like: that is what turns a one-off results lookup into a habit. */ ?>
<section class="mine-panel d-mine" id="minePanel" hidden
         data-week="<?= (int)$w->week ?>" data-year="<?= (int)$w->year ?>"
         data-season="<?= e($w->season) ?>" data-state="<?= e($state) ?>">
  <div class="mp-head">
    <h2>Your coupon</h2>
    <button type="button" class="mp-edit" id="mpEdit">change</button>
  </div>
  <p class="mp-line" id="mpLine"></p>
  <div class="numgrid board compact" id="mpGrid"></div>
</section>

<section class="d-board">
  <h1>Week <?= (int)$w->week ?> · all <?= (int)$summary['total'] ?> numbers</h1>
  <p class="lede"><span>Shaded by the market's chance of a draw<span class="lede-more">, with the bookmakers' margin removed</span>.</span>
     <span class="lede-more">The darkest numbers have the highest market chance of a draw.</span>
     <span>Market prices, not tips. Tap a number for the match.</span>
     <?php if ($multi): ?>This coupon runs over
     <?php $ds = $w->matchDays(); $names = array();
           foreach ($ds as $d) { $names[] = date('l', strtotime($d)); }
           echo e(implode(' and ', $names)); ?>.<?php endif; ?></p>

  <?php $bands = Week::drawBands($w->rows); ?>
  <div class="numgrid<?= count($w->rows) === 49 ? ' g7' : '' ?>" id="numgrid">
  <?php foreach ($w->rows as $r): ?>
    <a class="nc <?= $bands['map'][(int)$r['coupon_no']] ?>" href="#no<?= (int)$r['coupon_no'] ?>"
       title="<?= e($r['home']) ?> v <?= e($r['away']) ?>">
      <?= (int)$r['coupon_no'] ?><i><?= $r['p_draw'] === null ? '–' : round((float)$r['p_draw'] * 100) ?></i>
    </a>
  <?php endforeach; ?>
  </div>

  <p class="numkey">
    <span><b class="k3"></b>strongest: <?= (int)$bands['hi'] ?>% or more</span>
    <?php if ($bands['mid'] < $bands['hi']): ?><span><b class="k2"></b>middle: <?= (int)$bands['mid'] ?>% to <?= (int)$bands['hi'] - 1 ?>%</span><?php endif; ?>
    <span><b class="k1"></b>under <?= (int)$bands['mid'] ?>%</span>
    <?php if (in_array('na', $bands['map'], true)): ?><span><b class="k0"></b>not quoted</span><?php endif; ?>
  </p>

  <?php
  // if the market barely separates the coupon, say so rather than implying a
  // confident shortlist
  $ps = array();
  foreach ($w->rows as $r) { if ($r['p_draw'] !== null) { $ps[] = (float)$r['p_draw']; } }
  sort($ps);
  $spread = $ps ? (end($ps) - $ps[0]) * 100 : 0;
  ?>

</section>

<section class="d-top">
  <h2>Top draw games this week</h2>
  <p class="sub">Highest market chance of a draw</p>
  <?php
  $nStrong = 0;
  foreach ($bands['map'] as $bn) { if ($bn === 's3') { $nStrong++; } }
  ?>
  <?php if ($nStrong > 6): ?>
    <p class="lede"><?= (int)$nStrong ?> numbers are shaded solid on the board at
       <?= (int)$bands['hi'] ?>% or more. These six lead the list.</p>
  <?php endif; ?>
  <?php if ($spread < 8): ?>
    <p class="lede">The market sees little between most of this coupon —
       <?= number_format($spread, 0) ?> points separate the strongest number from the weakest.
       Treat the order below as a lean, not a shortlist.</p>
  <?php endif; ?>

  <div class="ranked">
  <?php
  $top = $w->rankedByDraw(6);
  $hi  = $ps ? end($ps) : 0;
  foreach ($top as $r):
      $p = $r['p_draw'] === null ? 0 : (float)$r['p_draw'];
      $bar = $hi > 0 ? max(6, round($p / $hi * 100)) : 0;
  ?>
    <div class="r<?= $r['books'] == 0 ? ' unpriced' : '' ?>">
      <div class="no"><?= (int)$r['coupon_no'] ?><small>NO.</small></div>
      <div class="mid">
        <p class="t"><?= e($r['home']) ?> v <?= e($r['away']) ?></p>
        <?php if ($r['books'] > 0): ?>
          <div class="bar"><span style="width:<?= (int)$bar ?>%"></span></div>
        <?php endif; ?>
        <p class="l"><?php
          echo $r['league'] !== '' ? e($r['league']) : 'league unknown';
          if ($r['country'] !== '') { echo ' · ' . e($r['country']); } ?></p>
      </div>
      <div class="rt">
        <?php if ($r['books'] == 0): ?>
          <p class="na">not quoted</p>
        <?php else: ?>
          <p class="pc"><?= pct($r['p_draw']) ?></p>
          <p class="sub"><?= price($r['best_draw_price']) ?> <?= e($r['best_draw_book']) ?></p>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>
  </div>
  <?php $off = $w->offNumbers(); if ($off && $state !== Week::SETTLED): ?>
    <p class="lede">Not ranked: <?= e(implode(', ', array_map('intval', $off))) ?>
       — postponed, called off or with the Panel, so there is no match to pick.</p>
  <?php endif; ?>
  <?php
  $waNums = array();
  foreach ($top as $r) { if ((int)$r['books'] > 0) { $waNums[] = (int)$r['coupon_no']; } }
  if ($waNums):
      $waText = 'Week ' . (int)$w->week . " draws, the six the betting market rates likeliest:\n"
              . implode('  ', $waNums)
              . "\nMarket prices, not tips. None of these is certain.\n" . $config['site']['base'] . '/';
  ?>
  <a class="wa" href="https://wa.me/?text=<?= e(rawurlencode($waText)) ?>" target="_blank" rel="noopener">
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M12 2a10 10 0 0 0-8.6 15.1L2 22l5-1.3A10 10 0 1 0 12 2Zm5.3 14.2c-.2.6-1.3 1.2-1.8 1.2-.5.1-1 .2-3.3-.7-2.8-1.1-4.6-3.9-4.7-4.1-.1-.2-1.1-1.5-1.1-2.8 0-1.4.7-2 1-2.3.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .6l-.4.5-.3.4c-.1.1-.3.3-.1.6.2.3.8 1.3 1.7 2.1 1.2 1 2.1 1.4 2.4 1.5.3.1.5.1.6-.1l.9-1c.2-.3.4-.2.7-.1l1.9.9c.3.1.5.2.5.3.1.2.1.6-.1 1.2Z"/></svg>
    Share these six on WhatsApp
  </a>
  <?php endif; ?>
</section>
<div class="d-promo"><?php promoBanner(); ?></div>
<?php else: ?>
<section class="d-board">
  <h1>Week <?= (int)$w->week ?> Pool Results <?= (int)$w->year ?><?= $state === Week::SETTLED ? '' : ' — live' ?></h1>

  <p class="lede">Every number on the coupon, coloured by how it finished.<?= $state === Week::SETTLED ? '' : ' Anything still running is provisional and can change.' ?></p>
  <div class="numgrid board<?= count($w->rows) === 49 ? ' g7' : '' ?>">
  <?php foreach ($w->rows as $r):
      // one colour per outcome, used identically on the board, the table and
      // the archive so the meaning is learned once
      $map = array('score_draw' => 'sd', 'no_score_draw' => 'sd',
                   'home' => 'home', 'away' => 'away', 'void' => 'void');
      $cls = isset($map[$r['classification']]) ? $map[$r['classification']] : '';
  ?>
    <a class="nc <?= $cls ?><?= (!$r['settled'] && $cls !== '') ? ' prov' : '' ?>"
       href="#no<?= (int)$r['coupon_no'] ?>"
       title="<?= e($r['home']) ?> v <?= e($r['away']) ?><?= $r['home_goals'] === null ? '' : ' — ' . e(scoreLabel($r)) ?><?= $r['settled'] ? '' : ' (' . strip_tags(statusBadge($r, $multi)) . ')' ?>"><?= (int)$r['coupon_no'] ?></a>
  <?php endforeach; ?>
  </div>
  <?php /* The key has to name every colour the board can show. It listed
           three while the board painted five, so home and away were unlabelled
           blocks of colour. */ ?>
  <p class="numkey">
    <span><b class="bsd"></b>draw</span>
    <span><b class="bhome"></b>home win</span>
    <span><b class="baway"></b>away win</span>
    <span><b class="k0"></b><?= $state === Week::SETTLED ? 'void' : 'not finished' ?></span>
  </p>
</section>
<div class="d-promo"><?php promoBanner(); ?></div>
<?php endif; ?>

<?php /* The `top` slot used to sit here, between the ranking and the table.
         On a phone that put a 250px block in the middle of the one journey
         people actually make — shortlist, then scroll the 49. One unit below
         the table earns nearly as much and interrupts nothing.

         Note for later: never hide an ad unit with CSS to thin the page out.
         A unit that renders into a hidden container still counts an
         impression, and impressions nobody can see is how accounts get
         flagged. Don't emit it. */ ?>

<section class="d-table">
  <h2>All <?= (int)$summary['total'] ?> matches</h2>
  <div class="filters" id="filters">
    <span class="lbl">Show</span>
    <button class="f on"  data-filter="all">Coupon order</button>
    <?php if ($isLive): ?><button class="f" data-filter="playing">In play first</button><?php endif; ?>
    <?php if ($state === Week::PRICED): ?><button class="f" data-filter="strongest">Strongest first</button>
    <?php else: ?><button class="f" data-filter="draws">Draws only</button><?php endif; ?>
    <button class="f" data-filter="mine">My numbers</button>
    <input class="mine" id="mine" placeholder="e.g. 3 7 12 24" inputmode="numeric">
    <button class="f save" id="mineSave" hidden>Save to this device</button>
    <span class="mine-saved" id="mineSaved" hidden>saved</span>
  </div>
  <?php if ($state === Week::PRICED): ?><p class="mine-hint">Tap My numbers, type yours, then Save to keep them on this device.</p><?php endif; ?>
  <?php if ($state === Week::PRICED && isset($bands)): ?>
  <?php /* Chance bands: the same three the board is shaded in, named in the same words as its key. A second tap clears the choice. */ ?>
  <div class="filters bandfilters" id="bandFilters" role="group" aria-label="Filter by draw chance">
    <span class="lbl">Chance</span>
    <button type="button" class="f" data-band="s3" aria-pressed="false"><?= (int)$bands['hi'] ?>% or more</button>
    <?php if ($bands['mid'] < $bands['hi']): ?><button type="button" class="f" data-band="s2" aria-pressed="false"><?= (int)$bands['mid'] ?>% to <?= (int)$bands['hi'] - 1 ?>%</button><?php endif; ?>
    <button type="button" class="f" data-band="s1" aria-pressed="false">Under <?= (int)$bands['mid'] ?>%</button>
  </div>
  <?php endif; ?>

  <?php
  // 1 / X / 2 — the pools notation: home win, draw, away win
  $markOf = array('home' => '1', 'score_draw' => 'X', 'no_score_draw' => 'X', 'away' => '2');
  $leagueOf = function ($r) {
      $l = trim((string)$r['league']);
      $ct = trim((string)$r['country']);
      if ($l === '') { return $ct; }
      return ($ct === '' || $ct === 'England') ? $l : $ct . ' · ' . $l;
  };
  $isPriced = $state === Week::PRICED;

  // League headings. The coupon order is the official order, so only CONSECUTIVE lines of the same league are grouped:
  // the numbers never move. $runOf[row index] = group number, $runN[group number] = how many lines it holds.
  $runOf = array(); $runN = array(); $ri = -1; $lastLg = null;
  foreach ($w->rows as $i0 => $r0) {
      $k0 = $leagueOf($r0);
      if ($k0 !== $lastLg) { $ri++; $lastLg = $k0; $runN[$ri] = 0; }
      $runOf[$i0] = $ri; $runN[$ri]++;
  }
  $prevRun = -1; $lgCols = $isPriced ? 4 : 5;
  ?>
  <table class="coupon fx fx-<?= e($state) ?> by-league" id="coupon" role="table" aria-label="All <?= (int)$summary['total'] ?> numbers on the coupon">
    <thead role="rowgroup"><tr role="row">
      <th role="columnheader">No.</th><th role="columnheader">Match</th>
      <?php if ($isPriced): ?>
        <th role="columnheader" class="c">Draw chance</th><th role="columnheader" class="r">Best price</th>
      <?php else: ?>
        <th role="columnheader" class="c">Score</th><th role="columnheader" class="c">Status</th><th role="columnheader" class="c">Result</th>
      <?php endif; ?>
    </tr></thead>
    <tbody role="rowgroup">
    <?php foreach ($w->rows as $ix => $r):
        $cl      = (string)$r['classification'];
        $final   = (int)$r['settled'] === 1;
        $started = !($r['status'] === '' || strtoupper((string)$r['status']) === 'NS');
        $mark    = isset($markOf[$cl]) ? $markOf[$cl] : ($cl === 'void' ? 'void' : '');
        $win     = $final ? ($cl === 'home' ? 'h' : ($cl === 'away' ? 'a' : '')) : '';
        $isTop   = $isPriced && isset($bands['map'][(int)$r['coupon_no']]) && $bands['map'][(int)$r['coupon_no']] === 's3';
        $rowCls  = 'c-' . e($cl)
                 . (isDraw($r) ? ' draw' : '')
                 . ($isTop ? ' top' : '')
                 . ($r['books'] == 0 ? ' unpriced' : '')
                 . (Week::oneGoalAway($r) ? ' close' : '')
                 . ($final ? ' final' : '')
                 . (!$isPriced && !$started ? ' nostart' : '');
        $lg      = $leagueOf($r);
    ?>
      <?php if ((int)$r['coupon_no'] === 25 && $state === Week::SETTLED): ?>
        <tr class="adrow" role="row" data-lgno="24.4"><td role="cell" colspan="5"><?php adSlot('mid', $state); ?></td></tr>
      <?php endif; ?>
      <?php if ($runOf[$ix] !== $prevRun): $prevRun = $runOf[$ix]; $gn = (int)$runN[$runOf[$ix]]; ?>
        <tr class="lgrow" role="row" data-lgno="<?= (int)$r['coupon_no'] - 0.5 ?>"><td role="cell" class="lgh" colspan="<?= (int)$lgCols ?>"><span class="lgt"><?= e($lg !== '' ? $lg : 'League unknown') ?></span><span class="lgc"><?= $gn ?> <?= $gn === 1 ? 'match' : 'matches' ?></span></td></tr>
      <?php endif; ?>
      <tr role="row" id="no<?= (int)$r['coupon_no'] ?>" data-no="<?= (int)$r['coupon_no'] ?>"
          data-band="<?= $isPriced && isset($bands['map'][(int)$r['coupon_no']]) ? ($bands['map'][(int)$r['coupon_no']] === '' ? 's1' : e($bands['map'][(int)$r['coupon_no']])) : '' ?>"
          data-draw="<?= isDraw($r) ? 1 : 0 ?>"
          data-p="<?= $r['p_draw'] === null ? -1 : (int)round((float)$r['p_draw'] * 1000) ?>"
          data-playing="<?= (!$r['settled'] && $r['status'] !== '' && strtoupper($r['status']) !== 'NS') ? 1 : 0 ?>"
          class="<?= $rowCls ?>">
        <td role="cell" class="no"><?= (int)$r['coupon_no'] ?></td>
        <td role="cell" class="m">
          <span class="tms"><span class="tm h<?= $win === 'h' ? ' w' : '' ?>"><?= e($r['home']) ?></span><span class="vs"> v </span><span class="tm a<?= $win === 'a' ? ' w' : '' ?>"><?= e($r['away']) ?></span></span>
          <small class="lg"><span class="lgn"><?= e($lg) ?></span><?php
            if ($isPriced) {
                echo '<span class="sep">·</span><span class="kt">' . e(fmtDate($r['kickoff_utc'], $multi ? 'D H:i' : 'H:i')) . '</span>';
            } else {
                if ($r['p_draw'] !== null) {
                    echo '<span class="pd" title="The market&#39;s chance of a draw before kick-off"><span class="sep">·</span>' . e(pct($r['p_draw'])) . '<span class="pdw"> draw</span></span>';
                }
                echo '<em class="cl"><span class="sep">·</span>one goal away</em>';
            }
          ?></small>
        </td>
        <?php if ($isPriced): ?>
          <td role="cell" class="c b pc" style="--w:<?= ($r['p_draw'] !== null && $mx > 0) ? (int)round((float)$r['p_draw'] / $mx * 100) : 0 ?>%"><?= pct($r['p_draw']) ?></td>
          <td role="cell" class="c pr"><?= price($r['best_draw_price']) ?><?php if ($r['best_draw_book'] !== ''): ?><small><?= e($r['best_draw_book']) ?></small><?php endif; ?></td>
        <?php else: ?>
          <?php $hs = $r['home_goals']; $as = $r['away_goals']; ?>
          <td role="cell" class="sc <?= scoreClass($r) ?>" data-score data-sc="<?= $hs === null ? '' : (int)$hs . '-' . (int)$as ?>"><?= $hs === null || $as === null ? '—' : '<b class="g">' . (int)$hs . '</b><i>–</i><b class="g">' . (int)$as . '</b>' ?></td>
          <?php /* While the week is running this is the match state: kick-off time, running minute,
                   HT or FT. Nobody can read a "1 – 1" without knowing whether it can still change. */ ?>
          <td role="cell" class="st" data-state><?= statusBadge($r, $multi) ?></td>
          <td role="cell" class="cls<?= ($mark !== '' && $mark !== 'void' && !$final) ? ' prov' : '' ?>" data-cls title="<?= e(classLabel($r)) ?>"><?= $mark === 'void' ? 'void' : e($mark) ?></td>
        <?php endif; ?>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</section>

<?php if ($state === Week::SETTLED): ?>
<section class="prose">
  <h2>How the market read week <?= (int)$w->week ?></h2>
  <p><?= (int)$summary['draws'] ?> of the <?= (int)$summary['total'] ?> matches
     drew. Beforehand the prices implied <?= number_format($summary['exp_draws'], 1) ?>
     draws. Every price quoted here was recorded before kick-off and has
     not been touched since — see the <a href="/record/">record</a> for how
     these numbers have held up across the season.</p>
  <p>Results are the score after 90 minutes, as the pools settle them. A match
     decided in extra time or on penalties was level after 90 minutes, so it
     counts as a draw.</p>
</section>
<?php endif; ?>

<?php /* The side column. On a phone it dissolves (display: contents) and its cards fall into the page in the order CSS gives them;
         from 1024px it is the third column of the dashboard. */ ?>
<div class="d-side">
<?php
// Search intent on this domain is overwhelmingly "week N results". When the
// current coupon has not been played, answer that question on the homepage
// instead of making people find the archive.
$prev = ($state === Week::PRICED && $isHome) ? Week::lastSettled($sb, $w->compId()) : null;
if ($prev):
    $ps = $prev->summary();
?>
<section class="lastweek">
  <div class="lw-head">
    <h2>Week <?= (int)$prev->week ?> results</h2>
    <span class="lw-sum"><?= (int)$ps['draws'] ?> draws from <?= (int)$ps['total'] ?></span>
    <a class="lw-more" href="<?= e($prev->url('')) ?>">Full results →</a>
  </div>
  <div class="lw-stats">
    <div><b><?= (int)$ps['total'] ?></b><small>MATCHES</small></div>
    <div><b><?= (int)$ps['draws'] ?></b><small>DRAWS</small></div>
    <div><b><?= $ps['settled'] > 0 ? round($ps['draws'] / $ps['settled'] * 100) : 0 ?>%</b><small>DRAW RATE</small></div>
  </div>
  <div class="numgrid board compact">
  <?php foreach ($prev->rows as $r):
      $map = array('score_draw' => 'sd', 'no_score_draw' => 'sd',
                   'home' => 'home', 'away' => 'away', 'void' => 'void');
      $cls = isset($map[$r['classification']]) ? $map[$r['classification']] : '';
  ?>
    <a class="nc <?= $cls ?>" href="<?= e($prev->url('')) ?>#no<?= (int)$r['coupon_no'] ?>"
       title="<?= e($r['home']) ?> v <?= e($r['away']) ?> — <?= e(scoreLabel($r)) ?>"><?= (int)$r['coupon_no'] ?></a>
  <?php endforeach; ?>
  </div>
  <p class="numkey">
    <span><b class="bsd"></b>draw</span>
    <span><b class="bhome"></b>home</span>
    <span><b class="baway"></b>away</span>
  </p>
</section>
<?php endif; ?>

<?php $recent = Week::recent($sb, 8); if (count($recent) > 1): ?>
<section class="weekstrip">
  <h2>Recent weeks</h2>
  <div class="strip">
  <?php foreach ($recent as $x):
      if ((int)$x['settled'] < 1) { continue; }
      // skip the week already on screen — "WK 13 · 0 SD · 0 NSD" next to the
      // week 13 coupon is noise, and it reads as though nothing drew
      if ((int)$x['week'] === (int)$w->week && (int)$x['year'] === (int)$w->year
          && $x['season'] === $w->season) { continue; }
      $u = '/week-' . (int)$x['week'] . '-' . (int)$x['year']
         . ($x['season'] === 'english' ? '' : '-' . $x['season']) . '/';
  ?>
    <a href="<?= e($u) ?>">
      <b>WK <?= (int)$x['week'] ?></b>
      <span><?= (int)$x['draws'] ?> draws</span>
    </a>
  <?php endforeach; ?>
    <a class="all" href="/archive/"><b>All</b><span><?= count(Week::archive($sb)) ?> weeks</span></a>
  </div>
</section>
<?php endif; ?>

<section class="d-about">
  <h2>About the predictions</h2>
  <p>These are the betting market's prices with the bookmakers' margin removed. They are for information and research only: market prices, not tips. Even the highest chance on the board fails more often than it comes in.</p>
  <p class="fine">18+ · Information service · We do not accept stakes. <a href="/guide/">Read the guide →</a></p>
</section>

<section class="d-explore">
  <h2>Explore more</h2>
  <ul>
    <li><a href="/draws/"><b>Draws</b><span>Numbers ranked by score-draw chance</span></a></li>
    <li><a href="/dead-games/"><b>Dead games</b><span>Numbers the market sees as least likely to draw</span></a></li>
    <li><a href="/archive/"><b>Archive</b><span>Past coupons and results</span></a></li>
    <li><a href="/record/"><b>Record</b><span>How the market prices have performed</span></a></li>
    <li><a href="/guide/"><b>Guide</b><span>How to read the coupon</span></a></li>
  </ul>
</section>
</div>

</div>

<?php crossBlock('strip'); ?>

<?php adSlot('foot', $state); ?>

</div>
<?php pageFoot();
