<?php
/* 
	What is LEO poll? 
	This is a poll conducted in our college for the posts Mr.Popular, Mr. Handsome etc etc.
	So a message to vote for option 1 as Mr.Popular will be like "LEO P 1"
	This code tries to handle most of boundary cases. To vote for Mr.Popular you can also send
	leo p 1 
	LeO p 1
	leo            p              1
		     leo p     1
	As you can see, empty space and case doesn't matter :)

	Apart from the inbox and outbox table, this has two more tables in the same database.
	The table structure is given below

	1. users

	phone 		varchar(50)

	2. votes 
	phone		varchar(20)
	category	varchar(20)
	choice		varchar(20)	
*/
//Leo parameters
$categories = array ("P", "H", "CA", "C", "FC", "S", "T", "FT", "F", "FF", "FB", "FC", "FP");

$choices = array ("1", "2", "3", "4", "5");

//Mysql connection

mysql_connect ("dbserver", "dbuser", "dbpassword") or die(mysql_error());

mysql_select_db("dbname") or die(mysql_error());

//Important functions here 

function filter($text) {
	return mysql_escape_string($text);

}	

function setMessageProcessed($id) {
	mysql_query ("UPDATE `inbox` SET `processed` = '1' WHERE `id` = '".filter($id)."'");  //Set processed as 1

	if (mysql_error()) return false; 
	return true;

}

function canVote($number) {
	if (strlen($number>10)) $number = substr($number, -10);

	$flag = mysql_num_rows (mysql_query("SELECT * FROM `users` WHERE `phone` LIKE '%".$number."%'"));

	return (boolean)$flag;
}

function addVote($number, $category, $choice) {

	mysql_query ("INSERT INTO `votes` (`phone` ,`category` ,`choice`)VALUES ('".filter($number)."', '".filter($category)."', '".filter($choice)."');");

}

function sendmessage($number, $text) {

	$text .= "\nPowered by Spider.";
	echo $number." --> ". $text."\n";

	mysql_query("INSERT INTO `outbox`  (`id` ,`number` ,`processed_date` ,`insertdate` ,`text` ,`phone` ,`processed` ,`error` ,`dreport`) VALUES (NULL , '".filter($number)."', NOW( ) , '0000-00-00 00:00:00', '".filter($text)."', NULL , '0', '-1', '0');");

}

while (1) {
	sleep(1);

	echo mysql_error();
	$details = mysql_fetch_array(mysql_query ("SELECT * FROM `inbox` WHERE `processed` = 0 ORDER BY `id` LIMIT 0, 1"));

	if ($details == false) { continue; }

	setMessageProcessed($details['id']);
	$reply = "";

	$number = $details['number'];
	if (canVote($number) == false) {

		$reply = "You cannot vote in this poll. Please contact admins to enable your number.";
		sendmessage($number, $reply);

		continue;
	}
	// Control comes here when he/she can vote :)
	$message = trim(strtoupper($details['text']));

	//The following loop to remove multiple spaces in the message.
	for ($i=0; $i<100; $i++) { $message = str_replace("  ", " ", $message); }

	
	$message_tok = explode (" ", $message);

	if ($message_tok[0] != "LEO") {

		$reply = "Invalid format. Send message as \"LEO CATEGORY CHOICE\" (quotes for clarity).";
		sendmessage($number, $reply);

		continue;
	}
	// Control comes here when the first key word is LEO
	$flag = false;

	for ($i= 0; $i<count($categories); $i++) {

		if ($categories[$i] == $message_tok[1]) { $flag = true; break; }

	}
	if ($flag == false) {

		$reply = "Invalid category. Category has to be one from \"P\", \"H\", \"CA\", \"C\", \"FC\", \"S\", \"T\", \"FT\", \"F\", \"FF\", \"FB\", \"FC\", \"FP\".";

		sendmessage($number, $reply);
		continue;
	}

	//Control comes here when the category is proper
	$flag = false;
	for ($i= 0; $i<count($choices); $i++) {

		if ($choices[$i] == $message_tok[2]) { $flag = true; break; }

	}
	if ($flag == false) {

		$reply = "Invalid choice. Choice has to be one from \"1\", \"2\", \"3\", \"4\", \"5\".";

		sendmessage($number, $reply);
		continue;
	}

	//Control comes here when the choice is proper
	$flag = mysql_num_rows(mysql_query("SELECT * FROM `votes` WHERE phone = '".$number."' AND `category` = '".$message_tok[1]."'"));

	if ($flag) {
		$reply = "You have already voted for this category. This vote is not counted.";

		sendmessage($number, $reply);
		continue;
	}

	//Control comes here when he/she has not yet voted for this category
	addVote($number, $message_tok[1], $message_tok[2]);  //AddVote

	$reply = "You have chosen option ".$message_tok[2]." for choice ".$message_tok[1].". Thank you for voting. :-)";

	sendmessage($number, $reply);
}
?>