<?php
require_once('../common.php');
require_once('checklogin.php');

// Display settings (use the new key names from fine_settings, with
// legacy fallbacks so older installs still work).
$showscore       = settingGet('show_score')        ?: settingGet('showscore');
$showipaddress   = settingGet('show_ip_address')   ?: settingGet('showipaddress');
$showpaymenttype = settingGet('show_payment_types') ?: settingGet('showpaymenttype');

$msg = '';
if (isset($_GET['delete']) && ctype_digit((string)$_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];
    $poet_id   = (int)($cPoet['id'] ?? 0);
    $stmt = $pdo->prepare("DELETE FROM sm_submissions WHERE id = :delete_id AND poetid = :poet_id");
    $stmt->bindValue(':delete_id', $delete_id, PDO::PARAM_INT);
    $stmt->bindValue(':poet_id',   $poet_id,   PDO::PARAM_INT);
    if ($stmt->execute()) {
        $msg = 'Submission deleted.';
    }
}

// Sort handling
$allowed_sorts = ['date_submitted', 'title', 'author_name', 'type', 'ip_address', 'email', 'editionid', 'ptype'];
$sort  = (isset($_REQUEST['sort']) && in_array($_REQUEST['sort'], $allowed_sorts, true)) ? $_REQUEST['sort'] : 'date_submitted';
$order = (isset($_REQUEST['order']) && strtolower($_REQUEST['order']) === 'asc') ? 'ASC' : 'DESC';
$next_order = $order === 'ASC' ? 'desc' : 'asc';

$sort_link = function (string $col, string $label) use ($sort, $next_order, $order): string {
    $marker = ($sort === $col) ? ($order === 'ASC' ? ' ▲' : ' ▼') : '';
    return '<a href="?sort=' . urlencode($col) . '&order=' . urlencode($next_order) . '">'
         . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . $marker . '</a>';
};

include_once('header.php');
include_once('editors-menu.php');

// Priority reading floats to the top of the slush pile: any paid submission
// (contest entry) reads first. The chosen column is the tiebreaker within
// each group.
$query = "SELECT a.*, a.id AS sid, b.email, b.author_name, b.author_lastname, b.pen_name,
                 (a.ptype = 'paid') AS is_priority
          FROM sm_submissions AS a
          INNER JOIN sm_poets AS b ON a.poetid = b.id
          WHERE a.status = 0
          ORDER BY is_priority DESC, $sort $order";
$rows = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container">
  <h2>Slush Pile</h2>
  <p class="lede" style="color: var(--c-slate); font-style: italic; margin: 4px 0 18px;">
    <?= count($rows) ?> pending submission<?= count($rows) === 1 ? '' : 's' ?> awaiting editorial decision.
    <?php if ($sort !== 'date_submitted' || $order !== 'DESC'): ?>
      &middot; <a href="editors-subs.php" style="font-size: 13px;">reset sort</a>
    <?php endif; ?>
  </p>

  <?php if ($msg !== ''): ?>
    <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>
  <?php endif; ?>

  <form method="post" action="editors-update-edition.php">
    <table class="slush-table">
      <thead>
        <tr>
          <th style="width: 36px;"></th>
          <th><?= $sort_link('date_submitted', 'Submitted') ?></th>
          <th><?= $sort_link('title', 'Title') ?></th>
          <th><?= $sort_link('author_name', 'Contributor') ?></th>
          <th><?= $sort_link('type', 'Type') ?></th>
          <?php if ($showscore == 'yes'): ?>
            <th>Score</th>
          <?php endif; ?>
          <?php if ($showipaddress == 'yes'): ?>
            <th><?= $sort_link('ip_address', 'IP') ?></th>
          <?php endif; ?>
          <th><?= $sort_link('email', 'Email') ?></th>
          <th><?= $sort_link('editionid', 'Edition') ?></th>
          <?php if ($showpaymenttype == 'yes'): ?>
            <th><?= $sort_link('ptype', 'Payment') ?></th>
          <?php endif; ?>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $row):
          $sid             = (int)$row['sid'];
          $is_paid         = ($row['ptype'] ?? 'free') === 'paid';
          $is_priority     = !empty($row['is_priority']);
          $date_submitted  = date('M j, Y · g:ia', strtotime($row['date_submitted']));
          $title           = (string)($row['title'] ?? '');
          $first           = (string)($row['author_name'] ?? '');
          $last            = (string)($row['author_lastname'] ?? '');
          $pen             = trim((string)($row['pen_name'] ?? ''));
          $contrib_display = $pen !== '' ? $pen : trim($first . ' ' . $last);
          $type            = (string)($row['type'] ?? '');
          $email           = (string)($row['email'] ?? '');
          $edition_name    = function_exists('getEditionName') ? (string)getEditionName($row['editionid']) : '';
          $payment_type    = (string)($row['ptype'] ?? 'free');
          $ip_address      = (string)($row['ip_address'] ?? '');
        ?>
          <tr<?= $is_priority ? ' class="row-paid"' : '' ?>>
            <td><input type="checkbox" name="checked[]" value="<?= (int)$row['editionid'] ?>_<?= $sid ?>"></td>
            <td style="white-space: nowrap; font-size: 13px; color: var(--c-slate);"><?= htmlspecialchars($date_submitted, ENT_QUOTES, 'UTF-8') ?></td>
            <td>
              <a href="view-submission.php?id=<?= $sid ?>"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></a>
              <?php if ($is_paid): ?>
                <span class="paid-pill">PAID</span>
              <?php endif; ?>
            </td>
            <td>
              <a href="user_history.php?poetid=<?= (int)$row['poetid'] ?>" target="_blank" rel="noopener"><?= htmlspecialchars($contrib_display, ENT_QUOTES, 'UTF-8') ?></a>
              <?php if ($pen !== ''): ?>
                <br><small style="color: var(--c-slate);"><?= htmlspecialchars(trim($first . ' ' . $last), ENT_QUOTES, 'UTF-8') ?></small>
              <?php endif; ?>
            </td>
            <td style="font-size: 13px;"><?= htmlspecialchars($type, ENT_QUOTES, 'UTF-8') ?></td>
            <?php if ($showscore == 'yes'): ?>
              <td style="text-align: center; font-variant-numeric: tabular-nums;"><?= htmlspecialchars((string)getAverageRating($row['sid']), ENT_QUOTES, 'UTF-8') ?></td>
            <?php endif; ?>
            <?php if ($showipaddress == 'yes'): ?>
              <td style="font-family: ui-monospace, Consolas, monospace; font-size: 12px; color: var(--c-slate);"><?= htmlspecialchars($ip_address, ENT_QUOTES, 'UTF-8') ?></td>
            <?php endif; ?>
            <td style="font-size: 13px;">
              <a href="mailto:<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></a>
            </td>
            <td style="font-size: 13px;"><?= htmlspecialchars($edition_name, ENT_QUOTES, 'UTF-8') ?></td>
            <?php if ($showpaymenttype == 'yes'): ?>
              <td style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: <?= $is_paid ? 'var(--c-brass-deep)' : 'var(--c-slate)' ?>;"><?= htmlspecialchars($payment_type, ENT_QUOTES, 'UTF-8') ?></td>
            <?php endif; ?>
            <td style="white-space: nowrap;">
              <a href="editors-update-status.php?id=<?= $sid ?>" class="action-link">Update&nbsp;Status</a>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($rows)): ?>
          <tr><td colspan="11" style="text-align: center; padding: 32px 12px; color: #888; font-style: italic;">The slush pile is empty. 🎉</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <?php if (!empty($rows)): ?>
      <div style="margin-top: 16px; text-align: right;">
        <input type="submit" name="submit" value="Move Selected to Another Edition" class="button-primary">
      </div>
    <?php endif; ?>
  </form>
</div>

<style>
  .slush-table { width: 100%; }
  .slush-table thead th a { color: var(--c-navy); border: 0; }
  .slush-table thead th a:hover { color: var(--c-brass-deep); }
  .slush-table .row-paid td { background: rgba(176, 133, 66, 0.08); }
  .slush-table .row-paid:hover td { background: rgba(176, 133, 66, 0.18); }
  .slush-table .paid-pill {
    display: inline-block;
    margin-left: 6px;
    padding: 1px 8px;
    color: #fff;
    font-family: var(--sans);
    font-size: 10px;
    letter-spacing: 0.14em;
    border-radius: 2px;
    vertical-align: middle;
    background: var(--c-brass);
  }
  .slush-table .action-link {
    display: inline-block;
    padding: 4px 10px;
    background: var(--c-frost);
    color: var(--c-navy);
    font-family: var(--sans);
    font-size: 11px;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    border: 1px solid var(--c-rule);
    border-radius: 2px;
  }
  .slush-table .action-link:hover {
    background: var(--c-navy);
    color: #fff;
    border-color: var(--c-navy);
  }
</style>

<?php include_once('footer.php'); ?>
