<?php session_start();
		if (isset($_SESSION['logged']) && $_SESSION['logged'] == 'yes') {
			include ('../../../scripts/classes.php'); //Retrieve functions
            if ($_SESSION['lang']=="EN"){$lang="EN"; include ('../../../lang/en.php');}elseif ($_SESSION['lang']=="GR"){$lang="GR";include ('../../../lang/gr.php');}else {$lang="EN";include ('../../../en.php');}
            
            $user_id = Core::GetUserId();				
			$array = getGlobalSettings(); //Retrieve Global Settings	
			$array_sms = getSMSSettings();//Get Global Settings
			foreach ($array_sms as $sms_settings){ extract($sms_settings);}
			
			if ($local_server_os=='windows'){
						$line_break="\r\n";
			} elseif ($local_server_os=='linux'){
						$line_break="\n";
			}
            							
			$ftp_api_id = "FTP API:$primary_ftp_api_id";		
			$page_title = $lbl_bulk_processing; //Assign Page Title
			$mode = $lbl_send_file; //Assign Mode
			$file_name = $_POST['file_name'];
			$campaign = $_POST['campaign'];
			##~~~~~~~~~~~~~~~~~~~~~~~CRITICAL~~~~~~~~~~~~~~~~~~~~~~~##
			//count records of campaign again - don't trust posted
            $count_mob = ("SELECT id FROM sms_campaign_details WHERE campaign_id='$campaign'");
            $result_mob= mysqli_query($mysqli, $count_mob) or die('An error occurred while fetching the number of phones in campaign: ' . mysqli_error($mysqli));
            $number_of_mob = mysqli_num_rows($result_mob);
			//echo $number_of_mob;
			//now retrieve current credits
            $credit_balance = getSMSBalance();	
			//compare and decide
				if ($credit_balance == 0){?>
						<script type="text/javascript">alert('<?php echo $lbl_error_balance_changed ?>'); </script>
						<?php
						//Update roufianos.log
						$filename = "../../../logs/roufianos.log";
						$content = stripslashes("\r\n".date("d-m-Y")." USER #system# Balance error ".date("H:i:s")); 
						$fp1 = fopen($filename,"a") or die ("Error opening file in write mode!");
						fputs($fp1, $content);
						fclose($fp1) or die ("Error closing log file!");
						exit();		
				}
				$name = $file_name;
						$name = str_replace(" ","_",$name,$i);
						$name = str_replace("α","a",$name,$i);
						$name = str_replace("Α","A",$name,$i);
						$name = str_replace("ά","a",$name,$i);
						$name= str_replace("Ά","A",$name,$i);
						$name= str_replace("Β","B",$name,$i);
						$name= str_replace("β","b",$name,$i);
						$name = str_replace("Γ","G",$name,$i);
						$name = str_replace("γ","g",$name,$i);
						$name = str_replace("Δ","D",$name,$i);
						$name = str_replace("δ","d",$name,$i);
						$name = str_replace("Ε","E",$name,$i);
						$name = str_replace("ε","e",$name,$i);
						$name = str_replace("Έ","E",$name,$i);
						$name = str_replace("έ","e",$name,$i);
						$name = str_replace("Ζ","Z",$name,$i);
						$name = str_replace("ζ","z",$name,$i);
						$name = str_replace("Η","H",$name,$i);
						$name = str_replace("η","i",$name,$i);
						$name = str_replace("Ή","H",$name,$i);
						$name = str_replace("ή","i",$name,$i);
						$name = str_replace("Θ","TH",$name,$i);
						$name = str_replace("θ","th",$name,$i);
						$name = str_replace("Ι","I",$name,$i);
						$name = str_replace("ι","i",$name,$i);
						$name = str_replace("Ί","I",$name,$i);
						$name = str_replace("ί","i",$name,$i);						
						$name = str_replace("Κ","K",$name,$i);
						$name = str_replace("κ","k",$name,$i);
						$name = str_replace("Λ","L",$name,$i);
						$name = str_replace("λ","l",$name,$i);
						$name = str_replace("Μ","M",$name,$i);
						$name = str_replace("μ","m",$name,$i);
						$name = str_replace("Ν","N",$name,$i);
						$name = str_replace("ν","n",$name,$i);
						$name = str_replace("Ξ","X",$name,$i);
						$name = str_replace("ξ","x",$name,$i);
						$name = str_replace("Ο","O",$name,$i);
						$name = str_replace("ο","o",$name,$i);
						$name = str_replace("Ό","O",$name,$i);
						$name = str_replace("ό","o",$name,$i);						
						$name = str_replace("Π","P",$name,$i);
						$name = str_replace("p","P",$name,$i);
						$name = str_replace("Ρ","P",$name,$i);
						$name = str_replace("ρ","r",$name,$i);
						$name = str_replace("Σ","S",$name,$i);
						$name = str_replace("σ","s",$name,$i);
						$name = str_replace("ς","s",$name,$i);
						$name = str_replace("Τ","T",$name,$i);
						$name = str_replace("τ","t",$name,$i);
						$name = str_replace("Υ","Y",$name,$i);
						$name = str_replace("υ","y",$name,$i);
						$name = str_replace("Ύ","Y",$name,$i);
						$name = str_replace("ύ","y",$name,$i);						
						$name = str_replace("Φ","F",$name,$i);
						$name = str_replace("φ","f",$name,$i);
						$name = str_replace("Χ","CH",$name,$i);
						$name = str_replace("χ","ch",$name,$i);
						$name = str_replace("Ψ","PS",$name,$i);
						$name = str_replace("ψ","ps",$name,$i);						
						$name = str_replace("Ω","O",$name,$i);
						$name = str_replace("ω","o",$name,$i); 
						$name = str_replace("Ώ","O",$name,$i);
						$name = str_replace("ώ","o",$name,$i); 
				//end of characters mapping
				$filename = $name."_".date("d")."_".date("m")."_".date("Y")."_".date("His");
				$sender = $_POST['sender'];
				$deliv_time = $_POST['deliv_time'];
				$deliv_queue = $_POST['deliv_queue'];
				$sched_time = $_POST['sched_time'];
				$sms_text = $_POST['sms_text'];
				//convert sms_text chars
				$message = $sms_text;
                        $message = str_replace("%","%25",$message,$i);
						$message = str_replace(" ","+",$message,$i);
						$message = str_replace("Α","A",$message,$i);
						$message= str_replace("Ά","A",$message,$i);
						$message= str_replace("Β","B",$message,$i);
						$message = str_replace("Γ","%13",$message,$i);
						$message = str_replace("Δ","%10",$message,$i);
						$message = str_replace("Ε","E",$message,$i);
						$message = str_replace("Έ","E",$message,$i);
						$message = str_replace("Ζ","Z",$message,$i);
						$message = str_replace("Η","H",$message,$i);
						$message = str_replace("Ή","H",$message,$i);
						$message = str_replace("Θ","%19",$message,$i);
						$message = str_replace("Ι","I",$message,$i);
						$message = str_replace("Ί","I",$message,$i);
						$message = str_replace("Κ","K",$message,$i);
						$message = str_replace("Λ","%14",$message,$i);
						$message = str_replace("Μ","M",$message,$i);
						$message = str_replace("Ν","N",$message,$i);
						$message = str_replace("Ξ","%1A",$message,$i);
						$message = str_replace("Ο","O",$message,$i);
						$message = str_replace("Ό","O",$message,$i);
						$message = str_replace("Π","%16",$message,$i);
						$message = str_replace("Ρ","P",$message,$i);
						$message = str_replace("Σ","%18",$message,$i);
						$message = str_replace("ς","%18",$message,$i);
						$message = str_replace("Τ","T",$message,$i);
						$message = str_replace("Υ","Y",$message,$i);
						$message = str_replace("Ύ","Y",$message,$i);
						$message = str_replace("Φ","%12",$message,$i);
						$message = str_replace("Χ","X",$message,$i);
						$message = str_replace("Ψ","%17",$message,$i);
						$message = str_replace("Ω","%15",$message,$i);
						$message = str_replace("Ώ","%15",$message,$i); 
                        $message = str_replace("€","%80",$message,$i);
                        $message = str_replace("@","%40",$message,$i);
                        $message = str_replace("#","%23",$message,$i);
                        $message = str_replace("$","%24",$message,$i);
                        $message = str_replace("^","%5E",$message,$i);
                        $message = str_replace("&","%26",$message,$i);
                        $message = str_replace("~","%7E",$message,$i);
                        $message = str_replace("`","%60",$message,$i);
                        $message = str_replace("|","%7C",$message,$i);
                        $message = str_replace("\\","%5C",$message,$i);
                        $message = str_replace("\"","%3A",$message,$i);
                        $message = str_replace(";","%3B",$message,$i);
                        $message = str_replace("{","%7B",$message,$i);
                        $message = str_replace("}","%7D",$message,$i);
                        $message = str_replace("[","%5B",$message,$i);
                        $message = str_replace("]","%5D",$message,$i);
                        $message = str_replace("<","%3C",$message,$i);
                        $message = str_replace(">","%3E",$message,$i);
                        $message =preg_replace( "/\r|\n/", "%0A", $message);
				//end of characters mapping
				$url_text=$message;
				$concat=$enable_concat;
				
		
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title ?></title>
<link rel="shortcut icon" href="../../../img/favicon.png" />
<link href="../../../cms1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script>top.document.title=self.document.title;</script>
	<div>
		<fieldset>
		<legend><?php echo $mode ?></legend>
		<div> 
			<span class="page_tips"><?php echo $lbl_text_file_send ?></span><br />
			<div class="success"><ul><li><?php echo $lbl_check_file_name ?> (<?php echo $filename ?>)...</li></ul></div>				
			<?php flush();?>
			<?php	//check if file exists
				$local_filepath=$local_sms_files_path."".$filename.".txt";
				if (file_exists ($local_filepath)){
						echo "<div class=\"critical\"><ul><li>".$lbl_error_file_exists."</li></ul></div>";
						exit();
					}else{
						echo "<div class=\"completed\"><ul><li>".$lbl_done."</li></ul></div>";
						echo "<div class=\"success\"><ul><li>$lbl_debug_file_creation</li></ul></div>";
						flush();
					touch($local_filepath) or die (_ERROR_CREATING_SMS_FILE);//create empty file;
						echo "<div class=\"completed\"><ul><li>".$lbl_done."</li></ul></div>";
						echo "<div class=\"success\"><ul><li>$lbl_debug_check_access</li></ul></div>";
						flush();
						if (is_readable ($local_filepath)) {
							echo "<div class=\"completed\"><ul><li>".$lbl_done."</li></ul></div>";
							echo "<div class=\"success\"><ul><li>$lbl_debug_write</ul></li></div>";							
							flush();
							}else{
						echo "<div class=\"critical\"><ul><li>".$lbl_error_access_denied."</li></ul></div>";
							exit();
							}
						set_time_limit(1000) or die("Time Limit Aborted procedure (1)"); //increase time out interval
							//Start file construction
							$line_1="api_id:$primary_ftp_api_id";
								$fp = fopen($local_filepath,"a+") or die ("Error opening file in write mode!");
								fwrite($fp,$line_1."".$line_break);
							$line_2="user:$primary_acc_user";	
								fwrite($fp,$line_2."".$line_break);
							$line_3="password:$primary_acc_pass";	
								fwrite($fp,$line_3."".$line_break);
							$line_4="from:$sender";	
								fwrite($fp,$line_4."".$line_break);
							$line_5="deliv_ack:1";	
								fwrite($fp,$line_5."".$line_break);								
							$line_6="callback:3";	
								fwrite($fp,$line_6."".$line_break);		
							$line_7="concat:$concat";	
								fwrite($fp,$line_7."".$line_break);	
							$line_8="deliv_queue:$deliv_queue";	
								fwrite($fp,$line_8."".$line_break);									
								if ($deliv_time!=""){									
									$line_9="deliv_time:$deliv_time";	
									fwrite($fp,$line_9."".$line_break);	
								}
								if ($sched_time!=""){	
									$line_10="scheduled_time:$sched_time";	
									fwrite($fp,$line_10."".$line_break);	
								}
							$line_11="urltext:$url_text";	
								fwrite($fp,$line_11."".$line_break);
							$line_12="delimiter:|";	
								fwrite($fp,$line_12."".$line_break);	
							$line_13="csvtemplate:cliMsgId";	
								fwrite($fp,$line_13."".$line_break);
       	                    $line_14="req_feat:48";	
								fwrite($fp,$line_14."".$line_break);	    																

							// select phones from db and write into file
							$phones = mysqli_query($mysqli, "SELECT phone, customer_id FROM sms_campaign_details WHERE campaign_id='$campaign'") or die("Error while_ running fetch query");
								while ($row = mysqli_fetch_assoc($phones)){
								$message_id = generatePassword($length = 32, $strength = 2);
								$phone=$row['phone'];
								$contact = $row['customer_id'];
								$phone_pre = $phones_country_pre."{$row['phone']}";
								fwrite ($fp, "csv:{$phone_pre}|{$message_id}".$line_break);	
								mysqli_query($mysqli, "INSERT INTO sms_outbox (batch_id, phone, status, message_id, sender, message, message_url, priority_queue, delivery_delay, scheduled_time, source_module, created_on, created_by, campaign_id, customer_id, carrier) VALUES ('$filename', '$phone', '000', '$message_id', '$sender', '$sms_text', '$url_text','$deliv_queue', '$deliv_time', '$sched_time', '$ftp_api_id', NOW(), '$user_id', '$campaign', '$contact', 'Clickatell')") or die("Error while updating sms_outbox");																																													
								}
								// close the output file	
								fclose($fp) or die ("Error closing log file!");
								echo "<div class=\"completed\"><ul><li>".$lbl_done."</li></ul></div>";
								echo "<div class=\"success\"><ul><li>$lbl_debug_connect</ul></li></div>";
								flush();
				}	
                                //count phones in file
                                $count_sms=("SELECT id FROM sms_outbox WHERE batch_id='$filename'");
                                $result_sms = mysqli_query($mysqli, $count_sms) or die('An error occurred while fetching the number of phone credits: ' . mysqli_error($mysqli));
                                $number_of_phones = mysqli_num_rows($result_sms);
                               // echo $number_of_phones ;
			set_time_limit(1000) or die("Time Limit Aborted procedure (2)"); //increase time out interval	
			ob_end_flush();
			$remote_file = $remote_sms_files_path."".$filename.".txt";
			$local_file = $local_filepath;
			$ftp_server =$primary_ftp_address;
			$ftp_user_name = $primary_ftp_user;
			$ftp_user_pass = $primary_ftp_pass;
            //echo $ftp_user_name." - ".$primary_ftp_pass; //just debugging
				
    $fp = fopen($local_file, 'r');
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
     if (!$ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_ASCII)){
		echo "<div class=\"critical\"><ul><li>".$lbl_error_cannot_connect."</li></ul></div>";
		mysqli_query($mysqli, "DELETE FROM sms_outbox WHERE batch_id='$filename'")or die("sms_outbox rollback failed!");	
		exit();
		}else{
		echo "<div class=\"completed\"><ul><li>".$lbl_done."</li></ul></div>";
		}
	 	
	?>		<div class="success"><ul><li><?php echo $lbl_file_upload_status ?>
			<input type="text" id="field0" value="0%" style="width:30px; border: none; background:none; height:10px; font-size:11px" />
			<input type="text" id="field" value="" style="width:100px; background-color:#33CC00; border: 1px solid #999999; height:10px" readonly="readonly" /></li></ul></div>
			<script>document.getElementById("field").style.visibility='visible'</script>
			<script>document.getElementById("field0").style.visibility='visible'</script>
<?php	flush();
	while ($ret == FTP_MOREDATA) {
        // Establish a new connection to FTP server
        if(!isset($conn_id2)) {
            $conn_id2 = ftp_connect($ftp_server);
            $login_result2 = ftp_login($conn_id2, $ftp_user_name, $ftp_user_pass);
        }
       
        // Retreive size of uploaded file.
        if(isset($conn_id2)) {
            clearstatcache(); // <- this must be included!!
            $remote_file_size = ftp_size($conn_id2, $remote_file);
        }

       // Calculate upload progress
       $local_file_size  = filesize($local_file);
       if (isset($remote_file_size) && $remote_file_size > 0 ){
           $i = ($remote_file_size/$local_file_size)*100;	
		   ?><script>document.getElementById("field0").value='<?php echo number_format($i-1,0)."%";?>'</script>
		   <script>document.getElementById("field").style.width='<?php echo $i."px"?>'</script>
		   <?php
           flush();
       } 
        $ret = ftp_nb_continue($conn_id);

	}
    if ($ret != FTP_FINISHED) {
			?>
			<script>document.getElementById("field").style.visibility='hidden'</script>
			<script>document.getElementById("field0").style.visibility='hidden'</script>
			<?php
       echo "<div class=\"critical\"><ul><li>".$lbl_error_upl_failed."</li></ul></div>";
				//Update roufianos.log
				$filename = "../../../logs/roufianos.log";
				$content = stripslashes("\r\n".date("d-m-Y")." USER #system# FTP Failed ".date("H:i:s")); 
				$fp1 = fopen($filename,"a") or die ("Error opening file in write mode!");
				fputs($fp1,$content);
				fclose($fp1) or die ("Error closing log file!");
				//end of updating roufianos.log		
				//rollback sms_outbox
				mysqli_query($mysqli, "DELETE FROM sms_outbox WHERE batch_id ='$filename'")or die("sms_outbox rollback failed!");												
        exit(1);
    }
    else {
	 ?><!--<script>document.location.href='page2.php'</script>--><?php
	 	?>	<script>document.getElementById("field").style.visibility='visible'</script>
			<script>document.getElementById("field0").style.visibility='visible'</script>
       		<script>document.getElementById("field0").value='100%'</script>
		<?php  //update credits
            	//mysql_query("update sms_credits set credits=credits-'$number_of_phones'")or die("sms_credits update failed!");
				mysqli_query($mysqli, "UPDATE sms_outbox SET success_flag='1' WHERE batch_id='$filename'")or die("sms_outbox update success_flag failed!");		
				echo "<div class=\"completed\"><ul><li>".$lbl_done_completed."</li></ul></div>";
				//Update roufianos.log
				$filename = "../../../logs/roufianos.log";
				$content = stripslashes("\r\n".date("d-m-Y")." USER #system# FTP Succeed ".date("H:i:s")); 
				$fp2 = fopen($filename,"a") or die ("Error opening file in write mode!");
				fputs($fp2,$content);
				fclose($fp2) or die ("Error closing log file!");
				//end of updating roufianos.log					
    }
    fclose($fp);
?>

</body>
</html>
<?php
} else {
    header('Location: login.php');
}
?>
