<?php
$pollFile = 'data/poll.json';
$polls = file_exists($pollFile) ? json_decode(file_get_contents($pollFile), true) : [];
?>

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

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

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

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