<?php
$pollFile = 'data/poll.json';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['poll_id'], $_POST['option'])) {
  $polls = json_decode(file_get_contents($pollFile), true);
  $pollId = (int)$_POST['poll_id'];
  $optionIndex = (int)$_POST['option'];

  foreach ($polls as &$poll) {
    if ($poll['id'] === $pollId && isset($poll['votes'][$optionIndex])) {
      $poll['votes'][$optionIndex]++;
      break;
    }
  }

  file_put_contents($pollFile, json_encode($polls, JSON_PRETTY_PRINT));
  header('Location: index.php?voted=1');
  exit;
}
?>
