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

// Editing the public guidelines is an administrator action.
if (!in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied. Editing guidelines is restricted to administrators.');
}
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

$content_file = __DIR__ . '/../guidelines_content.html';
$msg = '';
$error = '';

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_guidelines'])) {
    $newContent = (string)($_POST['content'] ?? '');

    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $error = "Invalid request. Please reload the page and try again.";
    } elseif (!is_writable($content_file) && !(file_exists($content_file) === false && is_writable(dirname($content_file)))) {
        $error = "Cannot write to guidelines_content.html. Set file permissions to 664 (or 666 if your host requires it).";
    } else {
        $bytes = @file_put_contents($content_file, $newContent);
        if ($bytes === false) {
            $error = "Failed to write guidelines_content.html. Check file permissions.";
        } else {
            $msg = "Guidelines updated successfully (" . number_format($bytes) . " bytes written).";
        }
    }
}

// Read current content
$guidelines = is_readable($content_file) ? file_get_contents($content_file) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Edit Guidelines</title>
  <link rel="stylesheet" href="../styles.css">
  <style>
    .ag-wrap { max-width: 1080px; margin: 32px auto; padding: 0 24px; font-family: var(--serif, Georgia, serif); }
    .ag-head { display: flex; justify-content: space-between; align-items: baseline; gap: 16px; flex-wrap: wrap; padding-bottom: 14px; border-bottom: 1px solid var(--c-rule, #d8d4cc); margin-bottom: 22px; }
    .ag-head h2 { margin: 0; font-family: var(--display, Georgia, serif); font-weight: 400; font-size: 26px; color: var(--c-navy, #15294a); }
    .ag-meta { color: #888; font-size: 13px; font-style: italic; }
    .ag-help { background: #f4f8fc; border-left: 3px solid #7da3c6; padding: 12px 16px; margin-bottom: 18px; font-size: 13px; line-height: 1.55; color: #2a4d7a; }
    .ag-help code { background: rgba(0,0,0,0.04); padding: 1px 4px; border-radius: 2px; font-size: 12px; }
    textarea#guidelines-editor {
      width: 100%; height: 580px;
      font-family: ui-monospace, Consolas, 'SF Mono', Menlo, monospace;
      font-size: 13px; line-height: 1.55;
      padding: 16px; background: #fdfcf9;
      border: 1px solid var(--c-rule, #d8d4cc); border-radius: 2px;
      color: #1f1f1f; box-sizing: border-box;
    }
    textarea#guidelines-editor:focus { outline: 0; border-color: var(--c-blue, #2a4d7a); box-shadow: 0 0 0 3px rgba(42,77,122,0.15); }
    .ag-actions { display: flex; gap: 10px; align-items: center; margin-top: 16px; flex-wrap: wrap; }
    .ag-actions a.preview { color: #2a4d7a; font-size: 14px; font-style: italic; }
    .msg-bar { padding: 10px 14px; border-radius: 2px; font-size: 14px; margin-bottom: 14px; }
    .msg-bar.ok  { background: #ecf2e6; border-left: 3px solid #5a7d4f; color: #3a5a32; }
    .msg-bar.err { background: #fbeae9; border-left: 3px solid #8c3a4a; color: #6a2531; }
  </style>
</head>
<body>

<?php
include_once(__DIR__ . '/header.php');
include_once(__DIR__ . '/editors-menu.php');
?>

<div class="ag-wrap">
  <div class="ag-head">
    <h2>Edit Submission Guidelines</h2>
    <div class="ag-meta">
      <?= file_exists($content_file)
            ? 'Last modified ' . htmlspecialchars(date('M j, Y g:i a', filemtime($content_file)), ENT_QUOTES, 'UTF-8')
            : 'File does not exist yet' ?>
    </div>
  </div>

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

  <div class="ag-help">
    Edit the guidelines as raw HTML. Use the existing tags (<code>&lt;h2&gt;</code>, <code>&lt;p&gt;</code>, <code>&lt;ul&gt;</code>,
    <code>&lt;ol&gt;</code>, <code>&lt;aside class="callout"&gt;</code>, <code>&lt;hr class="ornament" /&gt;</code>) to keep the page styled correctly.
    Saving here writes directly to <code>guidelines_content.html</code>; it goes live the moment you click <em>Save</em>.
  </div>

  <form method="post">
    <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
    <textarea id="guidelines-editor" name="content" spellcheck="false"><?= htmlspecialchars($guidelines, ENT_QUOTES, 'UTF-8') ?></textarea>
    <div class="ag-actions">
      <input type="submit" name="update_guidelines" value="Save Guidelines" class="button-primary">
      <a class="preview" href="../guidelines.php" target="_blank" rel="noopener">Preview the live page →</a>
    </div>
  </form>
</div>

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

</body>
</html>
