<?php
/**
 * index.php — Play & Win. The home screen, and a public one.
 *
 * Shows the current game(s) and works out, server-side, which of four calls
 * to action the visitor should get. The CRA made that decision in the browser
 * after the bundle loaded; here it's decided before the first byte goes out.
 */

require_once __DIR__ . '/inc/auth.php';

$page  = 'play';
$title = 'Play & Win · ' . APP_NAME;

$res    = api('current-game');
$games  = $res['data'] ?? null;
$me     = member();                       // null when signed out or the call failed
$rate   = $me['rates']['subscription'] ?? null;
$howto  = require __DIR__ . '/data/howtoplay.php';

/**
 * Which CTA does this visitor get? Ported from the Play CTA decision tree in
 * the CRA's pages/Play.js.
 *
 *   register  — we don't know who they are yet
 *   blocked   — subscription rate is negative, i.e. not sold in their country
 *   subscribe — known, but not subscribed or the payment is outstanding
 *   play      — good to go
 */
function play_state($me, $rate)
{
    if (!$me || empty($me['profile'])) {
        return 'register';
    }
    // The CRA nested this test inside `if (!rate || isNaN(rate))`, so it could
    // never actually fire for a negative rate. Account.js gates its subscribe
    // alert on `rate >= 0`, which confirms negative is meant to mean
    // "unavailable" — so the test runs properly here.
    if (is_numeric($rate) && $rate < 0) {
        return 'blocked';
    }
    if (($me['payment_active'] ?? null) === false || ($me['sub'] ?? null) === false) {
        return 'subscribe';
    }
    return 'play';
}

$state = play_state($me, $rate);

require __DIR__ . '/inc/header.php';
?>

<?php if ($games === null): ?>

  <div class="alert alert--error" role="alert">
    <strong>Couldn't load the game.</strong>
    Something went wrong reaching ArenaGames.
    <a class="btn btn--sm btn--ghost alert__action" href="<?= e(url('index.php')) ?>">Retry</a>
  </div>

<?php elseif (!$games): ?>

  <div class="alert alert--info" role="status">
    No game is running right now. Check back shortly!
  </div>

<?php else: ?>

  <?php foreach ($games as $game):
      $id     = $game['id'] ?? '';
      $href   = game_url($game['href'] ?? '');
      $label  = trim((string)($game['label'] ?? ''));
      $target = $game['target_score'] ?? null; ?>

    <article class="card game-card">
      <div class="game-card__media">
        <?php if ($id !== ''): ?>
          <img src="<?= e(game_banner($id)) ?>"
               data-fallback="<?= e(game_banner($id, 'jpg')) ?>"
               alt="<?= e($game['title'] ?? 'Game') ?>" width="440" height="280">
        <?php endif ?>

        <?php if ($target !== null): ?>
          <div class="game-card__flag" aria-hidden="true"></div>
          <div class="game-card__target">
            <span>Target Score</span>
            <b><?= e($target) ?></b>
            <img class="coin-img" src="<?= e(asset('assets/img/money.png')) ?>" alt="coins" width="24" height="24">
          </div>
        <?php endif ?>
      </div>

      <?php if ($label !== ''): ?>
        <div class="game-card__label"><?= e($label) ?></div>
      <?php endif ?>

      <div class="card__body">
        <h1 class="game-card__title"><?= e(clip($game['title'] ?? '', 29)) ?></h1>
        <p class="game-card__desc"><?= e(clip($game['description'] ?? '', 58, '..')) ?></p>

        <?php if ($state === 'blocked'): ?>

          <div class="alert alert--error" role="status">Not available in your country</div>

        <?php elseif ($state === 'register'): ?>

          <a class="btn btn--primary btn--block" href="<?= e(url('register.php')) ?>">Play</a>
          <p class="center" style="margin:.75rem 0 0"><small>Let's get your account ready to Play &amp; Win.</small></p>

        <?php elseif ($state === 'subscribe'): ?>

          <form method="post" action="<?= e(url('action.php')) ?>"
                data-confirm="You will receive free SMS notifications while playing this game. Please confirm your free subscription."
                data-confirm-title="<?= e(APP_NAME) ?>"
                data-confirm-ok="Continue"
                data-loading>
            <?php csrf_field() ?>
            <input type="hidden" name="do" value="pay">
            <input type="hidden" name="game_id" value="<?= e($id) ?>">
            <input type="hidden" name="game_title" value="<?= e($game['title'] ?? '') ?>">
            <button type="submit" class="btn btn--primary btn--block">Play</button>
          </form>

        <?php else: ?>

          <a class="btn btn--primary btn--block" href="<?= e($href) ?>"
             data-track="game_play"
             data-track-data='<?= e(json_encode(['id' => $id, 'game' => $game['title'] ?? ''])) ?>'>Play</a>

        <?php endif ?>
      </div>
    </article>

  <?php endforeach ?>

<?php endif ?>

<section style="margin-top:1.5rem">
  <h2 class="center">How to Play</h2>
  <ul class="howto">
    <?php foreach ($howto as $item): ?>
      <li>
        <b><?= e($item['title']) ?></b>
        <span><?= e($item['description']) ?></span>
      </li>
    <?php endforeach ?>
  </ul>
</section>

<?php require __DIR__ . '/inc/footer.php';
