<?php
global $db,$conn;
set_time_limit(0);
ini_set('memory_limit','1024M');
ini_set('post_max_size','32M');
ini_set('upload_max_filesize ','32M');
//echo phpinfo();

$next_page_condition 	= "";
if($_REQUEST['campaign_id']){
	$campaign_id = $_REQUEST['campaign_id'];
	$next_page_condition.="&campaign_id=".$campaign_id;
}
$c_id = utility::app_crypt($_REQUEST['c_id'],'d');
if($_REQUEST['campaign_id'] != $c_id){
	die("Invaild URL");
}
if($_POST['importfile']) {
	$path = $_FILES['import_gsi']['name'];
	$ext = pathinfo($path, PATHINFO_EXTENSION);
	if($ext !='csv'){
		echo $msg = "<br><br><div style='border: 2px solid red;
		color: black;
		font-size: 14px;
		width: 250px;
		height: 50px;
		margin: 0 auto;
		text-align:center;
		padding: 10px;'>Please upload csv file only </div>";
		exit;
	}

$destdir = getcwd()."/bulk_import_csv/";
$filename = explode('.', $_FILES['import_gsi']['name']);
$namep1   = $filename[0];
//$name     = $namep1.'.'.$filename[1];
$dateString = str_replace("-","_",date($config->dateFormat));
$timeString = str_replace(":","_",date('H:i:s'));
$name     = $namep1.'_'.$dateString.'_'.$timeString.'.'.$filename[1];
$destfile = $destdir.$name;  

$batch_size = 3000;
$mail_inserted = 0;
$mail_updated = 0;   

move_uploaded_file($_FILES['import_gsi']['tmp_name'], $destfile);
                                   
$flag = true;
$fp = fopen($destfile, 'r');
while (!feof ($fp)){
  $buffer = fgetcsv($fp, 1000000, ',');  
  if($flag) {
	$fixed_sample_header = "FirstName,LastName,Email,Unsubscribe,UnsubscribeDate";
	$uploaded_sample_header = implode(",",$buffer);
	// echo $uploaded_sample_header."<br>";
	// echo $fixed_sample_header;
	$fixed_sample_header_array = explode(",",$fixed_sample_header);
	if($uploaded_sample_header != $fixed_sample_header){
		echo $msg = "<br><br><div style='border: 2px solid red;
		color: black;
		font-size: 14px;
		width: 450px;
		height: auto;
		margin: 0 auto;
		text-align:center;
		padding: 10px;'>CSV header is not correct, please follow the format given in import_sample.csv </div>";
		exit;
	}
	$flag = false;
	 continue; 
  }
  
	if($buffer){
		if(count($buffer) != count($fixed_sample_header_array)){
			$user_skiped++;
			continue;
		}
		$buffer=str_replace('"','',$buffer);//take care of double quotes in CSV
		
		$variable_array = array('FirstName','LastName','Email','Unsubscribe','UnsubscribeDate');
		
		foreach($variable_array as $key=>$val){		
			${$val} = addslashes($buffer[$key]);
		}
		if($FirstName =="FirstName"){
				continue;
			}
			
			$firstname    = "";
			if(isset($FirstName) && $FirstName!=""){
				$firstname  = $FirstName;
			}
			
			$lastname    = "";
			if(isset($LastName) && $LastName!=""){
				$lastname  = $LastName;
			}
	
		
			$email_encrypt    = "";
			if(isset($Email) && $Email!=""){
				$email_encrypt  = utility::app_crypt($Email,'e');
			}
			
			$unsubscribe = "0";
			if(isset($Unsubscribe) && $Unsubscribe!=""){
				if($Unsubscribe == 'Yes'){
					$unsubscribe = 1;
				}
			}
			
			if(isset($UnsubscribeDate) && $UnsubscribeDate !=""){
				$unsubscribe_date_array = explode("-",$UnsubscribeDate);
				$unsubscribe_date = $unsubscribe_date_array[2]."-".$unsubscribe_date_array[1]."-".$unsubscribe_date_array[0];
			}else{
				$unsubscribe_date = "0000-00-00 00:00:00";
			}
			

		$campaign_id            = $_REQUEST['campaign_id'];
		$created_by				= $_SESSION['user_id'];
		$updated_by				= $_SESSION['user_id'];
		$created_on				= date("Y-m-d H:i:s");

		/************** Data Upload ***********************************/
			$sql_to_stakeholder = "SELECT id FROM mail WHERE first_name = '$firstname' AND last_name = '$lastname' AND campaign_id= ".$campaign_id." ";
	
			$rs_to_stakeholder = mysqli_query($conn,$sql_to_stakeholder);
			$num_rows = mysqli_num_rows($rs_to_stakeholder);
			if($num_rows == 0){

				$sql= "INSERT INTO mail (campaign_id,first_name,last_name,email,unsubscribe,unsubscribe_date,created_on,created_by,updated_by) VALUES('$campaign_id','$firstname','$lastname','$email_encrypt','$unsubscribe','$unsubscribe_date','$created_on','$created_by','$updated_by')";
				if(mysqli_query($conn,$sql)){
					$mail_inserted++;
				}
			}else{
				
				$sql1 = "SELECT id FROM mail WHERE first_name= '$firstname' AND last_name = '$lastname' AND campaign_id= ".$campaign_id." ";
				$rs1 = mysqli_query($conn,$sql1);
				if(mysqli_num_rows($rs1) > 0){
					$data = mysqli_fetch_assoc($rs1);
					$id = $data["id"];
				
					$sql_update =  "UPDATE mail SET first_name = '$firstname', last_name = '$lastname', email = '$email_encrypt', unsubscribe = '$unsubscribe', unsubscribe_date = '$unsubscribe_date' WHERE id = '$id' ";
					if(mysqli_query($conn,$sql_update)){
						$mail_updated++;
					}
				}
			}
		/************** End Data Upload ***********************************/
			
	}
  }
    $c_id = urlencode(utility::app_crypt($_REQUEST['campaign_id'],'e'));
	$_SESSION['record_message_updated'] = "$mail_updated records updated sucessfully.";
    $_SESSION['info_message'] = "$mail_inserted records inserted sucessfully.";
	header("Location: index?page=bulk_import_csv&c_id=$c_id&campaign_id=$campaign_id");
	exit();
	
}


?>

<section class="content">
	<div class="row">
		<div class="col-lg-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			  <? if(isset($_SESSION['record_message_updated'])){ ?>
			  <div class="alert alert-warning alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['record_message_updated']; unset($_SESSION['record_message_updated']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<!-- general form elements -->
              <div class="box box-default">
			
			<section class="bulkuploadheader">
			  <h1 style="color:black">
				Bulk Upload
			  </h1>
			</section>
			
			<form id="bulkuploadform" method="post" name="update" action="" enctype="multipart/form-data">
			<div style="background-color: #f9f9f9;margin:0 auto;text-align:center;">
				<br /><br />
				<span style="color:#F44336;font-weight:bold;font-style:italic;padding-left:20px;">To bulk upload, please follow the below mentioned rules
					<br>1. The upload file should be in <span style='color:black;font-size:22px;text-transform:uppercase;'>"CSV"</span> file format.
					<br>2. The csv file should be like <a target="_blank" href="<?echo $config->siteURL;?>/images/mail_sample.csv">import_sample.csv</a></span>
					<br/><br/><br/>
					<div class="upload-btn-wrapper">
						<button class="btn btn-primary">Choose File</button>
						<input type="file" name="import_gsi" id="import_gsi">
						<input type="hidden" name="campaign_id" id="campaign_id" value="<?=$campaign_id;?>">
					</div>
					
					<br /><br /><br />
					<div style="display:none;"><input type="submit" name="importfile" id="importfile" value="import file"></div>
			</div>
			</form>
			<?php   
				/* if($user_inserted || $user_updated){
					echo '<div style="color:#F44336;text-align:center;padding:10px;">'.($user_inserted).' users has been inserted, '.($user_updated).' users has been updated and '.($user_skiped).' users has been skiped...</div>';
				} */
			?>
			</div>
		</div>
	</div>
</section>
<style>
.content-wrapper{
	min-height: 593px;
}

.bulkuploadheader{
	padding:16px;
	background: aliceblue;
    text-align: center;
}

.bulkuploadheader h1{
	color: #808080;
	font-weight: bold;
	padding: 0;
    margin: 0;
    font-size: 25px;
}

.upload-btn-wrapper {
  position: relative;
  overflow: hidden;
  display: inline-block;
}

.exportbtns {
  border: 2px solid gray;
  color: gray;
  background-color: white;
  padding: 8px 20px;
  border-radius: 8px;
  font-size: 20px;
  font-weight: bold;
}

.choosefilebtn{
	border: 1px solid #2196F3;
    color: #2196F3;
    background-color: transparent;
    padding: 6px 20px;
    border-radius: 0;
    font-size: 15px;
}

.upload-btn-wrapper input[type=file] {
  font-size: 100px;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
	$("#bulkuploadform").on("change","#import_gsi",function(){
		if(confirm("Do you want to upload the file.")){
			$("#importfile").trigger("click");
		}
	});
});     
</script>   
</script>   