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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['option'])) {
    $poll = file_exists($pollFile) ? json_decode(file_get_contents($pollFile), true) : [];
    $votes = file_exists($votesFile) ? json_decode(file_get_contents($votesFile), true) : [];

    if (!is_array($poll)) { $poll = []; }
    if (!is_array($votes)) { $votes = []; }

    $showOnHome = !empty($poll['show_on_home']);
    $question = trim((string)($poll['question'] ?? ''));
    $options = array_values(array_filter(array_map('trim', (array)($poll['options'] ?? [])), fn($v) => $v !== ''));
    $optionIndex = (int)($_POST['option'] ?? -1);

    if ($showOnHome && $question !== '' && isset($options[$optionIndex])) {
        $selected = $options[$optionIndex];
        $votes[$selected] = (int)($votes[$selected] ?? 0) + 1;
        file_put_contents($votesFile, json_encode($votes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }
}

header('Location: index.php?voted=1');
exit;
