<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';

$pollJsonFile = __DIR__ . '/../data/poll.json';
$votesJsonFile = __DIR__ . '/../data/poll_votes.json';
$pollTxtFile = __DIR__ . '/../data/poll.txt';
$votesTxtFile = __DIR__ . '/../data/poll_votes.txt';

function almostheaven_poll_read(string $pollJsonFile, string $votesJsonFile, string $pollTxtFile, string $votesTxtFile): array {
  $poll = ['question'=>'', 'options'=>[], 'show_on_home'=>1];
  $votes = [];

  if (file_exists($pollJsonFile)) {
    $json = smurf_read_json($pollJsonFile, []);
    if (is_array($json)) {
      $poll['question'] = (string)($json['question'] ?? '');
      $poll['options'] = array_values(array_filter(array_map('strval', (array)($json['options'] ?? [])), fn($v)=>trim($v)!==''));
      $poll['show_on_home'] = !empty($json['show_on_home']) ? 1 : 0;
    }
  } elseif (file_exists($pollTxtFile)) {
    $lines = file($pollTxtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    if ($lines) {
      $parts = explode('|', (string)$lines[0], 2);
      $poll['question'] = trim((string)($parts[0] ?? ''));
      $poll['show_on_home'] = 1;
      foreach (array_slice($lines, 1) as $line) {
        $opt = trim((string)explode('|', $line, 2)[0]);
        if ($opt !== '') $poll['options'][] = $opt;
      }
    }
  }

  if (file_exists($votesJsonFile)) {
    $jsonVotes = smurf_read_json($votesJsonFile, []);
    if (is_array($jsonVotes)) $votes = $jsonVotes;
  } elseif (file_exists($votesTxtFile)) {
    $lines = file($votesTxtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    foreach ($lines as $i => $line) {
      $votes[$i] = (int)$line;
    }
  }

  return [$poll, $votes];
}

function almostheaven_poll_write(array $poll, array $votes, string $pollJsonFile, string $votesJsonFile, string $pollTxtFile, string $votesTxtFile): void {
  smurf_write_json($pollJsonFile, $poll);
  smurf_write_json($votesJsonFile, $votes);

  $txtLines = [];
  $txtLines[] = trim((string)$poll['question']) . '|';
  foreach ((array)$poll['options'] as $opt) {
    $txtLines[] = trim((string)$opt) . '|';
  }
  file_put_contents($pollTxtFile, implode("\n", $txtLines) . (count($txtLines) ? "\n" : ""), LOCK_EX);

  $voteLines = [];
  foreach ((array)$poll['options'] as $i => $opt) {
    $voteLines[] = (string)((int)($votes[$opt] ?? $votes[$i] ?? 0));
  }
  file_put_contents($votesTxtFile, implode("\n", $voteLines) . (count($voteLines) ? "\n" : ""), LOCK_EX);
}

[$poll, $votes] = almostheaven_poll_read($pollJsonFile, $votesJsonFile, $pollTxtFile, $votesTxtFile);
$saved = (isset($_GET['saved']) && $_GET['saved'] == '1');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to edit the poll.</p>");

  $question = trim($_POST['question'] ?? '');
  $optionsRaw = trim($_POST['options'] ?? '');
  $options = array_values(array_filter(array_map('trim', preg_split("/\R+/", $optionsRaw))));
  $poll = [
    'question' => $question,
    'options' => $options,
    'show_on_home' => (isset($_POST['show_on_home']) ? 1 : 0),
  ];

  if (!empty($_POST['reset_votes'])) {
    $votes = [];
  }

  almostheaven_poll_write($poll, $votes, $pollJsonFile, $votesJsonFile, $pollTxtFile, $votesTxtFile);
  smurf_redirect_self(['saved'=>1]);
}
$optionsText = implode("\n", $poll['options'] ?? []);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📊 Poll</h1>
  <p style="opacity:.8;">Poll data: <code>/data/poll.json</code> and <code>/data/poll.txt</code> • Votes: <code>/data/poll_votes.json</code> and <code>/data/poll_votes.txt</code></p>

  <?php if (!empty($saved)): ?>
    <div class="msg success">Saved.</div>
  <?php endif; ?>

  <form method="POST" class="form" style="text-align:left;">
    <label>Question</label>
    <input class="input-field" name="question" value="<?= smurf_h($poll['question'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

    <label>Options (one per line)</label>
    <textarea class="input-field" name="options" rows="8" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($optionsText) ?></textarea>

    <?php if ($CAN_EDIT): ?>
      <label style="display:flex;align-items:center;gap:8px;margin-top:10px;">
        <input type="checkbox" name="show_on_home" value="1" <?= !empty($poll['show_on_home']) ? 'checked' : '' ?>>
        Show poll on Home Page
      </label>

      <label style="display:flex;align-items:center;gap:8px;margin-top:10px;">
        <input type="checkbox" name="reset_votes" value="1">
        Reset votes
      </label>

      <button class="admin-btn primary" type="submit" style="margin-top:12px;">Save Poll</button>
    <?php else: ?>
      <p style="opacity:.7;margin-top:10px;">View-only mode — editing disabled.</p>
    <?php endif; ?>
  </form>

  <div class="smurf-divider"></div>

  <h3 style="margin:0 0 10px;">Current vote totals</h3>
  <?php if (empty($poll['options'])): ?>
    <p>No options set yet.</p>
  <?php else: ?>
    <div class="content-card" style="text-align:left;">
      <?php foreach (($poll['options'] ?? []) as $opt): 
        $count = (int)($votes[$opt] ?? 0);
      ?>
        <p style="margin:6px 0;"><strong><?= smurf_h($opt) ?>:</strong> <?= $count ?></p>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
