<?php 
/*
DROP FUNCTION IF EXISTS flip_ai_fave;

DELIMITER //

CREATE FUNCTION flip_ai_fave(lid INT)
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE select_var INT;
SET select_var = (select ai_faved from ai where ai_id = lid);
update ai set ai_faved = 1 where ai_id = lid;
RETURN select_var;
END
//

DELIMITER ;
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require("common_begin.php");

$lst = Listopia::getInstance();

$result['result'] = "";

$listID = 3258;
$fakeUserID = 1953;

if ($lst->isLoggedIn())
{
    $aiID = $_POST['id'];
    if (!isset($aiID))
        die("no AI ID specified");

    $aiID = (int)$aiID;
    if ($aiID <= 0)
        die("bad AI ID");

    $sesh = Session::getInstance();

    $query = $lst->Database()->raw_query("select flip_ai_fave(".$aiID.")");
    $result['flip_q'] = $query[0];

    if ( (int)$query[0] == 0 )
    {
      $inner_query = $lst->Database()->select(array(
        'fields' => 'ai.ai_think',
        'table' => 'ai',
        'condition' => 'ai.ai_id = '. $aiID
        ));  
    
      if (empty($inner_query[0]))
        die("bad AI message fetch");

      $think = str_replace("\n", "<br>",$inner_query[0]['ai']['ai_think']);

      $date = date("Y-m-d H:i:s", time());
      $data = array(
        'item_list'         => array((int)$listID),
        'item_blurb'        => $think,
        'item_createdby'    => array((int)$fakeUserID),
        'item_extra'        => '',
        'item_created'      => $date
      );
      $insertResult = $lst->Database()->insert('t_items', $data);
      
      if (isset($insertResult))
      {
        // update the list's update time
        $data = array(
          'list_updated'    => $date
        );
        $updateResultA = $lst->Database()->update('t_lists', $data, 't_lists.list_id = ' . ((int)$listID));

        // update the AI fave to the new list entry ID
        $data = array(
          'ai_faved'    => $insertResult
        );
        $updateResultB = $lst->Database()->update('ai', $data, 'ai.ai_id = ' . $aiID);

        $result['insert'] = $insertResult;
        $result['updateA'] = $updateResultA;
        $result['updateB'] = $updateResultB;
      }
    }
    else
    {
        $result['fail'] = "already voted";
    }
}

echo json_encode($result);

require("common_end.php");
