<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

require("common_begin.php");

$lst = Listopia::getInstance();

$incoming = $lst->Database()->query("select * from ai_input");  


$query = $lst->Database()->select(array(
    'fields' => 'ai.*',
    'table' => 'ai',
    'order' => 'ai.ai_ts desc',
    'limit' => 1
    ));  

$newTime = new DateTime('now');
if (empty($query[0]))
{
    echo "no previous<br>";
}
else
{
    $newTime = new DateTime($query[0]['ai']['ai_ts']);
    echo "previous " . $newTime->format('Y-m-d H:i:s') . "<br>";
}


echo "<pre>";

$nowTime = new DateTime('now');

echo "NOW : " . $nowTime->format('Y-m-d H:i:s') . "<br>";
echo "NEW : " . $newTime->format('Y-m-d H:i:s') . "<br>";

if ( $newTime < $nowTime )
{
    $newTime = $nowTime;
}

foreach ($incoming as &$entry)
{
    $newEntry = $entry["ai_input"]["incoming"];

    $timeOffset = "+" . rand(20, 3 * 60) . " seconds";
    $newTime->modify($timeOffset);

    $date = $newTime->format('Y-m-d H:i:s');

    echo "=== : " . $date . "<br>";
    echo "</pre>";
    
    $data = array(
      'ai_think'          => $newEntry,
      'ai_ts'             => $date
    );
    $insertResult = $lst->Database()->insert('ai', $data);
    
    echo $insertResult . "<br>";
}

require("common_end.php");
?>