<?php
require_once __DIR__ . '/../includes/redirect_helper.php';

$pollFile = __DIR__ . '/../data/poll.json';
$votesJsonFile = __DIR__ . '/../data/poll_votes.json';
$votesTxtFile = __DIR__ . '/../data/poll_votes.txt';

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

if ($poll && isset($_POST['option'])) {
  $selected = trim((string)$_POST['option']);
  $options = array_values(array_map('strval', (array)($poll['options'] ?? [])));
  if (in_array($selected, $options, true)) {
    $votes = file_exists($votesJsonFile) ? json_decode((string)file_get_contents($votesJsonFile), true) : [];
    if (!is_array($votes)) $votes = [];
    $votes[$selected] = (int)($votes[$selected] ?? 0) + 1;
    file_put_contents($votesJsonFile, json_encode($votes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "
", LOCK_EX);
    $lines = [];
    foreach ($options as $opt) {
      $lines[] = (string)((int)($votes[$opt] ?? 0));
    }
    file_put_contents($votesTxtFile, implode("
", $lines) . (count($lines) ? "
" : ''), LOCK_EX);
  }
}

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