<?php 
require("common_begin.php");

$lst = Listopia::getInstance();

if ($lst->isLoggedIn())
{
  $result = array();

  $sesh = Session::getInstance();
  
  $currentUserID = $sesh->gl_userid;
  
  if ($lst->isUserOnProbation())
  {
    die("{ }");
  }
  
  
  $voteUp = ($_POST['voteUp'] === "true");
  $itemID = $_POST['item'];
  
  if (gettype($voteUp) !== "boolean")
    die("vote type unrecognised");
  if (!isset($itemID) || !is_numeric($itemID))
    die("no item ID specified");
    
  $voteDBValue = $voteUp ? 'like' : 'hate';
  
  // get the creator userID for this item - we use it later on but we also double-check people
  // aren't trying to vote for their own items
  $itemCreatorID = -1;
  $query = $lst->Database()->select(array(
                      'fields' => 't_items.item_createdby',
                      'table' => 't_items',
                      'condition' => 't_items.item_id = ' . ((int)$itemID),
                      'limit' => 1
                      ));
  $query = $query[0];
  if (!empty($query))
  {
    $itemCreatorID = $query['t_items']['item_createdby'];
    if ($itemCreatorID == $currentUserID)
      die("stop voting for your own shit");
  }
  else
    die("this item doesn't exist!");
  
  
  // go check for an existing vote 
  $itemLikesQueryCondition = 'itemlikes.item_id = ' . ((int)$itemID) . ' and itemlikes.user_id = ' . ((int)$currentUserID);  
  $query = $lst->Database()->select(array(
                      'fields' => '*',
                      'table' => 'itemlikes',
                      'condition' => $itemLikesQueryCondition,
                      'limit' => 1
                      ));
                      
  // we have already cast a vote on this item
  $query = $query[0];
  if (!empty($query))
  {
    FB::log("current vote : " . $query['itemlikes']['vote']);
    FB::log("new vote : " . $voteDBValue);
        
    $alreadyVotedThisWay = ($voteUp && $query['itemlikes']['vote'] === "like") ||
                           (!$voteUp && $query['itemlikes']['vote'] === "hate");
                           
    // we have already cast an identical vote; discard. possible feature would be to undo this vote entirely
    if ($alreadyVotedThisWay)
    {
      FB::log("already voted on this item " . $itemID);
      $result['problem'] = "Duplicate Vote";
    }
    // otherwise we need to recast this. 
    else
    {
      // first up, rewrite the entry in 'itemlikes'
      $data = array(
        'vote' => $voteDBValue
      );
      $okA = $lst->Database()->update('itemlikes', $data, $itemLikesQueryCondition);
      
      // next modify the counters in the list item itself
      $data = array(
        'item_votesup'    => $voteUp ? array('item_votesup + 1')    : array('item_votesup - 1'),
        'item_votesdown'  => $voteUp ? array('item_votesdown - 1')  : array('item_votesdown + 1')
      );
      $okB = $lst->Database()->update('t_items', $data, 't_items.item_id = ' . ((int)$itemID));
      
      if ($okA !== false && $okB !== false)
      {
        FB::log("changing vote on " . $itemID);
      }
    }
  }
  // we've never voted on this before
  else
  {
    // create new entry in itemlikes
    $data = array(
      'user_id'       => array(Session::getInstance()->gl_userid),
      'item_id'       => array(((int)$itemID)),
      'createdby'     => array(((int)$itemCreatorID)),
      'vote'          => $voteDBValue
    );
    $okA = $lst->Database()->insert('itemlikes', $data);
    
    // and increment the appropriate counter in the items list
    $itemDBEntry = $voteUp ? 'item_votesup' : 'item_votesdown';
    $data = array(
      $itemDBEntry    => array($itemDBEntry . ' + 1')
    );    
    $okB = $lst->Database()->update('t_items', $data, 't_items.item_id = ' . ((int)$itemID));

    if ($okA !== false && $okB !== false)
    {
      FB::log("adding vote to " . $itemID);
    }
  }
  
  // we return the state of both like/hate counters, incase we swapped our vote
  $query = $lst->Database()->select(array(
                      'fields' => 't_items.item_votesup, t_items.item_votesdown',
                      'table' => 't_items',
                      'condition' => 't_items.item_id = ' . ((int)$itemID),
                      'limit' => 1
                      ));
  if (!empty($query[0]))
  {
    $result['up'] = sprintf("%02d", intval( $query[0]['t_items']['item_votesup'] ));
    $result['down'] = sprintf("%02d", intval( $query[0]['t_items']['item_votesdown'] ));
  }
}

echo json_encode($result);

require("common_end.php");

