<?php

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

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

$tweets = $mtdb->getAll("SELECT username, password, text, status, twitter_post.id AS id
	FROM twitter_post JOIN twitter_user
		ON twitter_post.user = twitter_user.id
	WHERE twitter_post.status = 'scheduled'
		AND time >= NOW()
		AND time < TIMESTAMPADD(" . RUN_INTERVAL . ", NOW())
");

//	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
	$mtdb->query("UPDATE twitter_post SET status = 'locked' WHERE id = ".(int)$t->id." AND status = 'scheduled'", false);

	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.
	$mtdb->query("UPDATE twitter_post SET status = '".mysqli_real_escape_string($mtdb->link, $t->status)."' WHERE status = 'locked' AND id = ".(int)$t->id, false);
}

?>
