<?php

require_once('include/admin.inc.php');

//	First, the quick hack way. May become neccessary to parallelize later.

$tweets = $dbConnection->fetchAll('SELECT username, password, text, status, tp.id AS id FROM twitter_post tp JOIN twitter_user tu ON tp.user = tu.id ' .
	'WHERE tp.status = \'scheduled\' AND time >= NOW() AND time < TIMESTAMPADD(?, NOW())', array(RUN_INTERVAL));

//	Check if we actually have any tweets. If not, bail.
if(count($tweets) === 0)
{
	exit(0);
}

//	There are tweets to post. Let's get to work.

foreach($tweets as $t)
{
	//	Lock the tweet
	$dbConnection->executeUpdate('UPDATE twitter_post SET status = \'locked\' WHERE id = ? AND status = \'scheduled\'', array($t->id));

	if(twitterpost($t->text, $t->username, $t->password))
	{
		//	It worked!
		adminlog("Scheduled tweet posted for user ".$t->username, MTS_TWITTER, MTA_ADD);
		$t->status = 'success';
	}
	else
	{
		//	Well, shit. Something went wrong. Log it.
		adminlog("Error $ret_code posting scheduled tweet ".$t->id . ' with return value ' . $ret, MTS_TWITTER, MTA_ADD);
		$t->status = 'error';
	}

	//	Unlock tweet, update db.
	$dbConnection->executeUpdate('UPDATE twitter_post SET status = ? WHERE status = \'locked\' AND id = ?', array($t->status, $t->id));
}

?>
