<?php 
	
	 require_once('../crm/Connections/newConMarketer.php');
	 
	  require_once('newSendsms_africastalking.php');

	$username = htmlspecialchars($_GET['username'],ENT_QUOTES);
	$password = htmlspecialchars($_GET['password'],ENT_QUOTES);
	$destination = htmlspecialchars($_GET['destination'],ENT_QUOTES);
	$source = htmlspecialchars($_GET['source'],ENT_QUOTES);
	$message = $_GET['message'];//htmlspecialchars($_GET['message'],ENT_QUOTES); //replaced with the get
	$sendsms=""; 
	$origin = htmlspecialchars($_GET['origin'],ENT_QUOTES);
	
	 if(empty($username) && empty($password) && empty($destination) && empty($message) ){
		die("Empty Credentials.");
	}
	
/*	$message = "Testing API Account.";
	$username = "demo1";
	$password = "dem0";
//	$destination = "+254727992036,254720003004,+254729980707,254727992039";
	$destination = "+254727992036";
	$sendsms="";  */
	
	$shop = NULL;
	$shop = authenticateAPIUser($db,$username,$password);

	//$sms = str_replace('+',' ',$_GET['message']);
	$sms = str_replace('+', ' ',$message);
	
//	echo $shop;
//    echo '<br>';
    
	$last_char = substr($sms,-1);
	if($last_char == '?'){
		$sendsms = $sms;
	}elseif($last_char == '.'){
		$sendsms = $sms;
	}else{
		$sms .=".";
		$sendsms = $sms;
	}
	
//	echo $sendsms;
//	  echo '<br>';

	//add tail message to SMS
	$sms2 = $sendsms.' '.getTailMessage($db,$shop);

	$sms2 = str_replace('+',' ',$sms2);
	
//	echo $sms2;
//	 echo '<br>';
	 
	 
	$recipients = (int)substr_count($destination,',')+1;	
	
	if($recipients > 1){
		$recipient = explode(',',$destination);
	}
	else{
		$recipient[0] = $destination;
	}
	
	$sms_size = ceil(strlen($sms2)/160);
	$size = sizeof($recipient);

	$total = (float)0;


	for($i =0 ; $i < $size ; $i++){
		$mobile  = $recipient[$i];
		$total	+= (float)getSMSCost($db,$shop,$mobile,$sms_size);
	//	echo "total:".$total."<br/>";
	}
	
	echo '<br>';
	
	if($shop != NULL) {
		
		$available = (float)checkCurrencyCredits($db,$shop);
		$source = getShopSMSName($db,$shop);
	
		if($available>=$total && $available!=0) {
	
				//SMS billing
				
		
			if($sms_size>1) {
					//Long SMS
			//$reply = fopen("http://api.infobip.com/api/sendsms/plain?user=mobisky1&password=mobi082010&sender=$source&SMSText=$sms&GSM=$destination&Type=LongSMS",rb);
			    //check destination number
			    
			    if(substr($destination, 0, 3 ) === "256"){
			        
                echo "Cannot send to a Ugandan number";
                }
                elseif(substr($destination, 0, 3 ) === "254"){
                  
                  $results = sendSMS($db,$destination,$sms2,$source,$shop,$origin);  
                  
                      foreach($results as $result) {
    				    $price = 0;
    				    if($result->status == 'Success'){
                    	    $price = (float)getSMSCost($db,$shop,$result->number,$sms_size);
    				    }
                    	$api_cost = explode(" ", $result->cost);
    			        smsCharge($db,$shop,$price,$result->number,$sms2,$source,$origin,$sms_size,$api_cost[1],$price,$result->status,$result->messageId);
    				}
                }
            	
			
			//echo "<br>$destination<br>$sms<br>$source<br>$shop";
			}
			else{
				//$reply = join('',file("http://api.infobip.com/api/sendsms/plain?user=mobisky1&password=mobi082010&sender=$source&SMSText=$sms&GSM=$destination"));
					//$results = sendSMS($db,$destination,$sms2,$source,$shop,$origin);
					
					
					
				if(substr($destination, 0, 3 ) === "256"){
			        
                echo "Cannot send to a Ugandan number";
                }
                
                elseif(substr($destination, 0, 3 ) === "254"){
                  
                  $results = sendSMS($db,$destination,$sms2,$source,$shop,$origin); 
                      foreach($results as $result) {
    				    $price = 0;
    				    if($result->status == 'Success'){
                    	    $price = (float)getSMSCost($db,$shop,$result->number,$sms_size);
    				    }
                    	$api_cost = explode(" ", $result->cost);
    			        smsCharge($db,$shop,$price,$result->number,$sms2,$source,$origin,$sms_size,$api_cost[1],$price,$result->status,$result->messageId);
    				}
                }
                
				
				//	echo "<br>$destination<br>$sms<br>$source<br>$shop";
			}	
		}
		else{
			?><!--<script type="text/javascript">alert("Insufficient SMS credits!.Please top up your account.");</script> -->
			<?php echo "Insufficient Balance";
		}
	}
	
        else{
		//echo "1703";//Invalid credentials.Provide correct username and password";	
		echo "Error  Invalid Credentials";
	}	
	
	

	function authenticateAPIUser($db,$username,$password) {
		
		$stmt = $db->prepare("SELECT shop_id FROM sms_api_users WHERE username=? AND password=?");
		$stmt->execute(array($username,$password));
		$rData = $stmt->fetch(PDO::FETCH_ASSOC);
			
		/*$sql = $db->prepare("SELECT shop_id FROM sms_api_users WHERE username=:username AND password=:password");
		$sql->bindValue(':username', $username, PDO::PARAM_STR);
		$sql->bindValue(':password', $password, PDO::PARAM_STR);
		$sql->execute();
		$rsData = $sql->fetchAll(PDO::FETCH_ASSOC); */
		
		 $rdt = "";
		
			if(strlen($rData['shop_id']) > 0) {
				$rdt = $rData['shop_id'];
			}
			else
				 $rdt = NULL; 
				
		return $rdt;
	}
	

    function getTailMessage($db,$shop) {
		
		$tail_message = "";
		$query = "SELECT tail_message FROM shop WHERE ShopID=? ";
		$stm = $db->prepare($query);
		$stm->execute(array($shop));
		$row_count = $stm->rowCount();
	//	echo $row_count.' rows selected';
	
	    if($row_count > 0){
	        $tmes = $stm->fetch(PDO::FETCH_ASSOC);
			$tail_message  = $tmes['tail_message'];
		}
		
		return $tail_message;	
	}
	
	function getCostPerSMS($db,$shop,$mobile){
	    
		$justNums = preg_replace("/[^0-9]/", '', $mobile); //check whether phone number has leading characters like +
		$country = substr($justNums,0,3);
	//	$country = substr($mobile,0,3);
	//    echo $country;
	    
		$price = 0;
		$price_query = "SELECT rate FROM country_rates WHERE country_id = (SELECT countries.id FROM countries WHERE code=? ) AND current = 1 AND shopid=? ";
		$stm1 = $db->prepare($price_query);
		$stm1->execute(array($country,$shop));
		$row_count = $stm1->rowCount();
		
		if($row_count > 0){
			
			while($row = $stm1->fetch(PDO::FETCH_OBJ)) {
				
				$price = (float)$row->rate;
			}
			
		}
		else
		{
		$country="254";
		$price_query = "SELECT rate FROM country_rates WHERE country_id = (SELECT countries.id FROM countries WHERE code=? ) AND current = 1 AND shopid=? ";
		$stm1 = $db->prepare($price_query);
		$stm1->execute(array($country,$shop));
		$row_count = $stm1->rowCount();
		
		if($row_count > 0){
			
			while($row = $stm1->fetch(PDO::FETCH_OBJ)) {
				
				$price = (float)$row->rate;
			}
			
		}
		    
		}
		
		
		return $price;	
	}	
	
	function getSMSCost($db,$shop,$mobile,$sms_size){
		
		$cost = (float)getCostPerSMS($db,$shop,$mobile) * $sms_size;
		
		return $cost;	
	}
	
	
	function checkCurrencyCredits($db,$shop){
		
		$credits = 0;
		$creditsql = "SELECT amount FROM currency_credits WHERE shopid=? ";	
		$stm2 = $db->prepare($creditsql);
		$stm2->execute(array($shop));
		$row_count = $stm2->rowCount();
		
		if($row_count > 0){
			while($row = $stm2->fetch(PDO::FETCH_OBJ)) {
				
				$credits = (float)$row->amount;
			}
		}
  
		return $credits;
	}
	
	function getShopSMSName($db,$shop){

		$query = "SELECT sms_name FROM shop WHERE ShopID=? ";	
		$stm3 = $db->prepare($query);
		$stm3->execute(array($shop));
		$row_count = $stm3->rowCount();
		
		if($row_count > 0){
			while($row = $stm3->fetch(PDO::FETCH_OBJ)) {
				
				$shop_name = $row->sms_name;
			}
		}
		
		return $shop_name;	
	}
	
	function smsCharge($db,$shop,$cost,$destination = "",$sms2 = "",$source = "",$origin = "",$sms_size = 0,$unit_cost = 0,$price = 0,$status = "Success",$messageid = ""){
		
		date_default_timezone_set("Africa/Nairobi");
		$today = date("Y-m-d H:i:s");
		
		$stmt = $db->prepare("INSERT INTO currency_expenditure(shopid,amount,date_time,destination,sms,source,origin,sms_size,unit_cost,price,status,messageid) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ");
		$stmt->execute(array($shop,$cost,$today,$destination,$sms2,$source,$origin,$sms_size,$unit_cost,$price,$status,$messageid));
		
		$credits_query = "SELECT amount FROM currency_credits WHERE shopid =? ";
		$stmx = $db->prepare($credits_query);
		$stmx->execute(array($shop));
		$rsData = $stmx->fetch(PDO::FETCH_ASSOC);
		
		$credits = (float)$rsData['amount'];
		$new_credits = (float)$credits - $cost;

		$credits_update = "UPDATE currency_credits SET amount =? WHERE shopid =? ";
		$stmx1 = $db->prepare($credits_update);
		$stmx1->execute(array($new_credits, $shop));
		
 
		//check if balance is below specified minimum
			// if below send email
		$balance_limit = "SELECT balance_limit, email_address FROM balance_limit where shop_id =? ";
		$stmx2 = $db->prepare($balance_limit );
		$stmx2->execute(array($shop));
		$rData = $stmx2->fetch(PDO::FETCH_ASSOC);
		$bal = $rData['balance_limit'];
		$email = $rData['email_address'];

	}
	
	
	
	
	
	
	
	
	
	
	

?>
