<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/start.php';
require_login();

if (!is_post()) {
    http_response_code(405);
    echo "Method Not Allowed";
    exit;
}

if (!csrf_check(post_str('csrf'))) {
    flash_set('err', t('bad_csrf'));
    redirect('/');
}

$pollId = (int)post_str('poll_id');
$optId  = (int)post_str('option_id');

if ($pollId <= 0 || $optId <= 0) {
    redirect('/');
}

$st = $pdo->prepare("SELECT id FROM post_poll_options WHERE id=? AND poll_id=? LIMIT 1");
$st->execute([$optId, $pollId]);
if (!$st->fetchColumn()) {
    flash_set('err', t('activation_bad'));
    redirect('/');
}

$st = $pdo->prepare("
  INSERT INTO post_poll_votes (poll_id, user_id, option_id, created_at)
  VALUES (?,?,?,NOW())
  ON DUPLICATE KEY UPDATE option_id=VALUES(option_id), created_at=NOW()
");
$st->execute([$pollId, (int)$me['id'], $optId]);

redirect('/');
