<?php
ob_start();
$title = 'Email Campaign';
include '../templates/backend/members/header.php';
global $deltaLatch, $deltaChatter;
$deltaAllow = !empty($deltaLatch);
$deltaNote = !empty($deltaChatter) ? $deltaChatter : (isset($_SESSION['evp_gate_msg']) ? $_SESSION['evp_gate_msg'] : __('License not active'));
$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($deltaAllow): ?>
    <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 echo $deltaNote; ?></label>

  <?php endif; ?>
	
</div>

</div>
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<style>
	.quill-wrapper {
		width: 100%;
		margin-bottom: 1rem;
	}
	.quill-wrapper .ql-toolbar.ql-snow {
		border-radius: 0.25rem 0.25rem 0 0;
	}
	.quill-wrapper .ql-container.ql-snow {
		border-radius: 0 0 0.25rem 0.25rem;
		min-height: 320px;
	}
</style>

<?php if($deltaAllow){ ?>
<script>
$(function() {

		$("#campaign_form #create_camp").click(function() {
			var url = $('#campaign_form').attr('action');
			var formContext = $(this).closest("#campaign_form");
			var s_id =  formContext.find("#smtp_server").val(); 
			var c_from =  formContext.find('#smtp_server > option:checked').text(); 
			var c_list = formContext.find("select[name='pre_tags']").val();
			var c_sub = formContext.find("input[name='subject']").val();
			var editorInstance = window.quillEditor;
			var c_msg = editorInstance ? editorInstance.root.innerHTML : formContext.find("textarea[name='message']").val();             
			var c_unsub = formContext.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>
(function ($) {
	"use strict";
	$(function () {
		var textarea = $('#message');
		if (textarea.length && typeof Quill !== 'undefined') {
			textarea.hide();
			var wrapper = $('<div class="quill-wrapper"></div>');
			wrapper.insertAfter(textarea);
			var quillContainer = $('<div id="message-editor" class="quill-editor"></div>');
			wrapper.append(quillContainer);
			window.quillEditor = new Quill('#message-editor', {
				theme: 'snow',
				modules: {
					toolbar: [
						[{ header: [1, 2, 3, false] }],
						['bold', 'italic', 'underline'],
						[{ list: 'ordered' }, { list: 'bullet' }],
						['link'],
						['code-block']
					]
				}
			});
			var existingContent = textarea.val();
			if (existingContent) {
				window.quillEditor.root.innerHTML = existingContent;
			}
			$(document).on('submit', '#campaign_form', function () {
				textarea.val(window.quillEditor.root.innerHTML);
			});
		}
	});
})(jQuery);
</script>
<?php 
include '../templates/backend/members/footer.php'; ?>