<?php
if (!isset($_SESSION['FirstName'])) {
	session_start();
}
if ($_SESSION['FirstName'] == "") {
	echo 'You are not authorized to view this page. <br><br>You may <a href="index.php"><font color="blue">log in here.</font></a>';
	exit;
	}
	//these codes apply to all taste systems clients
	$clientId = '5412'; // Your Client ID from https://developer.mogreet.com/dashboard
	$token = '9fbd7e0e70fc853dabd24c039f8b3603'; // Your token from https://developer.mogreet.com/dashboard
	$now   = new DateTime();
    $month = (int)$now->format("m");
	$year = (int)$now->format("Y");

	
//$API_KEY="d73b11b52ee85bdea171703c9d4183aa5c16f314";
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!--<link rel="stylesheet" href="includes/tinyaccordion/style.css" type="text/css" />-->

<script type="text/javascript" src="../js/ddaccordion.js">
/***********************************************
* Accordion Content script- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for hundreds of DHTML scripts
* This notice must stay intact for legal use
***********************************************/

</script>
<script type="text/javascript">
ddaccordion.init({
	headerclass: "expandable", //Shared CSS class name of headers group that are expandable
	contentclass: "categoryitems", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["", "openheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["prefix", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})

ddaccordion.init({ //2nd level headers initialization
	headerclass: "subexpandable", //Shared CSS class name of sub headers group that are expandable
	contentclass: "subcategoryitems", //Shared CSS class name of sub contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["opensubheader", "closedsubheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["none", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})
</script>
<style type="text/css">

.arrowlistmenu{
width: 100%; /*width of accordion menu*/
}

.arrowlistmenu .menuheader{ /*CSS class for menu headers in general (expanding or not!)*/
font:12px Verdana,Arial;width:95%; border:1px solid #467182; padding:7px; 
	font-weight:bold; margin-top:5px; cursor:pointer; 
    -webkit-border-radius: 7px;
    -moz-border-radius: 7px;
    border-radius: 7px;
    border: solid 1px #e8e8e8;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    -webkit-transition-duration: 0.2s;
    -moz-transition-duration: 0.2s;
    transition-duration: 0.2s;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
	color:#fff;
	background-color:#2077a1;
	padding-left:.5em;padding-right:.5em;
}

.arrowlistmenu .openheader{ /*CSS class to apply to expandable header when it's expanded*/
background-image: url(titlebar-active.png);
}

.arrowlistmenu ul{ /*CSS for UL of each sub menu*/
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 0px; /*bottom spacing between each UL and rest of content*/
background: none;
}

.arrowlistmenu ul li{
padding-bottom: 0px; /*bottom spacing between menu items*/
}

.arrowlistmenu ul li .opensubheader{ /*Open state CSS for sub menu header*/
background: lightblue !important;
}

.arrowlistmenu ul li .closedsubheader{ /*Closed state CSS for sub menu header*/
background: lightgreen !important;
}

.arrowlistmenu ul li a{
color: #81BEF7;
background: url(arrowbullet.png) no-repeat center left; /*custom bullet list image*/
display: block;
padding: 0px 0;
padding-left: 19px; /*link text is indented 19px*/
text-decoration: none;
font-weight: bold;
border-bottom: 1px solid #dadada;
font-size: 90%;
}

.arrowlistmenu ul li a:visited{
color: #81BEF7;
}

.arrowlistmenu ul li a:hover{ /*hover state CSS*/
color: #FA5858;
background-color: #FA5858;
}

.arrowlistmenu ul li a.subexpandable:hover{ /*hover state CSS for sub menu header*/
background: lightblue;
}
html {
    overflow-y: scroll;
}
</style>




<!--<link rel="stylesheet" type="text/css" href="css/cssverticalmenu.css" />-->
<!--<script type="text/javascript" src="js/jscolor/jscolor.js"></script>-->

<?php
//get sms/mms plan info
$qry="select sms_id, mms_id, sms_plan from admin_options";
	$rt=mysql_query($qry); 
	while($data=mysql_fetch_array($rt)){
		$sms_id = $data[sms_id];
		$mms_id = $data[mms_id];
		$sms_plan = $data[sms_plan];
	}
	
	//get totals for current period
	$qry="select * from sms_message_log where month(timestamp)='$month' AND year(timestamp)='$year'";
	$recipient_counter=0;
	$rt=mysql_query($qry); 
	if(mysql_num_rows($rt)>0){
		$body3.="<table cellpadding=3 cellspacing=2><tr><td><u>Text message</u><td><u>Recipients</u>";
		while($data=mysql_fetch_array($rt)){
			//$recipient_list=array_count_values(array($data[recipient_ids]));
			$recipients = explode (",", $data[recipient_ids]);
			//print_r($recipients);
			$body3.= "<tr><td>".$data[sms_body] . "<td><center>" . count($recipients)."</center>";
			$recipient_counter=$recipient_counter+count($recipients);
		}
		$body3.="</table>";
		
	}
		
$qry = "select count(mobile_number) as subscribers from sms_subscribers";
$return=mysql_query($qry);   
	while($data=mysql_fetch_array($return)){
		$total_subscribers = $data[subscribers];
	}

if((empty($sms_id))||(empty($mms_id))){
	echo "<center><font color='red'>Your texting plan is not configured correctly. </font></center><br>";
}
	
$qry = "select count(mobile_number) as subscribers from sms_subscribers where active='1'";
$return=mysql_query($qry);   
	while($data=mysql_fetch_array($return)){
		echo "<center>You have ".$data[subscribers]." active SMS subscribers.";
		if($total_subscribers>0){echo"(".$total_subscribers." total)";}
		echo"</center><br>";
		if($sms_plan=="300"){
			$plan="Starter 300";
		} elseif ($sms_plan=="750"){
			$plan="Standard 750";
		} elseif ($sms_plan=="1500"){
			$plan="Gold 1500";
		} elseif ($sms_plan=="2500"){
			$plan="Platinum 2500";
		} else{
			$plan="Not selected";
		}
		echo"<center>Your plan: $plan</center><br>";
	}

echo"<center>Total texts sent this month: $recipient_counter <br>
Remaining: ".($sms_plan-$recipient_counter)."</center>";
	
$sms_balance = $sms_plan-$recipient_counter; //store balance variable to keep from recalculating before every text

//echo "current period: ".$month . " " .$year;
	
//save message if selected
if($_POST['save_message']){	
	if($_POST['new_message']>""){
		$qry= "insert into sms_storage (sms_body, image_url) values('".$_POST['new_message']."', '".$_POST['image_url']."')";
		mysql_query($qry);
	}
}
//send if selected
if($_POST['send']){
	$msg = $_POST['message_body'];
	$image_url = $_POST['image_url'];
	
	//insert the message into the send log
	$qry= "insert into sms_message_log (sms_body, image_url) values('$msg', '$image_url')";
	mysql_query($qry);
	//get ID for logged message, to update with recipients as they are sent
	$qry="select max(recordkey) as message_id from sms_message_log";
	$rt=mysql_query($qry); 
	while($data=mysql_fetch_array($rt)){
		$message_id = $data[message_id];
	}
	
	
	//require_once('includes/Mogreet.php');
	if(empty($image_url)){//this is a sms message, no image
		$campaign_id=$sms_id;
	} else {
		$campaign_id=$mms_id;
	}
	
	$recipient_list = "";
	$msg_count=0;
	
	$qry = "select recordkey, mobile_number from sms_subscribers where active='1'";
	$rt=mysql_query($qry); 
	//echo "user qry=<br>$qry<br>";
	while($data=mysql_fetch_array($rt)){
		if($sms_balance>0){
			/*
			$client = new Mogreet($clientId, $token);
			$response = $client->transaction->send(array(
						'campaign_id' => $campaign_id, // Your SMS campaign ID from https://developer.mogreet.com/dashboard
						'to' => $data['mobile_number'],
						'message' => $msg,
						'content_url' => $image_url
			));
			*/
			$url = "\"https://api.mogreet.com/moms/transaction.send?client_id=5412&token=9fbd7e0e70fc853dabd24c039f8b3603&campaign_id=$campaign_id&to=".$data[mobile_number]."&message=$msg&content_url=$image_url&format=json\"";
			echo "<br>url=<br>$url";
			/*

			
			$ch = curl_init();
			// to handle https links
			
			curl_setopt($ch, CURLOPT_URL,$url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
			
		
			$response= curl_exec ($ch);
			curl_close ($ch);
	*/
	// create curl resource 
        $ch = curl_init(); 

        // set url 
        curl_setopt($ch, CURLOPT_URL, $url); 

        //return the transfer as a string 
        //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		//curl_setopt($ch, CURLOPT_URL, Mogreet::BASE_API . '/' . $base . '/' . $api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "mogret-php/1.0");
        // $response contains the output string 
        $response = curl_exec($ch); 

		// Check for errors and display the error message
		if($errno = curl_errno($ch)) {
			//$error_message = curl_strerror($errno);
			echo "<br>cURL error ({$errno}):\n {$error_message}";
		}
        // close curl resource to free up system resources 
        curl_close($ch);  
		echo "result: $response";
			//$response = file_get_contents($url);

			// Will dump a beauty json :3
			//var_dump(json_decode($response, true));
			
			
			
			print $response->messageId;
			print $response->status;
			
			if($response->status =="success"){
				$msg_count++;
				if($recipient_list == ""){
					$recipient_list = $data[recordkey];
				} else {
					$recipient_list .= ", ".$data[recordkey];
				}
				$sms_balance=$sms_balance-1;
			} else {
				print_r($response);
			}
		} else {
			$sec1_notice_msg="<font color='red'>You have reached your monthly send limit.</font>";
			break;
		}
	}	
	//add successful recipients to log for current sms message
	$qry = "update sms_message_log set recipient_ids = '$recipient_list', recipient_count='$msg_count' where recordkey='$message_id'";
	mysql_query($qry);
	$sec1_notice_msg="<font color='red'>Message successfully sent to $msg_count recipients.</font>";
	
	

}

if($_REQUEST['sendstored']){
	$qry="select * from sms_storage where recordkey='".$_REQUEST['sendstored']."'";
	$rt=mysql_query($qry); 
	while($data=mysql_fetch_array($rt)){
		$msg = $data['sms_body'];
		$image_url = $data['image_url'];
	}
	
	
	//insert the message into the send log
	$qry= "insert into sms_message_log (sms_body, image_url) values('$msg', '$image_url')";
	mysql_query($qry);
	//get ID for logged message, to update with recipients as they are sent
	$qry="select max(recordkey) as message_id from sms_message_log";
	$rt=mysql_query($qry); 
	while($data=mysql_fetch_array($rt)){
		$message_id = $data[message_id];
	}
	
	//require ('class-Clockwork.php');
	require_once('includes/Mogreet.php');
	if(empty($image_url)){//this is a sms message, no image
		$campaign_id=$sms_id;
	} else {
		$campaign_id=$mms_id;
	}
	
	$recipient_list = "";
	$msg_count=0;
	
	$qry = "select recordkey, mobile_number from sms_subscribers where active='1'";
	$rt=mysql_query($qry); 
	
	while($data=mysql_fetch_array($rt)){
		if($sms_balance>0){
			$client = new Mogreet($clientId, $token);
			$response = $client->transaction->send(array(
						'campaign_id' => $campaign_id, // Your SMS campaign ID from https://developer.mogreet.com/dashboard
						'to' => $data['mobile_number'],
						'message' => $msg,
						'content_url' => $image_url
			));
			//print $response->messageId;
			//print $response->status;
			if($response->status =="success"){
				$msg_count++;
				if($recipient_list == ""){
					$recipient_list = $data[recordkey];
				} else {
					$recipient_list .= ", ".$data[recordkey];
				}
				$sms_balance=$sms_balance-1;
			}
		} else {
			$sec2_notice_msg="<font color='red'>You have reached your monthly send limit.</font>";
			break;
		}
	}	
	//add successful recipients to log for current sms message
	$qry = "update sms_message_log set recipient_ids = '$recipient_list', recipient_count='$msg_count' where recordkey='$message_id'";
	mysql_query($qry);
	$sec2_notice_msg.="<font color='red'>Message successfully sent to $msg_count recipients.</font>";

}
if($_REQUEST['delstored']){
	$qry="delete from sms_storage where recordkey='".$_REQUEST['delstored']."'";
	mysql_query($qry);
}
echo '<br><br><div id="single-admin-button">
<ul>
<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
</ul>
</div>';
if($sms_enabled =='1'){
	echo '<div class="arrowlistmenu">';
	##******************************************* BEGIN SECTION 1 *****************************************##
	echo'<h3 class="menuheader expandable">Quick SMS Blast</h3>';
	echo'<ul class="categoryitems">';
	echo '<center><table width="90%"><tr><td><center>'.$sec1_notice_msg.'</center>Send a quick text to all active subscribers:
	<br><br><form action="" method="post">
	Message:<br>
	<textarea name="message_body" cols=40 rows=3></textarea><br>
	Enter image URL<font color="red">*</font>:<br>
	<input type="text" name="image_url"><br>
	<input type="submit" name="send" value="Send Message Now"></form>
	<br><font color="red">*</font><i>Adding a an image converts the text to an MMS message.</i>';
	echo'</table></center></ul>';
	##******************************************* END SECTION 1 *****************************************##

	##******************************************* BEGIN SECTION 2 *****************************************##
	echo'<h3 class="menuheader expandable">SMS Messages</h3>
	<ul class="categoryitems"><center><table width="90%"><tr><td><center>'.$sec2_notice_msg.'</center>';
	//add new message
	echo "Add new stored SMS message: <br>
	<form action='' method='POST'><textarea name='new_message' cols='40' rows='3'></textarea><br>
	Enter image URL<font color='red'>*</font>:<br>
	<input type='text' name='image_url' size='50'><br>
	<input type='submit' name='save_message' value='Save Message'></form>
	<br><font color='red'>*</font><i>Adding a an image converts the text to an MMS message.</i>";
	//display exissting messages
	$qry="select * from sms_storage";
	$rt=mysql_query($qry); 
		echo"<table><tr><td colspan='2' height='1' bgcolor='gray'>";
		while($data=mysql_fetch_array($rt)){
			echo "<tr><td valign='top' width='70%'>".$data[sms_body];
			if(!empty($data[image_url])){echo "<br><img src='".$data[image_url] . "'><br><i>".$data[image_url]."</i>";}
			echo"<td valign='top'> <a href='?admin-page=".$_GET['admin-page']."&sendstored=".$data[recordkey]."'>Send to subcribers</a> <a href='?admin-page=".$_GET['admin-page']."&delstored=".$data[recordkey]."'>Delete</a><tr><td colspan='2' height='1' bgcolor='gray'>";
		}
		echo"</table>";
	//echo 'test';
	echo'</table></center></ul>';
	##******************************************* END SECTION 2 *****************************************##

	##******************************************* BEGIN SECTION 3 *****************************************##
	echo'<h3 class="menuheader expandable">SMS Blast Log</h3>
	<ul class="categoryitems"><center><table width="90%"><tr><td>';
	//set report period if selected
	if(!empty($_REQUEST['report_mo'])){$report_mo=$_REQUEST['report_mo'];} else {$report_mo=$month;}
	if(!empty($_REQUEST['report_yr'])){$report_yr=$_REQUEST['report_yr'];} else {$report_yr=$year;}
	
	echo"<center>Month: <select name='report_mo'>";
	$x=1;
	while($x<=12){
		echo"<option value='$x'";
		if($x==$report_mo){echo " selected='selected'";}
		echo">$x</option>";
		$x++;
	}
	echo"</select>";
	//echo $year;
	//echo "<br>".$month;
	echo" Year: <select name='report_year'>";
	$begyear = $year-10;
	while($year>=$begyear){
		echo"<option value='$year'";
		if($year==$report_yr){echo " selected='selected'";}
		echo">$year</option>";
		$year--;
	}
	echo"</select></center>";
	
		echo $body3;
	
	echo'</table></center></ul>';
	##******************************************* END SECTION 3 *****************************************##

	echo'</div>';
} else {
	echo"<div>You aren't authorized to access this page. Please subscribe to SMS services in order to view this page.</div>";
}
?>


<script type="text/javascript" src="includes/tinyaccordion/script.js"></script>

<script type="text/javascript">

var parentAccordion=new TINY.accordion.slider("parentAccordion");
parentAccordion.init("acc","h3",1,-1);

var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
nestedAccordion.init("nested","h3",1,-1,"acc-selected");

var nestedAccordion2=new TINY.accordion.slider("nestedAccordion2");
nestedAccordion2.init("nested2","h3",1,-1,"acc-selected");


//var parentAccordion=new TINY.accordion.slider("parentAccordion");
//parentAccordion.init("acc","h3",0);

//var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");
</script>
