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

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

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

if(!isset($_SESSION['loggedin'], $params['pid'])){
    dj($output);
}

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

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

$voteInfoQuery              =   $db->prepare("SELECT COUNT(*) as `voteCount`,`answer_index` FROM poll_votes WHERE pid = :pid AND sid = :sid");
$voteInfoQuery->execute(array(
    ":pid"                  =>  $pid,
    ":sid"                  =>  $sid
));
if($voteInfoQuery->rowCount() > 0){
    $voteInfoRow            =   $voteInfoQuery->fetch(PDO::FETCH_ASSOC);
    $votes                  =   $voteInfoRow['voteCount'];
    $answer_key             =   intval($voteInfoRow['answer_index']);
}

$pollsRow                       =   $pollsQuery->fetch(PDO::FETCH_ASSOC);
$pollsRow['answers']            =   json_decode($pollsRow['answers']);
$output['status']               =   2;
$output['poll']                 =   $pollsRow;
$output['votes']                =   $votes;
$output['answer_key']           =   $answer_key;
dj($output);