<?php
$pollFile = __DIR__ . '/data/poll.json';
$votesFile = __DIR__ . '/data/poll_votes.json';
$poll = file_exists($pollFile) ? json_decode(file_get_contents($pollFile), true) : [];
$votes = file_exists($votesFile) ? json_decode(file_get_contents($votesFile), true) : [];
if (!is_array($poll)) { $poll = []; }
if (!is_array($votes)) { $votes = []; }
$options = array_values(array_filter(array_map('trim', (array)($poll['options'] ?? [])), fn($v) => $v !== ''));
$showPoll = !empty($poll['show_on_home']) && !empty(trim((string)($poll['question'] ?? ''))) && !empty($options);
?>

<?php include 'includes/header.php'; ?>

<div class="container content-box mt-5">
  <h2>📊 Poll Results</h2>

  <?php if (!$showPoll): ?>
    <p>No active poll.</p>
  <?php else: ?>
    <div class="htr-box mb-5">
      <h4><?= htmlspecialchars((string)$poll['question'], ENT_QUOTES, 'UTF-8') ?></h4>
      <?php $totalVotes = 0; foreach ($options as $option) { $totalVotes += (int)($votes[$option] ?? 0); } ?>
      <ul class="list-group">
        <?php foreach ($options as $option): 
          $count = (int)($votes[$option] ?? 0);
          $percent = $totalVotes > 0 ? round(($count / $totalVotes) * 100) : 0;
        ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <?= htmlspecialchars($option, ENT_QUOTES, 'UTF-8') ?>
            <span class="badge bg-dark rounded-pill"><?= $count ?> vote<?= $count !== 1 ? 's' : '' ?> (<?= $percent ?>%)</span>
          </li>
        <?php endforeach; ?>
      </ul>
      <small class="text-muted">Total votes: <?= $totalVotes ?></small>
    </div>
  <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ?>
