<?php
require_once __DIR__ . '/../includes/redirect_helper.php';
$poll_file = '../data/poll.json';
$votes_file = '../data/poll_votes.json';

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

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

  if (in_array($selected, (array)$poll['options'], true)) {
    $votes = file_exists($votes_file) ? json_decode(file_get_contents($votes_file), true) : [];
    if (!is_array($votes)) $votes = [];
    $votes[$selected] = (int)($votes[$selected] ?? 0) + 1;
    file_put_contents($votes_file, json_encode($votes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  }
}

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