<?php
/**
 * Editor admin: grant submission credits to a poet.
 *
 * Search by name/email/id, see balance + history, grant N credits with
 * a reason. CSRF-protected, prepared statements, audit trail via the
 * ledger.
 */
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once(__DIR__ . '/../common.php');
require_once(__DIR__ . '/checklogin.php');
require_once(__DIR__ . '/../credits.php');

// Restrict to admin / superadmin (regular editors and readers should not
// be able to grant credits, since that's effectively spending money).
$editor_type = (string)($_SESSION['editor_type'] ?? '');
if ($editor_type !== 'admin' && $editor_type !== 'superadmin') {
    http_response_code(403);
    exit('Access denied. Submission Credits is restricted to administrators.');
}

$editor_id = isset($_SESSION['editor_id']) ? (int)$_SESSION['editor_id'] : null;

if (empty($_SESSION['ec_csrf'])) {
    $_SESSION['ec_csrf'] = bin2hex(random_bytes(32));
}

$flash_msg = $_SESSION['ec_flash_msg'] ?? '';
$flash_err = $_SESSION['ec_flash_err'] ?? '';
unset($_SESSION['ec_flash_msg'], $_SESSION['ec_flash_err']);

// --- POST handler: grant credits -----------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['grant_credit'])) {
    $token = (string)($_POST['csrf_token'] ?? '');
    if ($token === '' || !hash_equals($_SESSION['ec_csrf'], $token)) {
        $_SESSION['ec_flash_err'] = 'Submission rejected (token mismatch).';
        header('Location: editors-credits.php', true, 303);
        exit;
    }

    $poet_id = isset($_POST['poet_id']) ? (int)$_POST['poet_id'] : 0;
    $amount  = isset($_POST['amount'])  ? (int)$_POST['amount']  : 0;
    $reason  = trim((string)($_POST['reason'] ?? ''));

    if ($poet_id <= 0)            { $_SESSION['ec_flash_err'] = 'Invalid poet id.'; }
    elseif ($amount === 0)        { $_SESSION['ec_flash_err'] = 'Amount must be non-zero.'; }
    elseif (abs($amount) > 100)   { $_SESSION['ec_flash_err'] = 'Amount must be between -100 and +100.'; }
    elseif ($reason === '')       { $_SESSION['ec_flash_err'] = 'A reason is required for the audit log.'; }
    else {
        // Confirm poet exists
        $check = $pdo->prepare('SELECT id FROM sm_poets WHERE id = :id');
        $check->bindValue(':id', $poet_id, PDO::PARAM_INT);
        $check->execute();
        if (!$check->fetchColumn()) {
            $_SESSION['ec_flash_err'] = 'No poet found with that id.';
        } else {
            $ok = credits_grant($pdo, $poet_id, $amount, $reason, $editor_id);
            if ($ok) {
                $_SESSION['ec_flash_msg'] = ($amount > 0 ? 'Granted ' : 'Deducted ') . abs($amount) . ' credit(s) for poet #' . $poet_id . '. New balance: ' . credits_balance($pdo, $poet_id) . '.';
                $_SESSION['ec_csrf'] = bin2hex(random_bytes(32));
            } else {
                $_SESSION['ec_flash_err'] = 'Could not write the credit. Check the error log.';
            }
        }
    }

    header('Location: editors-credits.php?q=' . urlencode((string)($_POST['q'] ?? '')), true, 303);
    exit;
}

// --- Search --------------------------------------------------------
$query = trim((string)($_GET['q'] ?? ''));
$matches = [];
if ($query !== '') {
    try {
        $like = '%' . $query . '%';
        if (ctype_digit($query)) {
            $stmt = $pdo->prepare("SELECT id, email, author_name, author_lastname, pen_name FROM sm_poets
                                   WHERE id = :id OR email LIKE :like OR author_name LIKE :like OR author_lastname LIKE :like OR pen_name LIKE :like
                                   ORDER BY author_lastname, author_name LIMIT 50");
            $stmt->bindValue(':id',   (int)$query, PDO::PARAM_INT);
            $stmt->bindValue(':like', $like,       PDO::PARAM_STR);
        } else {
            $stmt = $pdo->prepare("SELECT id, email, author_name, author_lastname, pen_name FROM sm_poets
                                   WHERE email LIKE :like OR author_name LIKE :like OR author_lastname LIKE :like OR pen_name LIKE :like OR CONCAT(author_name, ' ', author_lastname) LIKE :like
                                   ORDER BY author_lastname, author_name LIMIT 50");
            $stmt->bindValue(':like', $like, PDO::PARAM_STR);
        }
        $stmt->execute();
        $matches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        error_log('editors-credits search: ' . $e->getMessage());
    }
}

include_once(__DIR__ . '/header.php');
include_once(__DIR__ . '/editors-menu.php');
?>
<link rel="stylesheet" href="../styles.css">

<div class="container" style="max-width: 880px; padding: 36px 44px;">
  <h2 style="text-align: left;">Submission Credits</h2>
  <p style="color: var(--c-slate); font-style: italic; margin-bottom: 18px;">
    Grant or deduct paid-submission credits for a poet. Every change is logged in <code>sm_credits</code>.
  </p>

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

  <form method="get" action="editors-credits.php" style="display: flex; gap: 8px; margin-bottom: 24px;">
    <input type="search" name="q" placeholder="Search by name, email, pen name, or poet id…" value="<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>" style="flex: 1;">
    <button type="submit">Search</button>
  </form>

  <?php if ($query !== '' && empty($matches)): ?>
    <p style="color: var(--c-slate); font-style: italic;">No poets matched “<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>”.</p>
  <?php endif; ?>

  <?php foreach ($matches as $p):
    $bal     = credits_balance($pdo, (int)$p['id']);
    $history = credits_history($pdo, (int)$p['id'], 8);
    $real    = trim(($p['author_lastname'] ?? '') . ((!empty($p['author_lastname']) && !empty($p['author_name'])) ? ', ' : '') . ($p['author_name'] ?? ''));
    $name    = !empty($p['pen_name']) ? $p['pen_name'] . ' (' . $real . ')' : $real;
  ?>
    <details style="border: 1px solid var(--c-rule); border-left: 3px solid var(--c-brass); margin-bottom: 12px; padding: 0; background: #fff;" <?= count($matches) === 1 ? 'open' : '' ?>>
      <summary style="cursor: pointer; padding: 14px 20px; list-style: none; display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap;">
        <span style="font-family: var(--display); font-size: 18px;"><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></span>
        <span style="font-family: var(--sans); font-size: 12px; color: var(--c-slate); letter-spacing: 0.06em;">
          #<?= (int)$p['id'] ?> · <?= htmlspecialchars($p['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>
        </span>
        <span style="font-family: var(--sans); font-weight: 700; color: <?= $bal > 0 ? 'var(--c-moss)' : 'var(--c-slate)' ?>; font-size: 13px; letter-spacing: 0.1em;">
          BALANCE: <?= $bal ?>
        </span>
      </summary>

      <div style="padding: 0 20px 20px; border-top: 1px solid var(--c-faint);">
        <form method="post" action="editors-credits.php" style="margin: 18px 0; display: grid; grid-template-columns: 90px 1fr auto; gap: 8px; align-items: end;">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['ec_csrf'], ENT_QUOTES, 'UTF-8') ?>">
          <input type="hidden" name="poet_id"    value="<?= (int)$p['id'] ?>">
          <input type="hidden" name="q"          value="<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>">
          <div>
            <label style="font-size: 11px;">Amount</label>
            <input type="number" name="amount" min="-100" max="100" value="1" required>
          </div>
          <div>
            <label style="font-size: 11px;">Reason (audit log)</label>
            <input type="text" name="reason" placeholder="e.g. Goodwill credit" required maxlength="240">
          </div>
          <button type="submit" name="grant_credit" value="1" class="button-primary" style="padding: 10px 18px; align-self: end;">Apply</button>
        </form>

        <?php if (!empty($history)): ?>
          <div style="font-family: var(--sans); font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--c-brass-deep); font-weight: 700; margin-bottom: 6px;">Recent History</div>
          <table style="margin: 0 0 8px;">
            <thead>
              <tr><th>Date</th><th>Δ</th><th>Reason</th><th>By</th></tr>
            </thead>
            <tbody>
              <?php foreach ($history as $h): ?>
                <tr>
                  <td style="white-space: nowrap;"><?= htmlspecialchars(date('Y-m-d H:i', strtotime($h['created_at'])), ENT_QUOTES, 'UTF-8') ?></td>
                  <td style="font-weight: 600; color: <?= ((int)$h['amount'] > 0) ? 'var(--c-moss)' : 'var(--c-burgundy)' ?>;"><?= ((int)$h['amount'] > 0 ? '+' : '') . (int)$h['amount'] ?></td>
                  <td><?= htmlspecialchars((string)($h['reason'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                  <td style="color: var(--c-slate); font-size: 12px;"><?= $h['granted_by_editor_id'] ? 'editor #' . (int)$h['granted_by_editor_id'] : 'system' ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>
    </details>
  <?php endforeach; ?>
</div>

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