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

$lst = Listopia::getInstance();

$result = array();

if ($lst->isLoggedIn())
{
  $imageContent = $_POST['imgdata'];
  $targetID = $_POST['id'];
  $authKey = $_POST['auth'];
  
  // hack for spadger-protection
  if ($targetID == 1394 &&
      Session::getInstance()->gl_userid == 258)
  {
    $result['success'] = true;
    $result['result'] = "Sent";
  }

  // check our inputs
  else if (!isset($imageContent))
  {
    $result['result'] = "No image message data sent";
  }
  else if (!isset($targetID) || !$lst->userIDIsValid($targetID))
  {
    $result['result'] = "Missing or invalid target user ID " . $targetID;
  }
  else if (!isset($authKey) || $authKey != ("".$_COOKIE[__LAUTH_KEY__]))
  {
    $result['result'] = "Incorrect auth key";
  }
  // we're okay to plug this in
  else
  {
    $date = date("Y-m-d H:i:s", time());
    
    $data = array(
      'mess_from'         => array(((int)Session::getInstance()->gl_userid)),
      'mess_to'           => array(((int)$targetID)),
      'mess_from_status'  => 'read',
      'mess_to_status'    => 'unread',
      'mess_sent'         => $date,
      'mess_read'         => $date,
      'mess_content'      => $imageContent
    );
    $insertResult = $lst->Database()->insert('messages', $data);
    
    if (isset($insertResult))
      $result['success'] = true;
      
    $result['result'] = $insertResult;
  }
}
else
{
  $result['result'] = "Not logged in";
}

echo json_encode($result);

require("common_end.php");

