<?php 
session_start();
require('db.php'); 
include('inc/func.php');
include('inc/logo.php');
?> 
<?php include('inc/header.php');?> 

        <!-- ============================================================== -->
        <!-- end navbar -->
        <!-- ============================================================== -->
       
        <!-- ============================================================== -->
        <!-- left sidebar -->
        <!-- ============================================================== -->
       <?php include('inc/nav.php');?>
         
        <!-- ============================================================== -->
        <!-- end left sidebar -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- wrapper  -->
        <!-- ============================================================== -->
        <div class="dashboard-wrapper">
            <div class="dashboard-ecommerce">
                <div class="container-fluid dashboard-content ">
                    
              
                    <!-- ============================================================== -->
                    <!-- pageheader  -->
                    <!-- ============================================================== -->
                    <div class="row">
                        <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                            <div class="page-header">
                                <h2 class="pageheader-title">Bulk Messaging </h2>
                        
                               
                            </div>
                        </div>
                    </div>
                    <!-- ============================================================== -->
                    <!-- end pageheader  -->
                    <!-- ============================================================== -->
                    <div class="ecommerce-widget">

                        <div class="row"></div>
                        <div class="row">
                            <!-- ============================================================== -->
                      
                            <!-- ============================================================== -->

                                          <!-- recent orders  -->
                            <!-- ============================================================== -->
                            <div class="col-xl-9 col-lg-12 col-md-6 col-sm-12 col-12">
                                <div class="card">
                                    <h5 class="card-header">Compose SMS</h5>
                                    <div class="card-body">
                                    
                               
<?php
									

 	
									
									if(isset($_POST['send'])){
										
										
										$from = $_POST['sender'];
										
										$sendto = $_POST['sendto'];
										$txt = $_POST['message'];
										$schedule = $_POST['sendlater'];
										
										$reff = mt_rand(200888544,748988444);

$sendto = filter_var($sendto, FILTER_SANITIZE_STRING);
$from = filter_var($from, FILTER_SANITIZE_STRING);
$txt = filter_var($txt, FILTER_SANITIZE_STRING);
$schedule = filter_var($schedule, FILTER_SANITIZE_STRING);



$sendto = mysqli_real_escape_string ($conn, $sendto);
$from = mysqli_real_escape_string ($conn, $from);
$txt = mysqli_real_escape_string ($conn, $txt);
$schedule = mysqli_real_escape_string ($conn, $schedule);

$from = str_replace( array( '+', ',', '-', '/', '(', ')',   '_',  '//', 'drop', 'update', 'delete', 'insert', 'add',  '{',   '}',   '<',  '>',  '=', '  ', '   '), '', $from);


$sendto = str_replace( array('-', '/', '(', ')',   '_',  '//', 'drop', 'update', 'delete', 'insert', 'add',  '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $sendto);


$schedule = str_replace( array( '+',  '(', ')',   '_',  '//', 'drop', 'update', 'delete', 'insert', 'add',  '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $schedule);

										
if($level == $Portal ){
$charge = 0; //$pol['sms'];

}elseif($level == $Reseller ){
$charge = $bill['sms'];

		
}elseif($level == $Agent){
$charge = 0; //$agentbil['sms'];

	
}elseif($level == $free){		
$charge = $regbil['sms'];
                                               
}else{
$charge = 10;

 }	


 
				$Charlen = strlen($txt);
			
			 $sms_array = explode("," , $sendto);
			  
			  $no = count($sms_array);
			  
			  if($Charlen <='160'){
				  
				 $bi = $charge; 
				  }elseif($Charlen <='320'){
					  
					$bi = $charge*2;  
					  }elseif($Charlen <= '480'){
						  
						$bi = $charge*3;  
						  }elseif($Charlen <= '640'){
							
							$bi = $charge*4;

                          }elseif($Charlen <= '800'){
							
							$bi = $charge*5;							
							  
						  }else{
							  
							$bi = $charge*10;  
							  }
							  

$tot = $bi * $no;
$units = $tot/$charge;
$balanceA = $bal - $tot;
$balA= $bal-$tot;
				
				
			if(!empty($from) &&!empty($sendto) && !empty($txt) ){
											
									
if($bal >= $tot){
											
if($tot >= "2"){						
										
		
$qryApi = mysqli_query($conn,"SELECT * FROM api_setting");
$apidata = mysqli_fetch_array($qryApi);	
$apikey = $apidata['APIkey'];
		
$message = utf8_encode($txt);
$aa = urlencode($message);
$sender = utf8_encode($from);
$senderid = urlencode($sender);


$baseurl = "https://vtuafrica.com.ng/portal/api/sms/?apikey=$apikey&sendto=$sendto&message=$aa&sender=$senderid";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$content1 = curl_exec($ch);
                                    
curl_close($ch);


 $content = json_decode($content1); 
$APImessage = $content->description->message;		
		
if($content->code == '101') {

$Ddebit = "UPDATE users SET bal=bal-$tot WHERE email='$user'";
$doDebit = $conn->query($Ddebit);		

$Completed = 'Completed';


			
$qsel = "INSERT INTO message_history(mobile,sender,message,apiresponse,email,refid,status,senttime,charge,channel,user,balanceB,balanceA,del,today,month,date)VALUES('$sendto','$from','$txt','$APImessage','$user','$uid','$Completed','$dateTime','$tot','Wallet','$fname $lname','$bal','$balanceA','$del','$today','$month','$date')";
$sav = $conn->query($qsel);

  echo '<div class="alert alert-success">
		<button type="button" class="close" data-dismiss="alert">×</button>
	    <strong>Message Sent</strong> 
									</div>';

			

}else {
    
   echo '<div class="alert alert-danger">
		<button type="button" class="close" data-dismiss="alert">×</button>
	    <strong>Error occured. '.$APImessage.' <br> Please contact '.$sitephone.'</strong> 
									</div>';
        }




	}else{
												
	echo'<div class="alert alert-danger">
										<button type="button" class="close" data-dismiss="alert">×</button>
										<strong>Invalid Transaction Amount</strong> 
									</div>';
											}

			
											}else{
												
										echo'<div class="alert alert-danger">
										<button type="button" class="close" data-dismiss="alert">×</button>
										<strong>Insufficient Balance</strong> 
									</div>';
											}
											
											}else{
												echo'<div class="alert alert-danger">
										<button type="button" class="close" data-dismiss="alert">×</button>
										<strong>Enter required field</strong>  
									</div>'; }
										
								
										
									}
									 ?>
                                        <form method="post" action="">
                                            <div class="form-group">
                                                <label for="inputText3" class="col-form-label">Sender ID</label>
                                                <input id="inputText3" type="text" class="form-control" name="sender">
                                            </div>
                       
                                            <div class="form-group">
                                                <label for="exampleFormControlTextarea1">Receipient</label> (<font color="red">Seperate each number with comma EG. 08021111111,08032121212,08034343232,)</font>
                                                <textarea class="form-control" id="sendto" rows="8" name="sendto"  ></textarea>
                                            </div>
                                            
                                            
                                      
                                                <select class="form-control" id="ifYes" style="display:none">
											
                                                </select>
                                                
                                               
                               
			            <div class="form-group">
			                <label class="col-lg-2 col-md-12 control-label"></label>
			                <div class="col-lg-8 col-md-12">
			                	<p><strong id="destcount"></strong> <strong id="grp_select_check"></strong></p>  
			                </div>
			            </div>
                                
                                
                                            <div class="form-group">
                                                <label for="exampleFormControlTextarea1">Message</label>
                                                <textarea class="form-control" id="message" onchange="countMsgsText(this.value);" onkeyup="countMsgsText(this.value);" rows="7" name="message"></textarea>
                                            </div>
                                       
                                        <div class="form-group">
			                <label class="col-lg-2 col-md-12 control-label"></label>
			                <div class="col-lg-8 col-md-12">
			                <div>
			                	<b id="paget"></b>
			                	<b id="count"></b>
			                </div>                
							<div class="hidden" id="hiddenCount"></div>    
			                </div>
                               </div> 
                               
                     
                                             
                                                <input type="date" class="form-control" id="sendlater" style="display:none" name="sendlater" > 
                                                
                                          
												
                                                <p></p>                      
                               
                                     <div class="col-sm-6 pl-0">
                                                <p class="text-right">
                                                    <button type="submit" name="send" class="btn btn-space btn-primary">Send Message</button>
                                                    
                                                </p>
                                            </div> 
                                             
                                            <p></p>     
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <!-- ============================================================== -->
                            <!-- end recent orders  -->
                            
                            <script>
                                
                             
 function cont() {
    if (document.getElementById('phonebook').checked) {
        document.getElementById('ifYes').style.display = 'block';
    }
    else  document.getElementById('ifYes').style.display = 'none';
    
    
   if (document.getElementById('schedule').checked) {
        document.getElementById('sendlater').style.display = 'block';
    }
    else  document.getElementById('sendlater').style.display = 'none'; 
   
}    
                      
   $("#sendto").on("keyup", function() {
  $(this).val($(this).val().replace(/[\,\-\n]/g, ","));
});           
                                
                            </script>

    
                            <!-- ============================================================== -->
                            <!-- ============================================================== -->
                            <!-- customer acquistion  -->
                            <!-- ============================================================== -->
                            <div class="col-xl-3 col-lg-6 col-md-6 col-sm-12 col-12">
                                <div class="card">
                                    <h5 class="card-header">Account Status</h5>
                                    <div class="card-body">
                                   <div class="d-inline-block">
                                        <h5 class="text-muted">Current Balance</h5>
                                        <h2 class="mb-0"> &#x20A6;<?php echo number_format($bal,2,'.',',');?></h2>
                                    </div>
                                    <div class="float-right icon-circle-medium  icon-box-lg  bg-brand-light mt-1">
                                        <i class="fa fa-money-bill-alt fa-fw fa-sm text-brand"></i>
                                    </div>
                                   
                                    </div>
                                </div>
                                
                                <div class="card">
                                <div class="card-body">
                                    <div class="d-inline-block">
                                        <h5 class="text-muted">Total Contacts</h5>
                                        <h2 class="mb-0"> 0</h2>
                                    </div>
                                    <div class="float-right icon-circle-medium  icon-box-lg  bg-primary-light mt-1">
                                        <i class="fa fa-user fa-fw fa-sm text-primary"></i>
                                    </div>
                                </div>
                            </div>
                            </div>
                            <!-- ============================================================== -->
                            <!-- end customer acquistion  -->
                            
                          
                            <!-- ============================================================== -->
                        </div>
                        <div class="row">
                            <!-- ============================================================== -->
              				                        <!-- product category  -->
                            <!-- ============================================================== -->
                            <!-- ============================================================== -->
                            <!-- end product category  -->
                          
  	<script type="text/javascript">
		//datepicker plugin
		//link	
	


		function countMsgsText(val){

			val = val.split("\n").join('??').split('{').join('??').split('}').join('??');

			val = val.split('\\').join('??').split('[').join('??').split(']').join('??');

			val = val.split('~').join('??').split('|').join('??').split('^').join('??');

			val = val.split('€').join('??').split('"').join('??').split("'").join('??');

			len = val.length;

			if(len<=160){

				jQuery('#paget').html('Page: '+Math.ceil(len/160));
				jQuery('#count').html(', Characters left: ' + (1+((160 - 1) * Math.ceil(len/160))-len) + ', Total Typed Characters: '+len);

				jQuery('#hiddenCount').html(Math.ceil(len/160)+' page');

			} else {
				jQuery('#paget').html('Page: '+Math.ceil(len/151));
				jQuery('#count').html(', Characters left: ' + (1+((151 - 1) * Math.ceil(len/151))-len) + ', Total Typed Characters: '+len);	

				jQuery('#hiddenCount').html(Math.ceil(len/151)+' pages');

			}

			countDest();

		}

		
	

	</script>
                                   <!-- product sales  -->
                            <!-- ============================================================== -->
                            <!-- ============================================================== -->
                            <!-- end product sales  -->
                            <!-- ============================================================== -->
                        </div>

                        <div class="row">
                            <!-- ============================================================== -->
                            <!-- sales  -->
                            
                            <!-- ============================================================== -->
                            
                        </div>
                        <div class="row">
                            <!-- ============================================================== -->
                           
                            <!-- end category revenue  -->
                            <!-- ============================================================== -->
                        </div>
                        <div class="row">
                          <!-- ============================================================== -->
                            <!-- end sales traffice source  -->
                            <!-- ============================================================== -->
                            
                        </div>
                    </div>
                </div>
            </div>
            <!-- ============================================================== -->
            <!-- footer -->
            <!-- ============================================================== -->
           <?php include('inc/footer.php');?>