<?php

	function runCurl($url, $params = null){
		$session = curl_init();
	
		curl_setopt($session, CURLOPT_HEADER, false);
		curl_setopt($session, CURLOPT_POST, true);
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($session, CURLOPT_URL, $url);
		if($params != null) {
			curl_setopt($session, CURLOPT_POSTFIELDS, $params);
		}
		$response = curl_exec($session);
		curl_close($session);		
		return $response;
	}
	

	$outgoing_keyword = 'UPCOMING';
	$keyphrase = 'YOUR KEY PHRASE';
	
	/* incoming parameters */
	$keyword = $_GET['keyword'];
	$carrier = $_GET['network'];
	$handset = $_GET['smsfrom'];
	$smsmsg = $_GET['smsmsg'];

	/* upcoming api */
	$key = 'YOUR-API-KEY';
	$url = 'http://upcoming.yahooapis.com/services/rest/?api_key='. $key .'&';
	$dlApiEndpoint = "http://www.gumband.com/send/send.php";

	$city = urlencode(trim(substr($smsmsg, strlen($outgoing_keyword))));	

	if ($city == '') {
		/* no city was sent in */
		$msg = "Text in:\nUPCOMING CITY NAME\n to see what's going on.";
		
	} else {
		/* get the metro id for the city */	
		$c = runCurl($url . '&method=metro.search&search_text=' . $city);
		$xml = simplexml_load_string($c);
		$metroId = $xml->xpath('/rsp/metro/@id');	

		$d = date('Y-m-d');
		$c = runCurl($url . '&method=event.search&metro_id='. $metroId[0] .'&min_date='. $d .'&max_date='. $d .'&sort=start-date-desc');
	
		$xml = simplexml_load_string($c);
		$events = $xml->xpath('/rsp/event');
	
		if ($metroId == '' || sizeof($events) == 0) {
			/* either there's nothing going on, or we couldn't figure out where this city is*/
			$msg = "We couldn't find anything going on in " . $city . " today.  Sorry.";
		} else {	
	
			/* we found some events, pick a random one and create the message */
			$which = rand(0, sizeof($events)-1);
	
			$name = $events[$which]->xpath('@name');
			$start_date = $events[$which]->xpath('@start_date');
			$start_time = $events[$which]->xpath('@start_time');
			$venue_name = $events[$which]->xpath('@venue_name'); 
			$venue_address = $events[$which]->xpath('@venue_address'); 
			$description = $events[$which]->xpath('@description'); 
	
	
			$msg = '' ;
			$msg .=  $name[0] . "\n";
			$msg .= date('M d, Y g:i:sa', strtotime($start_date[0] . " " . $start_time[0])) . "\n";
			$msg .= $venue_name[0] . "(". $venue_address[0] .")\n";
	
			if (strlen($msg) < 150) {
				$msg .=  substr($description[0], 0, 160-strlen($msg));
			}
		}
	}
	
	$checksum = md5($outgoing_keyword . $msg . $keyphrase);

	$curlResp = runCurl($dlApiEndpoint, array(
		'keyword' => $outgoing_keyword,
		'message' => $msg,
		'carrier' => $carrier,
		'handset' => $handset,
		'checksum' => $checksum
	));

	
	
		
?>