<?php
$title = 'List Validation';

include '../templates/backend/members/header.php';

$user_id = $_SESSION['id'];

if(!empty($cc_data)){
	function cdata1($cc_data){
		$data = '';
		foreach($cc_data as $val){
			$data .= "var $val = 0;" . PHP_EOL;
		}
		return $data;
	}
	function cdata2($cc_data){
		$data = '';
		foreach($cc_data as $val){
			$data .= "$val = column_data.$val;" . PHP_EOL;
		}
		return $data;
	}
	function cdata3($cc_data){
		$data = '';
		foreach($cc_data as $val){
			$data .= "$val:$val," . PHP_EOL;
		}
		return $data;
	}
	$cdata1 = cdata1($cc_data);
	$cdata2 = cdata2($cc_data);
	$cdata3 = cdata3($cc_data);
}

?>

<!-- Page Heading -->
<div class="page-header">
<div class="pull-right">
	  <?php if( isset( $_SESSION['lic_chck'] ) && isset( $_SESSION['lic_err'] ) &&  $_SESSION['lic_err'] == false ){ ?>
	    <a href="#" id="add_list" data-toggle="modal" data-target="#addList" class="d-sm-inline-block btn btn-sm btn-primary shadow-sm"><?php _e('Add List');?></a>
	  <?php }else{ ?>
	    <button disabled class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><?php _e('Add List');?></button>
	  <?php } ?>

</div>
<div class="row">
	<div class="col-md-6 col-sm-12">
		<div class="title">
			<h4><?php _e($title);?></h4>
		</div>
		<nav aria-label="breadcrumb" role="navigation">
			<ol class="breadcrumb">
				<li class="breadcrumb-item"><a href="index.php"><?php _e('Dashboard');?></a></li>
				<li class="breadcrumb-item active" aria-current="page"><?php _e($title);?></li>
			</ol>
		</nav>
	</div>
</div>
</div>

<!-- Content Row -->
<?php

$email_info = "SELECT csv_file_name FROM evp_email_list WHERE user_id = '$user_id' GROUP BY csv_file_name ORDER BY csv_file_name DESC ";

$info = $db->select( $email_info );
 
$i = $c = 0;

while ( $result = $info->fetch_assoc() ) {
	
	$csv_file_name = $result['csv_file_name'];
	
	$task_check_status = false;
	
	$task_check_sql = "SELECT * FROM evp_task WHERE csv_name = '$csv_file_name' ";
	
	$task_check_read = $db->select( $task_check_sql );
	
	$task_count_check = mysqli_num_rows( $task_check_read );
    
    if ( $task_count_check > 0 ) $task_check_status = true; $c++;
    
	$csv_file_info = "SELECT * FROM evp_email_list_metadata e_mdata
							LEFT JOIN evp_task e_task
							ON e_mdata.csv_file_name=e_task.csv_name
						WHERE e_mdata.csv_file_name = '$csv_file_name' AND e_mdata.user_id = '$user_id'";
						
    $csv_info = $db->select( $csv_file_info );
    
    $csv_result = $csv_info->fetch_assoc();
    
    // $t_email = $csv_result['t_email'];
    
    $create_time = $csv_result['creation_date'];
    
    $completed_time = $csv_result['completed_date'];
    
    $count_valid = $csv_result['valid'];
    
    $count_invalid = $csv_result['invalid'];
    
    $count_catchall = $csv_result['catch_all'];
    
    $count_unknown = $csv_result['unknown'];
        
    $count_skipped = $csv_result['skipped'];
	
	$scan_status = $csv_result['scan_status'];
        
    $count_free = $csv_result['free_account'];
    
    $count_role = $csv_result['role_account'];
    
    $count_disposable = $csv_result['disposable'];
    
    $count_syntax = $csv_result['syntax_error'];
    
    $total_verify = $count_valid + $count_invalid + $count_catchall + $count_unknown + $count_skipped;
	
    $total_email =  $csv_result['total'];
    
    $task_status = $csv_result['status'];
	
    $check_inbox =  $csv_result['check_mailbox'];
    
    $count_not_verify = $total_email - $total_verify;

    $csv_name_ex = preg_replace( '/\\.[^.\\s]{3,4}$/', '', $csv_file_name );
    
    $verify_per_status = ceil( ( ( $total_verify ) / $total_email ) * 100 );
	
	$sql_user_list_valid = "SELECT email_status FROM evp_email_list elist
							INNER JOIN evp_email_list_metadata e_meta
								ON e_meta.csv_file_name = elist.csv_file_name
								WHERE elist.csv_file_name = '$csv_file_name' AND
									  elist.user_id = '$user_id' AND
									  e_meta.scan_status = 'completed'";
	
	$sql_user_list_read = $db->select($sql_user_list_valid);
	
	$sql_user_list_chk = mysqli_num_rows( $sql_user_list_read );	
?>

<div class="row scan_list" id="mega_bar_<?php echo $csv_name_ex; ?>">
   <div class="col-md-12">
    <div class="pd-20 card-box mb-30">
	 <div class="row">
	<!-- File - First Column -->
	<div class="col-md-12 col-lg-3">
	  <!-- Custom Text Color Utilities -->
	  <div class="card-box mt-4 mb-4">
	    <div class="card-header py-3">
	      <h6 class="m-0 font-weight-bold text-primary"><?php _e('File Name');?>: <span id="filename"><?php echo $csv_file_name; ?></span></h6>
	    </div>
	    <div class="card-body">
	      <p class="text-gray-800 pt-1 pb-3 m-0"><?php _e('Created');?>: <?php echo $create_time ?></p>
	    <button class="btn btn-outline-secondary" type="button" data-toggle="modal" data-target="#model_<?php echo $csv_name_ex; ?>"><?php _e('Download');?></button>
		
				<!--	<script src="<?php  // echo $cred_script_url;?>"></script>		-->			
					
				
<?php if ( $sql_user_list_chk > 0 ):
if($check_inbox == 'true'):
$diff_time = 0;
$time_now = time(); 
$unblock_check = strtotime($completed_time)+300;
$diff_time = floor(($unblock_check - $time_now)/60);
$disabled = 'true';
if($time_now > ($unblock_check)){$disabled = 'false';}
?>
<button class="btn btn-success check_inbox" type="button" title="<?php _e('Validate Mailbox');?>" data-target="<?php echo $csv_file_name; ?>"> 
<i class="icon-copy dw dw-email2"></i>
<input type="hidden" data-status="<?php echo $disabled?>" data-wtime="<?php echo $diff_time;?>" value="email_check" />
</button>
<?php endif; ?>
 
		<button class="btn btn-info" type="button" data-toggle="modal" data-target="#model_assign_<?php echo $csv_name_ex; ?>"><i class="icon-copy dw dw-list"></i></button>
		
		<?php endif; ?>

<!-- CSV Assign Segment -->
			
<div class="csv_assign modal fade" id="model_assign_<?php echo $csv_name_ex; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel"><?php _e('Assign A Tag');?></h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form id="tag_maker" action="#" method="post">
				<input type="text" name="filename" hidden value="<?php echo $csv_file_name; ?>">
				<input type="text" name="user_id" hidden value="<?php echo $user_id; ?>">
				
				
				
				<div class="modal-body row">
					<div class="col-sm-12">
						<div class="form-group">
						
						<div id="new_list"><a href="/#" class="news_list_btn" data-dismiss="modal"><?php _e('Create a New Tag?');?></a></div>
							
								<p><?php _e('or select an existing tag');?><p>	
						
        <select class="selectpicker pre_tags" data-live-search="true">
		        <option disabled selected value style="display:none;"><?php _e('Select Tag');?></option>
			<?php $check_tags = $db->select( "SELECT DISTINCT list_name FROM evp_tag_list WHERE user_id = '".$user_id."'" ); 
					while ($tags = mysqli_fetch_array($check_tags)) :
						$tag = $tags['list_name'];
					?>
          <option data-tokens="<?php echo $tag; ?>"><?php echo $tag; ?></option>
		  <?php endwhile; ?>
        </select>

<script>
$(function() {
	$("#tag_maker .news_list_btn").click(function() {
	var csv_name = 	$(this).closest("#tag_maker").find("input[name='filename']").val();
	var user_id = $(this).closest("#tag_maker").find("input[name='user_id']").val();
    Swal.fire({
        title: "<?php _e('Tag Name');?>",
		html: "<?php _e('type in a new tag name');?>",
        input: 'text',
        showCancelButton: true,
        confirmButtonText: '<?php _e('Add');?>',
        showLoaderOnConfirm: true,
		heightAuto: false,
        preConfirm: function(text) {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    $.ajax({
                        url: "../functions/tag_func.php",
                        type: 'POST',
                        data: {
							target_csv_name: csv_name,
							user_id: user_id,
                            list_name: text
                        },
						dataType: "json"
						   }).done(function (response) {
							swal.fire({
							title: "<?php _e('Complete');?>",
							showConfirmButton: true,
							type: "success",
						    html: '<?php _e('Scanned list added into newly created tag');?>',
							heightAuto: false
                            }).then(function() {
                                location.reload();
                            })
						  
					  }).fail(function () {
						swal.fire("<?php _e('Error');?>", "<?php _e('Cannot add blank name!');?>", 'error');
					  });				
                 
                }, 1000)
            })
        },
    })
    event.preventDefault();
});	
	
});
</script>

						</div>
					</div>
				</div>
				
				<div class="modal-footer">
					<button id="assign_tag" name="assign_tag" type="submit" class="btn btn-primary" disabled><?php _e('Assign Tag');?></button>
					<button id="clear_tag" name="clear_tag" type="button" class="btn btn-dark"><?php _e('Clear Tag');?></button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Close');?></button>
				</div>
<script>
$(function() {	
$('#tag_maker select.pre_tags').on('change', function() {
	var selected_tag = this.value;
	$(this).closest("#tag_maker").find('#assign_tag').prop("disabled", false);
$("#tag_maker #assign_tag").click(function() {
	var csv_name = 	$(this).closest("#tag_maker").find("input[name='filename']").val();
	var user_id = $(this).closest("#tag_maker").find("input[name='user_id']").val();
	    Swal.fire({
		title:"<?php _e('Are you sure?');?>",
        html: "<?php _e('You are applying');?> <span style='color:red;'>" +selected_tag+ "</span> <?php _e('tag for scanned');?> <span style='color:red;'>" +csv_name+ "</span>",
		showCancelButton: true,
        confirmButtonText: '<?php _e('Yes, I confirm!');?>',
        showLoaderOnConfirm: true,
		heightAuto: false,
        preConfirm: function() {
		return new Promise(function(resolve) {
		   setTimeout(function() {
						$.ajax({
							url: "../functions/tag_func.php",
							type: 'POST',
							data: {
								target_csv_name: csv_name,
								user_id: user_id,
								selected_tag_name: selected_tag
							},
							dataType: "json"
							   }).done(function (response) {
								swal.fire({
								title: "<?php _e('Complete');?>",
								showConfirmButton: true,
								heightAuto: false,
								type: "success",
								html: '<?php _e('Scanned list');?> <span style=color:red;>' +csv_name+ '</span> <?php _e('assigned in');?> <span style=color:red;>' +selected_tag+ '</span> <?php _e('tag');?>'
								}).then(function() {
									location.reload();
								})
							  
						  }).fail(function () {
							swal.fire("<?php _e('Error');?>", "<?php _e('Unable to assign on selected tag!');?>", 'error');
						  });				
					 
					}, 1000)
		});
	
	  },
    })
	event.preventDefault();
	});
	
});	
	

	$("#tag_maker #clear_tag").click(function() {
		var csv_name = 	$(this).closest("#tag_maker").find("input[name='filename']").val();
		var user_id = $(this).closest("#tag_maker").find("input[name='user_id']").val();
	//	var tag = $('#mega_bar_'+csv_name).find("input[name='tag_name']").val();
		var tag = $('#mega_bar_'+csv_name).find("span[class=tags]").text();
		
		Swal.fire({
		title:"Are you sure?", 
        html: "You want to remove <span style='color:red;'>" +tag+ "</span> tag for scanned <span style='color:red;'>" +csv_name+ "</span>",
		showCancelButton: true,
        confirmButtonText: 'Yes, I confirm!',
        showLoaderOnConfirm: true,
		heightAuto: false,
        preConfirm: function() {
		return new Promise(function(resolve) {
		   setTimeout(function() {
						$.ajax({
							url: "../functions/tag_func.php",
							type: 'POST',
							data: {
								target_csv_name: csv_name,
								user_id: user_id,
								clear_tag : tag
							},
							dataType: "json"
							   }).done(function (response) {
								swal.fire({
								title: "Complete",
								showConfirmButton: true,
								heightAuto: false,
								type: "success",
								html: 'Scanned list <span style=color:red;>' +csv_name+ '</span> Unassigned from <span style=color:red;>' +tag+ '</span> tag'
								}).then(function() {
									location.reload();
								})
							  
						  }).fail(function () {
							swal.fire("Error", "Unable to clear from selected tag!", 'error');
						  });				
					 
					}, 1000)
		});
	
	  },
    })
	event.preventDefault();
		
	});

	
});
</script>	
			</form>
		</div>

	</div>
</div>


		
	    <button class="file_delete_btn btn btn-danger" data-target = '<?php echo $csv_file_name; ?>'>
			<i class="icon-copy dw dw-delete-3"></i>
		</button>
	  
				  <?php $check_tags = $db->select( "SELECT * FROM evp_tag_list WHERE target_csv_name = '".$csv_file_name."' and user_id = '".$user_id."'" ); 
					if (!mysqli_num_rows($check_tags)) :
						// echo "No Tags found";
					else:
					?>
					<div class="assigned_tag"><span class="title"><?php _e('Assigned Tag');?>:</span> 
					<?php
						while ($tags = mysqli_fetch_array($check_tags)) :
											$tag = $tags['list_name']; 
											echo "<span class='tags'>".$tag."</span>";
										//	echo "<input type='text' name='tag_name' hidden value=".$tag.">";
						endwhile;
						?>
					</div>	
					<?php endif;  ?>


	    </div>
		

	  </div>
	</div>
	

	<!-- Result - Second Column -->
	<div class="col-lg-5">
	  <!-- Background Gradient Utilities -->
	  <div class="card-box mt-4 mb-4">
		  <div class="table-responsive">
		    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
		      <thead>
		        <tr>
		          <th align="center" colspan="2"><?php _e('Verified Result');?>
		            <?php if( $verify_per_status < 100 && $verify_per_status != 0 ){ ?>
		              <h6 class="d-inline-block float-right text-primary" id="per_count_<?php echo $csv_name_ex; ?>" ><?php echo $verify_per_status.'% ('.$total_verify.')';?></h6>
		            <?php }?>
		          </th>
		        </tr>
		        <tr>
		          <td>
		            <p><?php _e('Total');?> : <?php echo $csv_result['total'] ?></p>
		            <p><?php _e('Valid');?> : <span id="valid_<?php echo $csv_name_ex;?>"><?php echo $count_valid;?></span></p>
		            <p><?php _e('Invalid');?> : <span id="invalid_<?php echo $csv_name_ex;?>"><?php echo $count_invalid;?></span></p>
		            <p><?php _e('Catch All');?> : <span id="catchall_<?php echo $csv_name_ex;?>"><?php echo $count_catchall;?></span></p>
		            <p><?php _e('Unknown');?> : <span id="unknown_<?php echo $csv_name_ex;?>"><?php echo $count_unknown;?></span></p>
		          </td>
		          <td>
		            <p><?php _e('Skipped');?> :  <span id="skipped_<?php echo $csv_name_ex;?>"><?php echo $count_skipped;?></span></p>
		            <p><?php _e('Syntax Error');?> :  <span id="syntax_<?php echo $csv_name_ex;?>"><?php echo $count_syntax;?></span></p>
		            <p><?php _e('Disposable');?> :  <span id="disposable_<?php echo $csv_name_ex;?>"><?php echo $count_disposable;?></span></p>
		            <p><?php _e('Free Account');?> :  <span id="free_account_<?php echo $csv_name_ex;?>"><?php echo $count_free;?></span></p>
		            <p><?php _e('Role Account');?> :  <span id="role_account_<?php echo $csv_name_ex;?>"><?php echo $count_role;?></span></p>
		          </td>
		        </tr>
		      </thead>
		    </table>
		  </div>
		</div>
	</div>

	<!-- Chart - Third Column -->
	<div class="col-lg-4">
	
	<!-- Grayscale -->
	<?php
	    
	    if(( $count_not_verify != 0 ) || ($task_status == 'retry_emailsend')){
	      
	      if( $task_check_status ){ ?>
	        
	        <div class="preloader" style="display:block" id="preloader_<?php echo $csv_name_ex; ?>">
	          <div class="spinner-border text-info" role="status">
	            <span class="sr-only"><?php _e('Loading');?>...</span>
	          </div>
	          <div class="task-cancel-btn">
	            <button data-target='<?php echo $csv_file_name; ?>' type="button" class="btn btn-danger btn-sm task-cancel-btn" name="button"><?php _e('Cancel');?></button>
	          </div>
	        </div>
	        <button style="display:none;" id="cancel_<?php echo $csv_name_ex; ?>" class="btn btn-danger btn-icon-split verify_email">
	          <span class="text verify-btn" id="" data-target='<?php echo $csv_file_name; ?>'><?php _e('Verify');?></span>
	        </button>
	      
	      <?php } else { ?>
	        
	        <button class="btn btn-danger btn-icon-split verify_email" id="cancel_<?php echo $csv_name_ex; ?>">
	          <span class="text verify-btn" id="" data-target='<?php echo $csv_file_name; ?>'><?php _e('Verify');?></span>
	        </button>
	        <div class="preloader" id="preloader_<?php echo $csv_name_ex; ?>">
	          <div class="spinner-border text-info" role="status">
	            <span class="sr-only"><?php _e('Loading');?>...</span>
	          </div>
	          <div class="task-cancel-btn">
	            <button type="button" class="btn btn-danger btn-sm task-cancel-btn" data-target='<?php echo $csv_file_name; ?>' name="button"><?php _e('Cancel');?></button>
	          </div>
	        </div>
	      <?php } ?>
			<div class="card-body verify-chart" id='chart_<?php echo $csv_name_ex; ?>'>
				<div class="chart-pie pt-4 pb-2">
				  <canvas id='myChart_<?php echo $csv_name_ex; ?>'></canvas>
				  <canvas id='new_myChart_<?php echo $csv_name_ex; ?>'></canvas>
				</div>
			</div>
	    
<?php } elseif(($count_not_verify == 0) && ($task_check_status) && ($scan_status == 'processing')) { ?>

	        <div class="preloader" style="display:block" id="preloader_<?php echo $csv_name_ex; ?>">
	          <div class="spinner-border text-info" role="status">
	            <span class="sr-only"><?php _e('Loading');?>...</span>
	          </div>
	        </div>

<?php } else {  ?>
	    
	    <!-- Card Header - Dropdown -->

	    <!-- Card Body -->
	    <div style="display:block" class="card-body verify-chart" id='chart_<?php echo $csv_name_ex; ?>'>
	      <div class="chart-pie pt-4 pb-2">
	        <canvas class="cart_sizing" id='myChart_<?php echo $csv_name_ex; ?>'></canvas>
	        <canvas class="cart_sizing" id='new_myChart_<?php echo $csv_name_ex; ?>' style="display:none;"></canvas>
	      </div>
	    </div>
	    <?php } ?>

	    <script src="../assets/scripts/chart.js"></script>
	    
	    <script>
		    var ctx = document.getElementById('myChart_<?php echo $csv_name_ex; ?>').getContext('2d');
		    
		    var myChart = new Chart(ctx, {
		        type: 'doughnut',
		        data: {
		            labels: ['<?php _e('Valid');?>', '<?php _e('Invalid');?>', '<?php _e('Catch All');?>', '<?php _e('Unknown');?>'],
		            datasets: [{
		                label: '# of Votes',
		                data: [<?php echo $count_valid; ?>, <?php echo $count_invalid; ?>, <?php echo $count_catchall; ?>, <?php echo $count_unknown; ?>],
		                backgroundColor: ['#C6E377','#F16F6F','#75CAC3','#C0C0C0'],
		                borderColor: ['#C6E377','#F16F6F','#75CAC3','#C0C0C0'],
		                borderWidth: 1
		            }]
		        },
		        options: {
		          responsive: true,
		          legend:{
		            display:true,
		            position: 'bottom'
		          }
		        }
		    });
	    </script>
	
	</div>
	</div>
 </div>
 </div>
</div>

<?php if( $verify_per_status < 100 && $verify_per_status != 0 ){

	// check if user verifying status is running...
	$task_status_c = $db->select( "SELECT * FROM evp_task WHERE csv_name = '$csv_file_name' AND user_id = '$user_id' AND status = 'scanning'" );

	if ( mysqli_num_rows( $task_status_c ) > 0 ){ ?>

<script>

	$(document).ready(function(){
		
		var interval_<?php echo $c; ?> = null;
		
		interval_<?php echo $c; ?> = setInterval( updatepercent<?php echo $c; ?>, 5000 );
		
		function updatepercent<?php echo $c; ?>(){
			
			var csvfile_name_<?php echo $c; ?> = '<?php echo $csv_file_name; ?>';
			
			var csv_name_ex_<?php echo $c; ?> = '<?php echo $csv_name_ex; ?>';
			
			var user_id = "<?php echo $user_id?>";
			
			$.ajax({
				
				url: "../functions/<?php echo $percent_count_func; ?>",
				
				type: "post",

				data: { filename:csvfile_name_<?php echo $c; ?>, uid:user_id },
		        
		        success: function ( response_<?php echo $c; ?> ) {
		        	
		        	var obj_<?php echo $c;?> = jQuery.parseJSON( response_<?php echo $c; ?> );
		        	
		        	if( obj_<?php echo $c; ?>.percent == '100' ){
		        		
		        		clearInterval( interval_<?php echo $c; ?> );
		        		
		        		$('#per_count_<?php echo $csv_name_ex;?>').html('<h6 class="d-inline-block float-right text-success"><?php _e('Complete');?> <a href = "" class="text-primary"><?php _e('Refresh');?></a> </h6>');
		        	}else{
		        		
		        		$('#per_count_<?php echo $csv_name_ex;?>').html( obj_<?php echo $c; ?>.percent+'% (' + obj_<?php echo $c; ?>.total_verify + ') ' );
		        		
		        		if( obj_<?php echo $c; ?>.details !== 'undefined' ){

		        			$.each( obj_<?php echo $c; ?>.details, function() {
							  
								var key = Object.keys(this)[0];
								var value = this[key];

								try { $( '#' + key ).text( value ); } catch(e) { console.log( e ); }
							});
		        		}
		        	}
		        }
		    });
		}
	});

</script>

<?php }

} ?>




<!-- CSV Download Modal -->
<div class="csv_download modal fade" id="model_<?php echo $csv_name_ex; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalLabel"><?php _e('CSV Download');?></h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form action="../functions/<?php echo $download_file_func;?>" method="post">
				<input type="text" name="filename" hidden value="<?php echo $csv_file_name; ?>">
				<input type="text" name="user_id" hidden value="<?php echo $user_id; ?>">
				<div class="modal-body row">
					<div class="col-sm-6">
						<div class="form-group form-check">
							<input type="checkbox" name="all" class="form-check-input check_all_<?php echo $i?>" value="all" checked onchange="allChange<?php echo $i; ?>(this)" id="checkbox_<?php echo $c;?>" <?php if( $total_email == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('ALL');?> <span class="badge badge-primary"><?php echo $total_email; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="valid" value="valid" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c;?>" <?php if( $count_valid == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Deliverables');?> <span class="badge badge-success"><?php echo $count_valid; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="invalid" value="invalid" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c;?>" <?php if( $count_invalid == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Non Deliverables');?> <span class="badge badge-danger"><?php echo $count_invalid + $count_skipped; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="catchall" value="catchall" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c;?>" <?php if( $count_catchall == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Deliverables with Risk');?> <span class="badge badge-info"><?php echo $count_catchall; ?></span></label>
						</div>

					</div>
					<div class="col-sm-6">
						<div class="form-group form-check">
							<input type="checkbox" name="free" value="free" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>" <?php if($count_free == 0){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Free Account');?> <span class="badge badge-dark"><?php echo $count_free; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="role" value="role" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>" <?php if( $count_role == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Role Account');?> <span class="badge badge-light"><?php echo $count_role; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="disposable" value="disposable" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>" <?php if( $count_disposable == 0 ){ echo 'disabled'; } ?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Disposable Account');?> <span class="badge badge-secondary"><?php echo $count_disposable; ?></span></label>
						</div>
						<div class="form-group form-check">
							<input type="checkbox" name="syntax" value="syntax" class="form-check-input check_sub_<?php echo $i?>" onchange="cbChange<?php echo $i ; ?>(this)" id="checkbox_<?php echo ++$c; ?>" <?php if( $count_syntax == 0 ){ echo 'disabled' ;}?>>
							<label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('Syntex Error');?> <span class="badge badge-warning"><?php echo $count_syntax; ?></span></label>
						</div>
					</div>
				</div>
				<script>
					function cbChange<?php echo $i?>(obj){
						var cbs = document.getElementsByClassName("check_all_<?php echo $i?>");
						cbs[0].checked = false;
					}
					function allChange<?php echo $i?>(obj){
						var cbs = document.getElementsByClassName("check_sub_<?php echo $i?>");
						for (var i = 0; i < cbs.length; i++) {
							cbs[i].checked = false;
						}
					}
				</script>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Close');?></button>
					<button type="submit" class="btn btn-primary"><?php _e('Download');?></button>
				</div>
			</form>
		</div>
	</div>
</div>

<?php $i++; } ?>

<script>
    
$(document).ready(function(){

	$(".file_delete_btn").click(function(){
		
		var csvfile_name_d = $(this).attr("data-target");
		
		var user_id = "<?php echo $user_id?>";
		
		var delete_confirm = confirm("<?php _e('Are you sure?');?>");
		
		if ( delete_confirm ) {
			
			$.ajax({
				
				url: "../functions/<?php echo $delete_csv_file_func;?>",
				
				type: "post",
            
            data: { filename:csvfile_name_d, uid:user_id } ,
            
            success: function (response) {
            	
            	$( '#mega_bar_'+csvfile_name_d ).hide();
            }
        });
		}
	});
});

</script>

<?php if( isset( $_SESSION['lic_chck'] ) && isset( $_SESSION['lic_err'] ) &&  $_SESSION['lic_err'] == false ){ ?>

<script>
  
$(document).ready(function(){

	$(".task-cancel-btn").on('click', function(){

		var csvfile_name_t = $(this).attr("data-target");
		
		var user_id = "<?php echo $user_id?>";
		
		$.ajax({
			
			url: "../functions/<?php echo $task_cancel_func;?>",
			
			type: "post",
			
			data: { filename:csvfile_name_t, uid:user_id } ,
			
			success: function (response) { 
				
				$( '#preloader_'+csvfile_name_t ).css('display','none');
				
				$( '#cancel_'+csvfile_name_t ).css('display','block');
			}
		});
	});


    $(".verify-btn").click(function(){
		event.preventDefault();
      var from_mail = '<?php echo $scan_mail;?>';
      
      var time_out = '<?php echo (!empty($scan_timeout) ? $scan_timeout: 10);?>';
      
      var scan_port = '<?php echo (!empty($scan_port) ? $scan_port: 25);?>';
      
      if( from_mail.length == 0 ){
      
        alert('<?php _e('Please set time out and a from mail in settings page for continue scan');?>');
      
        return false;
      }
      var csvfile_name = $(this).attr("data-target");

      $('.preloader').each(function(index,node){
      
        if( $(node).attr('id') !== '#preloader_'+csvfile_name ){
      
          $('#'+$(node).attr('id')).css('display','none');
      
          $('#cancel_'+$(node).attr('id').replace('preloader_','')).css('display','block');
        }
      });

      var csv_name_ex = csvfile_name.replace(/\.[^/.]+$/, ""); 
      
      $(this).parents('.verify_email').hide();
      
      $('#preloader_'+csv_name_ex).css('display','block');
      
      var count_valid = parseInt($('#valid_'+csv_name_ex).html());
      
      var count_invalid = parseInt($('#invalid_'+csv_name_ex).html());
      
      var count_catchall = parseInt($('#catchall_'+csv_name_ex).html());
      
      var count_unknown = parseInt($('#unknown_'+csv_name_ex).html());
      
      var count_skipped = parseInt($('#skipped_'+csv_name_ex).html());
      
      var count_syntex = parseInt($('#syntax_'+csv_name_ex).html());
      
      var count_free = parseInt($('#free_account_'+csv_name_ex).html());
      
      var count_role = parseInt($('#role_account_'+csv_name_ex).html());
      
      var count_disponsable = parseInt($('#disposable_'+csv_name_ex).html());
      
      var user_id = "<?php echo $user_id?>";

      $.ajax({
            
            url: "../functions/<?php echo $emails_verify_func;?>",
            
            type: "post",
            
            data: { filename:csvfile_name, uid:user_id,frommail:from_mail,timeout:time_out,scan_port:scan_port },
            
            success: function (response) {

              window.location.reload( false );
			  
            }
        });

    });
});

</script>

<div class="modal fade" id="addList"  role="dialog">
  <div class="modal-dialog modal-lg">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h5><?php _e('Only CSV file can add');?></h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
       <ul class="nav nav-tabs" style="border-bottom: 0px;" id="myTab" role="tablist">
        <li class="nav-item">
          <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true"><i class="fas fa-file-upload"></i><?php _e('Upload');?></a>
        </li>
      </ul>
      <div class="tab-content" id="myTabContent">
        <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
		<div class="row" id="upload_area">
            <form method="post" id="upload_form2" enctype="multipart/form-data">
			  <div style="border: 1px solid #dddfeb;margin: 0 auto;text-align: center;padding: 150px;">
				  <input type="file" name="file" id="csv_filename">
          </div>
        	</form>
        </div>
        <div class="table-responsive" id="process_area"></div>        

          <p class="uplogin_file"><i class="start fas fa-circle-notch fa-spin"></i> &nbsp; <?php _e('File Uploading  total');?>- <span class="ml-2 text-primary" id="count_total_export"></span> </p>
          <div style="margin-top: 20px; " class="uploading_succes">
            <h3><?php _e('Thank you');?> - <?php _e('Your list has been uploaded successfully');?>.</h3>
            <p class="" id="store-status"> </p>
            <p><a href="<?php echo $my_list_page;?>"><?php _e('Refresh page');?></a></p>
          </div>
          <br>
        </div>
        <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
        </div>
        <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
        </div>
      </div>
      </div>
    </div>

  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){
	$(".uplogin_file").hide();

	$(".uploading_succes").hide();

  <?php echo $cdata1; ?>
  
  var email_name = 0;
  var user_id = <?php echo $_SESSION['id']; ?>;              
  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('<?php _e('You have already define');?> '+column_name+ ' <?php _e('column');?>');

      $(this).val('');
	  delete column_data[column_name];
	  
      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;
    console.log(column_data.email_name,total_selection);
    if(total_selection > 0 && column_data.email_name !=undefined)
    {
      $('#import').attr('disabled', false);

	<?php echo $cdata2; ?>

      email_name = column_data.email_name;
      // user_id = column_data.user_id;            
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });

  $(document).on('click', '#import', function(event){
			var get_check_mailbox = $(this).closest('#process_area').find("input[name='check_mailbox']").prop('checked');
			var ext = $("input#csv_filename").val().split(".").pop().toLowerCase();
			function randomNumberFromRange(min,max)
			{
				return Math.floor(Math.random()*(max-min+1)+min);
			}
			var fname = '<?php echo time() ;?>' +randomNumberFromRange(10,99)+'<?php echo $_SESSION['id']; ?>'+ '_csv_file';
			
			fname = fname.replace(/\s/g, "_");

    event.preventDefault();

    $.ajax({
			url: "../functions/<?php echo 'save_email.php';?>",			
      method:"POST",
      data:{filename:fname,<?php echo $cdata3; ?>email_name:email_name,check_mailbox:get_check_mailbox,uid:user_id},
      beforeSend:function(){
        $('#import').attr('disabled', 'disabled');
        $('#import').text('<?php _e('Importing');?>...');
      },
      success:function(data)
      {

      	// console.log(data);
        $('#import').attr('disabled', false);
        $('#import').text('<?php _e('Import');?>');
        $('#process_area').css('display', 'none');
        $('#upload_area').css('display', 'block');
        $('#upload_form2')[0].reset();
        $('#message').html("<div class='alert alert-success'>"+data+"</div>");

				var obj = jQuery.parseJSON(data);

				$('#store-status').html('<?php _e('Total');?>: <span class="text-primary">'+obj.total+'</span>  <?php _e('Save');?>: <span class="text-success">'+obj.save+'</span>  <?php _e('Duplicate');?>: <span class="text-danger">'+obj.duplicate+'</span> (<?php _e('duplicate emails has been removed from scan queue');?>)');
				$('#count_total_export').text('');
				$(".uplogin_file").hide();
				$("#myTab").hide();
				$("#upload_form2").hide();
				$(".uploading_succes").show();
				$("#filename").empty(" ");        
      }
    })

  });
  
});
</script>


<script>
$(function() {		 
$(".check_inbox").on('click', function() {
	 var disabled = $(this).find("input[type='hidden']").attr("data-status");
	 if(disabled == 'true'){
		var time_left = $(this).find("input[type='hidden']").attr("data-wtime");
		swal.fire({
				title: "<?php _e('Sorry, Not Yet!');?>",
				showConfirmButton: true,
				heightAuto: false,
				type: "caution",
				html: '<?php _e('You cannot start Mailbox Validation right now. At least wait');?> '+time_left+' <?php _e('more minutes. This cooldown assigned to get all return emails from undelivered addresses for higher validation accuracy before final validations.');?>'
				}).then((result) => {
				  location.reload();
				});
	 } else {
	  event.preventDefault();

      var csvfile_name = $(this).attr("data-target");

      var csv_name_ex = csvfile_name.replace(/\.[^/.]+$/, ""); 
      
      $(this).parents('.verify-chart').hide();
      
      $('#preloader_'+csv_name_ex).css('display','block');
      
      var inbox_check = $(this).find("input[type='hidden']").val();

      var user_id = "<?php echo $user_id?>";

      $.ajax({
            
            url: "../functions/email_verify.php",
            
            type: "post",
            
            data: {filename:csvfile_name,uid:user_id,inbox_check:inbox_check},
            
            success: function (response) {

				Swal.fire(
					"<?php _e('Inbox Getting Checked For This List!');?>",
					"<?php _e('Once inbox checking completes, you will receive a notification email with updated results. Check back after a few minutes!');?>",
					"success"
				).then((result) => {
				  location.reload();
				});
				// window.location.reload( false );
            }
        });
	 }
    });
});
</script>


<!-- add list script -->
<script>

	$(".uplogin_file").hide();
	
	$(".uploading_succes").hide();
	
	$(document).ready(function(){
		
		$("#csv_filename").change(function(e) {

			$('#store-status').html('');
			
			var ext = $("input#csv_filename").val().split(".").pop().toLowerCase();
			
			function randomNumberFromRange(min,max)
			{
				return Math.floor(Math.random()*(max-min+1)+min);
			}
			
			var fname = '<?php echo time() ;?>' +randomNumberFromRange(10,99)+'<?php echo $_SESSION['id']; ?>'+ '_csv_file';
			
			fname = fname.replace(/\s/g, "_");
			
			if( $.inArray( ext, ["csv"] ) == -1 ) {
				
				alert('Upload CSV');
				
				return false;
			}
			
			$(".uplogin_file").show();
			
			if ( e.target.files != undefined ) {
				
				var reader = new FileReader();
				
				reader.onload = function(e) {
					
					$(".uploading_succes").hide();
					
					$('#count_total_export').text('');
					
					var lines = e.target.result.split('\r\n');

					if ( lines.length == 1 ) {

						lines = e.target.result.split('\n');
					}

					var c = 0;

					var t = 0;

					var title_row = lines[0].split(',');

					var email_row_check = false;

					for ( r = 0; r < title_row.length; r++ )
					{
						var column_name = title_row[r].trim();

						column_name = title_row[r].toLowerCase();

						

							email_row_check = true;

							var target_column_index = r;

							break;
						
					}

					var data_array = '';

					if( email_row_check ){

						for ( i = 1; i < lines.length; ++i )
						{
							var email_column = lines[i].split(',');

							var email = email_column[target_column_index];

							if( email != '' ){

								email = $.trim(email);
							}

							if( email != '' ){

								t++;

								data_array  += email+',';

								$('#count_total_export').text(t);

								var user_id = '<?php echo $_SESSION['id']; ?>';
							}
						}
							 var formData = new FormData()
							 var file_obj = document.getElementById("csv_filename")
							  // $('#image')[0].files[0];
							formData.append('file', file_obj.files[0]);	
							formData.append('inbox_checker', '<?php echo $inbox_checker; ?>');
							<?php $cc_data = serialize($cc_data); ?>
							 formData.append('cc_data', '<?php echo $cc_data; ?>');	
							 // formData.append('file', fname);						
						// console.log(data_array.length);
						if( data_array.length !== 0 ){
							$.ajax({
						      url:"../functions/upload.php",
						      method:"POST",
						      data:formData,
						      dataType:'json',
						      contentType:false,
						      cache:false,
						      processData:false,
						      success:function(data)
						      {
						        if(data.error != '')
						        {
						          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
						        }
						        else
						        {
						          $('#process_area').html(data.output);
						          $('#upload_area').css('display', 'none');
						        }
								}
							});
							
						}else{

							$(".uplogin_file").hide();

							$("#filename").empty(" ");

							alert('<?php _e('No email column found');?>');
						}

					}
				};

				reader.readAsText( e.target.files.item(0) );
			}

			return false;
		});

	});
  
</script>
<?php } ?>

<?php include '../templates/backend/members/footer.php'; ?>