<?php
ob_start();
$title = 'Email Campaign';
include '../templates/backend/members/header.php';
$dates = new DateTime('now', new DateTimeZone('UTC') ); //php UTC timezone
$dates = $dates->format('Y-m-d H:i:s');
$user_id = $_SESSION['id'];
$c_user_id = '';
if($email_campaigns == 'false'){
	header("Location:$a_url");
	exit();
}
?>
<!-- Page Heading -->
<div class="page-header">
<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>

<div class="pd-20 card-box mb-30">
<div class="mb-4">
  <div class="row">
  <?php if(isset($_SESSION['lic_chck']) && isset($_SESSION['lic_err']) &&  $_SESSION['lic_err'] == false): ?>
    <div class="mb-3 col-md-6 pr-md-4">
	<h3 class="mb-4"><?php _e('Create A Campaign');?></h3>
		<div class="input-group">
			<form id="campaign_form" action="../functions/scripts/campaign/create_campaign_func.php" method="post">
					
				<div class="form-group row">
						  <label for="smtp_server" class="col-sm-3 col-form-label"><?php _e('SMTP Email Server');?></label>
				  <div class="col-sm-9">
								<select required id="smtp_server" name="smtp_server" class="selectpicker" data-live-search="true">
								  <option disabled selected value style="display:none;"><?php _e('Select Email Server');?></option>
									<?php $get_smtp_server = $db->select( "SELECT id, smtp_email FROM `evp_smtp_server_list` WHERE user_id = '".$user_id."'" ); 
											while ($server_list = mysqli_fetch_array($get_smtp_server)) :
												$smtp_id = $server_list['id'];
												$smtp_email = $server_list['smtp_email'];
											?>
								  <option data-tokens="<?php echo $smtp_email; ?>" value="<?php echo $smtp_id; ?>"><?php echo $smtp_email; ?></option>
								  <?php endwhile; ?>
								</select>
				  </div>
				</div>
					
				<div class="form-group row">
						  <label for="from" class="col-sm-3 col-form-label"><?php _e('List');?></label>
				  <div class="col-sm-9">
								<select required name="pre_tags" class="selectpicker" data-live-search="true">
										 <option disabled selected value style="display:none;"><?php _e('Select List');?></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>
				  </div>
				</div>
					
				<div class="form-group row">
						  <label for="subject" class="col-sm-3 col-form-label"><?php _e('Subject');?></label>
				  <div class="col-sm-9">
							<input type="text" class="form-control" name="subject" id="subject" placeholder="<?php _e('Subject');?>" required>
				  </div>
				</div>
						
				<div class="form-group row">
				 <label for="message" class="col-sm-3 col-form-label"><?php _e('Message');?></label>
				  <div class="col-sm-9">
							<textarea id="message" name="message" required></textarea>
				  </div>
				</div>
					
				<div class="form-group row">
				<label class="col-sm-4 col-form-label"><?php _e('Unsubscribe Link');?> <i class="icon-copy dw dw-question-1" data-container="body" data-toggle="tooltip" data-placement="top" data-original-title="<?php _e('Adds a Unsubscribe Link after message body');?>."></i></label>
				<div class="col-sm-8">
					<label class="btn_switch">
						<input type="checkbox" name="c_unsub" id="c_unsub" value="<?php echo $c_unsub;?>" <?php if($c_unsub == 'true'){echo 'checked';} ?> required>
						<span class="btn_slider round"></span>
					</label>
				</div>
			  </div>
					
					<button type="submit" class="btn btn-primary"  id="create_camp"><?php _e('Create');?></button>
			</form>
        </div>
    </div>
	
	
	 <div class="col-md-6 pl-md-4 pr-md-4">
      <h3 class="mb-4"><?php _e('Email Campaign List');?></h3>

    <div style="overflow-x:auto" class="">
    <table class="table table-sm">
      <thead class="thead-light">
        <tr>
          <th scope="col"><?php _e('id');?></th>
          <th scope="col"><?php _e('Name');?></th>
          <th scope="col"><?php _e('Sender');?></th>
          <th scope="col"><?php _e('Subject');?></th>
          <th scope="col"><?php _e('Sent');?></th>
          <th scope="col"><?php _e('Status');?></th>
          <th scope="col"><?php _e('Date');?></th>
          <th scope="col"><?php _e('Actions');?></th>
        </tr>
      </thead>
      <tbody>
        <?php
        $check_sql = $db->select("SELECT c_id, c_name, c_from, c_sub, total_sent, total_amount, c_status, c_date, c_user_id FROM evp_campaign_list WHERE c_user_id = '$user_id'");
        $rows = mysqli_num_rows($check_sql);
        if($rows > 0){
		$i = 0;	
          while ($row = $check_sql->fetch_assoc()) {
            $i++; ?>
            <tr>
              <th scope="row"><?php echo $i;?></th>
              <td><?php echo $row['c_name'];?></td>
              <td><?php echo $row['c_from'];?></td>
              <td><?php echo $row['c_sub'];?></td>
              <td align="center"><?php echo $row['total_sent'] . "/" . $row['total_amount'];?></td>
              <td align="center"><?php echo $row['c_status'];?></td>
              <td><?php echo $row['c_date'];?></td>
              <td>
			  
			   <form class="d-inline-block" action="../functions/scripts/campaign/campaign_func.php" method="post">
                  <input type="text" hidden id="target_id" name="target_id" value="<?php echo $row['c_id'] ;?>">
                  <input type="text" hidden id="user_id" name="user_id" value="<?php echo $row['c_user_id'] ;?>">
                  <?php if($row['c_status'] == 'pending'){?>
                    <button type="submit" name="start-btn" class="btn btn-sm btn-success" onclick="return confirm('<?php _e('do you want to start this campaign?');?>');"><?php _e('Start');?></button>
                  <?php }elseif($row['c_status'] == 'processing'){ ?>
                    <button type="submit" name="stop-btn" class="btn btn-sm btn-dark" onclick="return confirm('<?php _e('do you want to stop this running campaign?');?>');"><?php _e('Stop');?></button>
                  <?php }elseif($row['c_status'] == 'completed'){ ?>
                    <button type="submit" name="done-btn" class="btn btn-sm btn-dark"><?php _e('Completed');?></button>
                  <?php }?>
                  <button type="submit" name="del-btn" class="btn btn-sm btn-danger" onclick="return confirm('<?php _e('do you want to delete this user and all data?');?>');"><?php _e('Delete');?></button>
      </form>
			  
			  </td>
            </tr>
          <?php }
        }

        ?>
      </tbody>
    </table>
      </div>

    </div>
	
	
  </div>

  <?php else: ?>
  
	<label class="col-form-label d-block text-danger"><?php _e('Script icense not active!');?></label>

  <?php endif; ?>
	
</div>

</div>
<script src="../assets/ckeditor/ckeditor.js"></script>  <!-- ckeditor library call -->

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

		$("#campaign_form #create_camp").click(function() {
			var url = $('#campaign_form').attr('action');
			var s_id =  $(this).closest("#campaign_form").find("#smtp_server").val(); 
			var c_from =  $(this).closest("#campaign_form").find('#smtp_server > option:checked').text(); 
			var c_list = $(this).closest("#campaign_form").find("select[name='pre_tags']").val();
			var c_sub = $(this).closest("#campaign_form").find("input[name='subject']").val();
			var c_msg = CKEDITOR.instances['message'].getData();             
			var c_unsub = $(this).closest("#campaign_form").find("input[name='c_unsub']").prop('checked');

			Swal.fire({
			title:"<?php _e('Are you sure');?>?", 
			html: "<div cass='c_info'><?php _e('You are creating a scheduled campaign with these information');?>: <br></br> <p><span><?php _e('Sending By');?>: </span>"+c_from+"</p> <p><span><?php _e('Selected List');?>: </span>"+c_list+"</p> <p><span><?php _e('Your Subject');?>: </span>"+c_sub+"</p> </div>",
			showCancelButton: true,
			confirmButtonText: '<?php _e('Yes, I confirm!');?>',
			showLoaderOnConfirm: true,
			heightAuto: false,
			preConfirm: function() {
			return new Promise(function(resolve) {
			   setTimeout(function() {
							$.ajax({
								url: url,
								type: 'POST',
								data: {
									s_id: s_id,
									c_from: c_from,
									c_list: c_list,
									c_sub: c_sub,
									c_msg : c_msg,
									c_unsub : c_unsub
  									},
								dataType: "json"
								   }).done(function (response) {
									if(response['title'] === 'Success') {
										swal.fire({
										title: "<?php _e('Complete');?>",
										showConfirmButton: true,
										type: "success",
										html: '<?php _e('Campaign');?> '+c_list+' <?php _e('successfully created!');?>',
										heightAuto: false
										}).then(function() {
											location.reload();
									})
									} else if(response['title'] === 'Caution'){
										swal.fire({
										title: "<?php _e('Caution');?>",
										showConfirmButton: true,
										type: "info",
										html: '<?php _e('Campaign');?> '+c_list+' <?php _e('already exists!');?>',
										heightAuto: false
									})
									} else if(response['title'] === 'Error'){
										swal.fire({
										title: "<?php _e('Error');?>",
										showConfirmButton: true,
										type: "error",
										html: '<?php _e('Kindly fill up all required fields!');?>',
										heightAuto: false
  			})
									}
									   
							  }).fail(function () {
								swal.fire("<?php _e('Error');?>", "<?php _e('Ajax submission could not intialize!');?>", 'error');
							  });				
						 
						}, 1000)
			});
		
		  },
  	})
		event.preventDefault();
  });
	
});
</script>
<?php } ?>
<script>
  CKEDITOR.replace('message');
</script>
<?php 
include '../templates/backend/members/footer.php'; ?>