<?php
	require 'autoload.php';
	require 'PushNotifications.php';

	use Parse\ParseClient;
	use Parse\ParseObject;
	use Parse\ParseQuery;
	use Parse\ParseACL;
	use Parse\ParsePush;
	use Parse\ParseUser;
	use Parse\ParseInstallation;
	use Parse\ParseException;
	use Parse\ParseAnalytics;
	use Parse\ParseFile;
	use Parse\ParseCloud;
	
	include 'includes/func.php';
	include 'config.php';
	
	ParseClient::initialize($ApplicationID, $RestAPIKEY, $MasterKey);
	ParseClient::setServerURL($serverURLB4APP, '/');

	if(empty($_GET['uTp'])){
		header('Location: manage-ad.php');
	}
	$objID	=	$_GET['uTp'];

	$qury = new ParseQuery("ads");
	$result = $qury->get($objID);
	if(empty($result)){
		header('Location: manage-ad.php');
	}
	
	$title = $result->get("title");
	$details = $result->get("details");
	$notification_detail = $result->get("notification_detail");
	$start = date('m/d/Y H:i:s',strtotime($result->get("start_date")));
	$end = date('m/d/Y H:i:s',strtotime($result->get("end_date")));
	$pic = explode(',', $result->get("pic"));
	$giveUrl = $result->get("url");
	$button_title = $result->get("button_title");
	$url = url();
	$imgUrl = $url.'/uploads/'.$pic[0];
?>

<!DOCTYPE html>
<html lang="en">

<head>

	<title>Edit Ad Campaign</title>
	<?php include 'includes/head.php'; ?>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
    <style>
    	@media(max-width:500px){
    		div#mobile-background{
            	display:none;
    		}
    	}
    	div#backborder{
    		padding:0 auto;
        	height:800px;
		}
  		div#mobile-background {
        	text-align: center;			
			background-size: contain;
			background-repeat: no-repeat;
			width: 414Px;
			heigh:736px;
			-webkit-border-radius: 25px;
  			-moz-border-radius: 25px;
			background-radius: 25px;
			/*position: absolute;*/
			margin: 0 0px;		
			border:1px solid #DDD;
            margin:0 auto;			
		}
		div#background{
			-webkit-border-radius: 25px;
  			-moz-border-radius: 25px;
			background-radius: 25px;
			background-size: cover;
    		min-height: 100%;
    		background-position: center center;
			position: relative;
			background-image:url('<?php echo $imgUrl;?>');
		}
		div#background div#text {
  			padding-top:80px !important;
		}
		div#background a#bottom {
  			position: absolute;
			bottom: 20px;
			left:50%;
			transform: translateX(-50%);
		}
	</style>
</head>
<body>
    <div id="wrapper">
        <?php include 'includes/header.php';?>
        <div id="page-wrapper">

            <div class="container-fluid">
                <div class="row">
					<div class="col-lg-12">
                         <h1 class="page-header">
                            Edit Ad Campaign
							<a href="manage-ad.php" class="btn btn-danger pull-right">Go Back</a>
                        </h1>
						
							<?php
								if ( isset($_POST["btnAddAd"]) ) {

									$valid_formats = array('JPG',"jpg", "jpeg", "png", "gif", "zip", "bmp");
									$max_file_size = 1024*1024*10; //100 kb
									$path = "uploads/"; // Upload directory
									$count = 0;
									
										$filearray = array();
										// Loop $_FILES to execute all files										
										foreach ($_FILES['files']['name'] as $f => $name) {
											if ($_FILES['files']['error'][$f] == 4) {
												continue; // Skip file if any error found
											}       
                                        	
											if ($_FILES['files']['error'][$f] == 0) {	           
												if ($_FILES['files']['size'][$f] > $max_file_size) {
													$message[] = "$name is too large!.";
													continue; // Skip large files
												}elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
													$message[] = "$name is not a valid format";
													continue; // Skip invalid file formats
												}else{														
														$name1 = strtotime('now').rand(0,125);
														$ext = end(explode(".", $name));
														$target = $path.$name1.'.'.$ext;
														$pathforDb = $name1.'.'.$ext;
    													$tmp_name = $_FILES['files']["tmp_name"][$f];
														move_uploaded_file($tmp_name, $target);
														$filearray[] = $pathforDb;
												}
											}
										}                               
									$result->set( "title", $_POST["title"]);
									$result->set( "details", $_POST["details"]);
									$result->set( "button_title", $_POST["button_title"]);
									$start = date('y-m-d H:i:s',strtotime($_POST["start_date"]));
									$end = date('y-m-d H:i:s',strtotime($_POST["end_date"]));
									$result->set( "start_date", $start);
									$result->set( "end_date",$end);
                                	$result->set( "notification_detail",$_POST["notification_detail"]);
                                	if(!empty($_POST['url'])){
                                    	$result->set( "url",$_POST["url"]);
                                    }
									if(!empty($filearray)){
										$implode = implode(',',$filearray);
										$result->set( "pic",$implode);
									}
									$result->save();
                                	$pushObj = new PushNotifications();
                                    $id = $result->getObjectId();
                                	$detail = 'From: ' .date('d M-y',strtotime($_POST["start_date"])).' To: '.date('d M-y',strtotime($_POST["end_date"])); 
                                    $pushObj->android(array('mtitle'=>$_POST["title"],'mdesc'=>$detail,'id'=>$id));  
											?>
											
											<script>
								alertify.alert('Successfully saved', 'Ad has been edited successfully.!', function(){
									
									window.location = "manage-ad.php";
								});
							</script>
							<?php
							 } 
							?>
						
						<div class="panel panel-default">
						  <div class="panel-heading">Campaign Details</div>
						  <div class="panel-body">
								<div class="row">
									<div class="col-md-7">
										<form method="post" id="addNewad" enctype="multipart/form-data" >
										
											<div class="form-group">
												<label for="title" class="form-label">Ad Campaign & Push Notification Title</label>
												<input type="text" class="form-control" id="title" name="title" placeholder="Type ad Title"  required data-error-msg="Please enter ad Title" value="<?php echo $title; ?>"/>
											</div>
											<div class="form-group">
												<label for="title" class="form-label">Notification Description</label>
												<input type="text" class="form-control" id="notification_detail" maxlength="255" name="notification_detail" placeholder="Max 255 characters"  required data-error-msg="Please enter Notification Details max 255" value="<?php echo $notification_detail; ?>"/>
											</div>
                                                
											<div class="form-group">
												<label for="tDetails"  class="form-label">Ad Campaign Description</label>
												<textarea class="form-control" rows="6" id="Details" name="details" placeholder="Details" ><?php echo $details; ?></textarea>
											</div>
											
											<div class="form-group">
												<label for="button_title" class="form-label">Button Title</label>
												<input type="text" class="form-control" id="btn_text" name="button_title"  value="<?php echo $button_title; ?>" placeholder="Type button title" />
											</div>
                                            <div class="form-group">
												<label for="url" class="form-label">Target URL</label>
												<input type="text" class="form-control" id="url" name="url" value="<?php echo $giveUrl; ?>" placeholder="Type url" />
											</div>
											<div class="form-group">
												<label  class="form-label">Upload Background Image <small style="font-weight:normal">( Ratio 9:16 ) </small> </label>
												<input type="file" name="files[]" accept="image/*" id="uploadImage">
											</div>										
											<div class="form-group">
												<label  class="form-label">Start Date <small style="font-weight: normal;padding-left: 10px;color: red;"><span class="glyphicon glyphicon-info-sign"></span>Auto broadcasts ad with in this date range, to rebroadcast change date range</small></label>
												<div class='input-group date' id='datetimepicker'>
				                                    <input type='text' id="start_data" name="start_date" class="form-control search"  value="<?php echo $start; ?>" />
				                                    <span class="input-group-addon">
				                                        <span class="glyphicon glyphicon-calendar"></span>
				                                    </span>
				                                </div>
											</div>
											<div class="form-group">
												<label  class="form-label">End Date</label>
												<div class='input-group date' id='datetimepicker1'>
				                                    <input type='text'  value="<?php echo $end; ?>" id="end_date" name="end_date" class="form-control search" />
				                                    <span class="input-group-addon">
				                                        <span class="glyphicon glyphicon-calendar"></span>
				                                    </span>
				                                </div>
											</div>
											<div class="form-group">
												<input type="submit"  class="btn btn-success" name="btnAddAd" value="Save" />
												<input type="reset" class="btn btn-info" id="resetBtn" />
											</div>
										</form>
									</div>
                                     <div class="col-md-5" id="backborder" style="padding:0px 0px;">
                            			<div id="mobile-background" style="height:736px !important">
                                        	<div id="background">                                            	
                                            	<div id="text"  style="background-color:tranparent;"><?php echo $details; ?></div>
                                                <a id="bottom" class="btn btn-primary" href="#"><b><?php echo $button_title; ?></b></a>
                                        	</div>   
                            			</div>
                                   </div>               
								</div>
						  </div>
						</div>
                    </div>
                </div>
                <!-- /.row -->
            </div>
            <!-- /.container-fluid -->
        </div>
        <!-- /#page-wrapper -->
    </div>
    <!-- /#wrapper -->
   <?php include 'includes/footer.php'; ?>  
   	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>    
 	<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.css" rel="stylesheet">
	<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.js"></script>
   
   	<script type="text/javascript"> 
   	
      $(document).ready(function(){
   
   		
       $('#Details').summernote({
        	toolbar: [
              ['style', ['style']],
              ['font', ['bold', 'underline', 'clear']],
              ['fontsize', ['fontsize']],
              ['fontname', ['fontname']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['table', ['table']],              
              ['view', ['fullscreen', 'codeview']]
          ],
		tooltip:false, 
		});
   		
   		$('#Details').on('summernote.blur', function(){        	
 			$('#text').html($('#Details').summernote('code'));
		});
   		$('#btn_text').on("change", function(){
        	$('#bottom').html('<b>'+$('#btn_text').val()+'</b>');
        });
      	$("#uploadImage").on("change", function(){
   			var files = !!this.files ? this.files : [];
    		if ( !files.length || !window.FileReader ) return;
    		if ( /^image/.test( files[0].type ) ) {
        		var reader = new FileReader();
        		reader.readAsDataURL( files[0] );
        		reader.onloadend = function(){
            		$("#background").css("background-image", "url(" + this.result + ")");
        		}
    		}
		});
   
   
        $('#addClientDetails').attrvalidate();
        $('#resetBtn').click(function(){ 
			$('#addNewad').attrvalidate('reset'); 
		});
		$('#datetimepicker,#datetimepicker1').datetimepicker({
                useCurrent: false
            });
        $('#datetimepicker').datetimepicker().on('dp.change', function (e) {
            var incrementDay = moment(new Date(e.date));
            //incrementDay.add(365, 'days');
            $('#datetimepicker1').data('DateTimePicker').minDate(incrementDay);
            $(this).data("DateTimePicker").hide();
        });

        $('#datetimepicker1').datetimepicker().on('dp.change', function (e) {
            var decrementDay = moment(new Date(e.date));
            //decrementDay.subtract(365, 'days');
            $('#datetimepicker').data('DateTimePicker').maxDate(decrementDay);
            $(this).data("DateTimePicker").hide();
        });

      });
    </script>
</body>
</html>