<?php include('../header.php'); ?>
<?php include('../menu.php'); ?>
<link rel="stylesheet" href="../css/style.css">

<main class="main-container">
  <section class="schedule-preview">
    <h2>Manage Poll</h2>

    <?php
    $poll_file = '../poll/poll.json';
    $answers_file = '../poll/poll_answers.json';

    // Load poll and answers
    $poll = file_exists($poll_file) ? json_decode(file_get_contents($poll_file), true) : [];
    $answers = file_exists($answers_file) ? json_decode(file_get_contents($answers_file), true) : [];

    // Handle form actions
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      $action = $_POST['action'];

      if ($action === 'create' || $action === 'update') {
        $question = trim($_POST['question']);
        $options = array_filter(array_map('trim', $_POST['options']));

        if ($question && count($options) >= 2) {
          $poll = ['question' => $question, 'options' => $options];
          file_put_contents($poll_file, json_encode($poll, JSON_PRETTY_PRINT));
          file_put_contents($answers_file, json_encode([], JSON_PRETTY_PRINT)); // reset answers
          header('Location: manage_poll.php');
          exit;
        } else {
          echo "<div class='dj-slot now'>Please enter a question and at least two options.</div>";
        }
      }

      if ($action === 'delete') {
        if (file_exists($poll_file)) unlink($poll_file);
        if (file_exists($answers_file)) unlink($answers_file);
        $poll = [];
        $answers = [];
        header('Location: manage_poll.php');
        exit;
      }
    }
    ?>

    <?php if (!empty($poll)): ?>
      <div class="dj-slot now">
        <h4 class="text-warning">Current Poll</h4>
        <p><strong>Question:</strong> <?= htmlspecialchars($poll['question']) ?></p>
        <ul>
          <?php foreach ($poll['options'] as $opt): ?>
            <li><?= htmlspecialchars($opt) ?></li>
          <?php endforeach; ?>
        </ul>
        <form method="post" class="mt-2">
          <input type="hidden" name="action" value="delete">
          <button type="submit" class="btn btn-danger btn-sm">Delete Poll</button>
        </form>
      </div>

      <?php
      // Count votes per option
      $vote_counts = [];
      foreach ($poll['options'] as $opt) {
        $vote_counts[$opt] = 0;
      }
      foreach ($answers as $entry) {
        $opt = $entry['option'];
        if (isset($vote_counts[$opt])) {
          $vote_counts[$opt]++;
        }
      }
      ?>
      <div class="dj-slot coming">
        <h4 class="text-warning">Poll Results</h4>
        <ul>
          <?php foreach ($vote_counts as $opt => $count): ?>
            <li><?= htmlspecialchars($opt) ?> — <?= $count ?> vote<?= $count !== 1 ? 's' : '' ?></li>
          <?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

    <div class="dj-slot next">
      <h4 class="text-warning"><?= empty($poll) ? 'Create New Poll' : 'Edit Poll' ?></h4>
      <form method="post" id="pollForm">
        <input type="hidden" name="action" value="<?= empty($poll) ? 'create' : 'update' ?>">

        <div class="mb-3">
          <label class="form-label text-light">Poll Question</label>
          <textarea name="question" class="form-control mb-3" rows="2" placeholder="Enter your poll question..." required><?= htmlspecialchars($poll['question'] ?? '') ?></textarea>
        </div>

        <label class="form-label text-light">Poll Options</label>
        <div id="optionsContainer">
          <?php
            $existing = !empty($poll['options']) ? $poll['options'] : ['', ''];
            foreach ($existing as $opt) {
              echo "<textarea name='options[]' class='form-control mb-2' rows='1' placeholder='Option'>" . htmlspecialchars($opt) . "</textarea>";
            }
          ?>
        </div>

        <button type="button" class="btn btn-secondary btn-sm mb-3" onclick="addOption()">+ Add Option</button><br>
        <button type="submit" class="btn btn-dark">Save Poll</button>
      </form>
    </div>
  </section>
</main>

<script>
  function addOption() {
    const container = document.getElementById('optionsContainer');
    const textarea = document.createElement('textarea');
    textarea.name = 'options[]';
    textarea.className = 'form-control mb-2';
    textarea.rows = 1;
    textarea.placeholder = 'New option';
    container.appendChild(textarea);
  }
</script>

<?php include('../footer.php'); ?>
