<?php
/**
 * Editor admin: Contributors Visibility / bio cleanup.
 *
 * Lists every poet who has at least one accepted submission. Admin can:
 *   - Toggle each contributor's visibility on the public Contributors page
 *   - Edit/clean up their bio (bio_sanitize applied for safety)
 *
 * Note: poets can also manage these themselves in My Profile / My Biography.
 * This tool is the editor override.
 */
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__ . '/../bio_sanitize.php');

$editor_type = (string)($_SESSION['editor_type'] ?? '');
if ($editor_type !== 'admin' && $editor_type !== 'superadmin') {
    http_response_code(403);
    exit('Access denied. Contributors Visibility is restricted to administrators.');
}

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

$msg = '';
$err = '';

// --- Save handler --------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $token = (string)($_POST['csrf_token'] ?? '');
    if ($token === '' || !hash_equals($_SESSION['ea_csrf'], $token)) {
        $err = 'Submission rejected (token mismatch). Reload the page and try again.';
    } else {
        try {
            $pdo->beginTransaction();

            // Build the list of currently-visible contributors (those NOT hidden).
            // Only act on poets who appear on this page (i.e. have an accepted
            // submission) so we don't trample the visibility flag of poets the
            // admin can't see.
            $visible_ids = $pdo->query(
                "SELECT DISTINCT b.id
                 FROM sm_submissions a
                 INNER JOIN sm_poets b ON a.poetid = b.id
                 WHERE a.status = 1"
            )->fetchAll(PDO::FETCH_COLUMN, 0);
            $visible_ids = array_map('intval', $visible_ids);

            $hidden_ids = [];
            if (!empty($_POST['no_authors_page']) && is_array($_POST['no_authors_page'])) {
                foreach ($_POST['no_authors_page'] as $aid) {
                    if (ctype_digit((string)$aid)) {
                        $hidden_ids[] = (int)$aid;
                    }
                }
            }
            // Only hide poets that are actually on this list
            $hidden_ids = array_values(array_intersect($hidden_ids, $visible_ids));
            $unhide_ids = array_values(array_diff($visible_ids, $hidden_ids));

            if (!empty($hidden_ids)) {
                $ph = implode(',', array_fill(0, count($hidden_ids), '?'));
                $stmt = $pdo->prepare("UPDATE sm_poets SET no_authors_page = 1 WHERE id IN ($ph)");
                foreach ($hidden_ids as $i => $id) $stmt->bindValue($i + 1, $id, PDO::PARAM_INT);
                $stmt->execute();
            }
            if (!empty($unhide_ids)) {
                $ph = implode(',', array_fill(0, count($unhide_ids), '?'));
                $stmt = $pdo->prepare("UPDATE sm_poets SET no_authors_page = 0 WHERE id IN ($ph)");
                foreach ($unhide_ids as $i => $id) $stmt->bindValue($i + 1, $id, PDO::PARAM_INT);
                $stmt->execute();
            }

            // Bio updates -- only for rows the admin explicitly checked "Save This Update"
            $bio_updated = 0;
            if (!empty($_POST['edit_id']) && is_array($_POST['edit_id'])) {
                $bio_stmt = $pdo->prepare("UPDATE sm_poets SET bio = :bio WHERE id = :id");
                foreach ($_POST['edit_id'] as $eid) {
                    if (!ctype_digit((string)$eid)) continue;
                    $eid_int = (int)$eid;
                    $raw = (string)($_POST['bio'][$eid_int] ?? '');
                    $clean = bio_sanitize($raw);
                    $clean = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $clean);
                    $bio_stmt->bindValue(':bio', $clean, PDO::PARAM_STR);
                    $bio_stmt->bindValue(':id',  $eid_int, PDO::PARAM_INT);
                    $bio_stmt->execute();
                    $bio_updated++;
                }
            }

            $pdo->commit();
            $_SESSION['ea_csrf'] = bin2hex(random_bytes(32));
            $msg = 'Visibility saved'
                 . (count($hidden_ids) ? ' (' . count($hidden_ids) . ' hidden, ' . count($unhide_ids) . ' visible)' : '')
                 . ($bio_updated ? '. ' . $bio_updated . ' bio' . ($bio_updated === 1 ? '' : 's') . ' updated.' : '.');
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log('editors-authors save: ' . $e->getMessage());
            $err = 'Could not save changes. Check the error log.';
        }
    }
}

// --- Fetch list ----------------------------------------------------
$rows = [];
try {
    $rows = $pdo->query(
        "SELECT DISTINCT b.id, b.author_name, b.author_lastname, b.pen_name,
                b.email, b.signup_date, b.bio, b.no_authors_page
         FROM sm_submissions a
         INNER JOIN sm_poets b ON a.poetid = b.id
         WHERE a.status = 1
         ORDER BY b.author_lastname, b.author_name"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('editors-authors list: ' . $e->getMessage());
    $err = 'Could not load contributor list.';
}

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

<div class="container" style="max-width: 1100px; padding: 30px 36px;">
  <h2 style="text-align: left;">Biographies of Accepted Contributors</h2>
  <p style="color: var(--c-slate); font-style: italic; margin-bottom: 14px;">
    <?= count($rows) ?> contributor<?= count($rows) === 1 ? '' : 's' ?> with at least one accepted submission.
    Tick <em>Hide from Public View</em> to keep them out of <code>biographies.php</code>.
    To clean up a bio, edit and tick <em>Save This Update</em>.
  </p>

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

  <form method="post" action="editors-authors.php">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['ea_csrf'], ENT_QUOTES, 'UTF-8') ?>">
    <p style="text-align: right; margin: 8px 0;">
      <input type="submit" name="update" value="Save Changes" class="button-primary">
    </p>
    <table>
      <tr>
        <th>Registered</th>
        <th>Name</th>
        <th>Email</th>
        <th>Biography</th>
        <th>Visibility</th>
      </tr>
      <?php foreach ($rows as $row):
        $id      = (int)$row['id'];
        $reg     = $row['signup_date'] ? date('M. d, Y', strtotime($row['signup_date'])) : '';
        $first   = (string)($row['author_name'] ?? '');
        $last    = (string)($row['author_lastname'] ?? '');
        $pen     = trim((string)($row['pen_name'] ?? ''));
        $name    = $pen !== '' ? $pen : trim($first . ' ' . $last);
        $email   = (string)($row['email'] ?? '');
        $bio     = (string)($row['bio'] ?? '');
        $hidden  = !empty($row['no_authors_page']);
      ?>
        <tr>
          <td style="font-size: 12px; white-space: nowrap;"><?= htmlspecialchars($reg, ENT_QUOTES, 'UTF-8') ?></td>
          <td style="font-size: 13px;">
            <a href="user_history.php?poetid=<?= $id ?>" target="_blank" rel="noopener"><?= htmlspecialchars($name, 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: 12px;"><a href="mailto:<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></a></td>
          <td>
            <textarea name="bio[<?= $id ?>]" style="width: 100%; min-width: 360px; height: 80px; font-size: 12px;"><?= htmlspecialchars($bio, ENT_QUOTES, 'UTF-8') ?></textarea>
            <br><label style="font-size: 11px;"><input type="checkbox" name="edit_id[]" value="<?= $id ?>" style="width: auto;"> Save This Update</label>
          </td>
          <td style="text-align: center;">
            <label style="font-size: 12px;">
              <input type="checkbox" value="<?= $id ?>" name="no_authors_page[]" <?= $hidden ? 'checked' : '' ?> style="width: auto;">
              Hide
            </label>
          </td>
        </tr>
      <?php endforeach; ?>
      <tr>
        <td colspan="4"></td>
        <td style="text-align: center;"><input type="submit" name="update" value="Save Changes" class="button-primary"></td>
      </tr>
    </table>
  </form>
</div>

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