<?php
			


/**
 * Webhook for Time Bot- Facebook Messenger Bot
 * User: adnan
 * Date: 24/04/16
 * Time: 3:26 PM
 */
 
$input = json_decode(file_get_contents('php://input'), true);
error_log(print_r($input,true));


//$access_token = "EAAEgAPJlAvMBADlwIrYbQ5ZAvZAYDZBtBfyxabwuK628ZAPtClpkLZCwLCCsb4ojVu9a3ttKFTZAJnqgwQZBktC1YlSsBDZC2rT4VEw0zj0eAvX42PHASGKHcdK32Jgt3BgZAHSytZBDe2sUKqCM22RiucQN2oP5tbXIg83vd8PMlGxQZDZD";
$access_token = "EAAEgAPJlAvMBAEA8UTAGZAw0V0lMweZCKQfTIEZAXhaZCXSqdqHMRu34eIzJ2XinWUzC0nitIVpaZCjzzpLc0uyZCMBouvW6sO6vVZBVg7F5enB4lrDilAY2aoEAMdAARLQYBpZAIYK2PsivPltrkpwE4GB9E1KgkdgTUWveojbZB2gZDZD";
$access_token = "EAAEgAPJlAvMBAEA8UTAGZAw0V0lMweZCKQfTIEZAXhaZCXSqdqHMRu34eIzJ2XinWUzC0nitIVpaZCjzzpLc0uyZCMBouvW6sO6vVZBVg7F5enB4lrDilAY2aoEAMdAARLQYBpZAIYK2PsivPltrkpwE4GB9E1KgkdgTUWveojbZB2gZDZD";
$verify_token = "abc123";
$hub_verify_token = null;

if(isset($_REQUEST['hub_challenge'])) {
    $challenge = $_REQUEST['hub_challenge'];
    $hub_verify_token = $_REQUEST['hub_verify_token'];
}


if ($hub_verify_token === $verify_token) {
    echo $challenge;
}


$input = json_decode(file_get_contents('php://input'), true);
error_log(print_r($input,true));



$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];


$message_to_reply = '';

/**
 * Some Basic rules to validate incoming messages
 */
if(preg_match('[time|current time|now]', strtolower($message))) {

    // Make request to Time API
    ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)');
    $result = file_get_contents("http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S%20%25Y");
	    if($result != '') {
	        $message_to_reply = $result;
	    }
    }

else if(preg_match('[search|name]', strtolower($message))) {
	$conn = db_connect1();
	$rturn = search_by_name($conn,strtolower($message));
	$message_to_reply = 'Searching by name ... ' . $rturn ;
	$conn->close();
	
} 
else if(preg_match('[details|full]', strtolower($message))) {
	$conn = db_connect1();
	$rturn = search_by_id($conn,strtolower($message));
	$message_to_reply = 'Searching Full Details... ' . $rturn ;
	$conn->close();
	
} 
else if(preg_match('[phone|number]', strtolower($message))) {
	$conn = db_connect1();
	$rturn = search_by_phone($conn,strtolower($message));
	$message_to_reply = 'Searching By Phone... ' . $rturn ;
	$conn->close();
	
} 

else if(preg_match('[email|mail]', strtolower($message))) {
	$conn = db_connect1();
	$rturn = search_by_email($conn,strtolower($message));
	$message_to_reply = 'Searching By Email... ' . $rturn ;
	$conn->close();
	
} 
 
else if(preg_match('[help]', strtolower($message))) {
	$message_to_reply = 'search <name> \n\rname <name> \n\rphone <phone> \n\remail <email> \n\r' ;
	
} 


else {
    $message_to_reply = 'Type help for commands. Robot made by Paolo';
}

//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;

/// sending message

$parts = str_split($message_to_reply, $split_length = 300);

$pagemax = 0;
foreach ($parts as $message_to_reply) {
	
	
if ($pagemax >= 3) {
	$message_to_reply = "Max Search Exceed. Please Narrow down your search to specific.";
}
//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = '{
    "recipient":{
        "id":"'.$sender.'"
    },
    "message":{
        "text":"'.$message_to_reply.'"
    }
}';




//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
error_log(print_r($url,true));
error_log(print_r($jsonDataEncoded,true));
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
    $result = curl_exec($ch);
}
var_dump($result);
if ($pagemax >= 5) { exit(); }
 //sleep ( 1 );
 $pagemax++;

}