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

$lst = Listopia::getInstance();

$result = array();

if ($lst->isLoggedIn())
{
  $messageContent = base64_decode($_POST['msg']);
  $listItemID = isset($_POST['id']) ? intval($_POST['id']) : -1;
  $listID  = isset($_POST['list']) ? intval($_POST['list']) : 0;
  $authKey = $_POST['auth'];

  if ($lst->isUserOnProbation())
  {
      $result['result'] = "You're on probation, can't add anything";
  }
  
  // check our inputs
  else if (!isset($messageContent) || $messageContent === FALSE)
  {
    $result['result'] = "No message data sent";
  }
  else if ($listID == 0 && !$lst->listItemIDIsValid($listItemID))
  {
    $result['result'] = "Missing or invalid list item ID " . $listItemID;
  }
  else if ($listItemID == -1 && !$lst->listIDIsValid($listID))
  {
    $result['result'] = "Missing or invalid list ID " . $listID;
  }  
  else if (!isset($authKey) || $authKey != $_COOKIE[__LAUTH_KEY__])
  {
    $result['result'] = "Incorrect auth key";
  }
  else if (strlen($messageContent) > 500)
  {
    $result['result'] = "Message is too big";
  }
  else if (strlen($messageContent) < 2)
  {
    $result['result'] = "Message is too small";
  }  
  // we're okay to plug this in
  else
  {
    $conditionedMessage = htmlspecialchars($messageContent);
    
    $date = date("Y-m-d H:i:s");

    $data = array(
      'disc_user'         => array(Session::getInstance()->gl_userid),
      'disc_username'     => Session::getInstance()->gl_username,
      'disc_list'         => $listID,
      'disc_comment'      => $conditionedMessage,
      'disc_item'         => $listItemID,
      'disc_datetime'     => $date
    );
    $insertResult = $lst->Database()->insert('t_discussion', $data);
    
    if (isset($insertResult))
    {
      $result['success'] = true;
      $lst->pushPublish("New Comment"); 
    }
      
    $result['result'] = $insertResult;
  }
}
else
{
  $result['result'] = "Not logged in";
}

echo json_encode($result);

require("common_end.php");

