<?php
require_once __DIR__ . '/../includes/redirect_helper.php';
$poll_file = '../poll/poll.json';
$answers_file = '../poll/poll_answers.json';

$poll = file_exists($poll_file) ? json_decode(file_get_contents($poll_file), true) : null;

if ($poll && isset($_POST['option'])) {
  $selected = $_POST['option'];

  // Validate option
  if (in_array($selected, $poll['options'])) {
    $answers = file_exists($answers_file) ? json_decode(file_get_contents($answers_file), true) : [];
    $answers[] = [
      'option' => $selected,
      'timestamp' => date('Y-m-d H:i:s')
    ];
    file_put_contents($answers_file, json_encode($answers, JSON_PRETTY_PRINT));
  }
}

ah_redirect_back('/index.php', ['voted' => 1]);
