<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 4/26/2015
 * Time: 3:55 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');

$params                         =   getParams();
$output                         =   array('status' => 1);

if(!isReady($params, array('pid'))){
    dj($output);
}

$pid                            =   intval($params['pid']);
$ai                             =   intval($params['ai']);
$sid                            =   isset($_SESSION['loggedin']) ? $_SESSION['uid'] : secure($_SERVER['REMOTE_ADDR']);

$pollQuery                      =   $db->prepare("SELECT * FROM polls WHERE id = :id");
$pollQuery->execute(array(
    ":id"                       =>  $pid
));

if($pollQuery->rowCount() === 0){
    dj($output);
}

$pollsRow                       =   $pollQuery->fetch(PDO::FETCH_ASSOC);
$pollsRow['answers']            =   json_decode($pollsRow['answers']);

foreach($pollsRow['answers'] as $ak => $av){
    if($ak === $ai){
        $pollsRow['answers'][$ak]->total_votes++;
    }
}

$answers                        =   json_encode($pollsRow['answers']);
$updatePollQuery                =   $db->prepare("UPDATE polls SET answers = :a, total_votes = total_votes + 1 WHERE id = :id");
$updatePollQuery->execute(array(
    ":a"                        =>  $answers,
    ":id"                       =>  $pid
));
$insertVoteQuery                =   $db->prepare("INSERT INTO poll_votes(pid,answer_index,sid)
                                                  VALUES( :pid, :ai, :sid )");
$insertVoteQuery->execute(array(
    ":pid"                      =>  $pid,
    ":ai"                       =>  $ai,
    ":sid"                      =>  $sid
));

$output['status']               =   2;
dj($output);