<?php
if(isset($_POST['btnLogout']))
{
	session_start();
	session_destroy();
} 
include('rights.php');
include('config.php');
include('includes/_admin_top.php');


?>

<div class="flex flex-col md:flex-row">
	<?php include('includes/_admin_menus.php') ?>

	<div class="main-content flex-1 bg-gray-100 md:mt-2 pb-24 md:pb-5">
            <div class="bg-blue-800 p-2 shadow text-xl text-white">
                <div class="d-table">
                	<div class="pull-left">
                	<h3 class="font-bold pl-2">Sticker Packs <small id="StickerPackId">()</small> </h3>
                </div>
                <div class="pull-right">
                	<a href="newpack.php" style="float:right;margin-left: 5px" class="btn btn-success"><i class="fa fa-plus-square" aria-hidden="true"></i> Create New</a>
                	<a href="stickerpack.php" style="float:right;" class="btn btn-success"><i class="fa fa-chevron-left" aria-hidden="true"></i> List</a>
                </div>
                </div>
            </div>

            <form id="newpackForm">
            	<div class="flex flex-wrap" id="stickerpackstable">
            		<div class="w-full col-md-12 p-3">
            			<div class="card">
            				<div class="card-body">
	            				<div class="form-group">
								    <label for="exampleInputEmail1">Sticker Pack Name</label>
								    <input type="text" class="form-control" id="StickerPackName" name="StickerPackName" placeholder="Big Emoji">
								    <input type="hidden" class="form-control" id="identifier" name="identifier" >
							  	</div>
							  	<div class="form-group">
								    <label for="exampleInputEmail1">publisher</label>
								    <input type="text" class="form-control" id="publisher" name="publisher" placeholder="StickerAdmin">
							  	</div>
							  	<div class="form-group" style="display:none">
								    <label for="exampleInputEmail1">Publisher Email</label>
								    <input type="Email" class="form-control" id="publisher_email" name="publisher_email" placeholder="StickerAdmin@mail.com">
							  	</div>
							  	<div class="form-group">
								    <label for="exampleInputEmail1">Signal Sticker Pack URL</label>
								    <input type="Website" class="form-control" id="publisher_website" name="SignalStickerPackURL" placeholder="https://signal.art/addstickers/#pack_id=63b631e382fa310af6d279b51574d7bb&pack_key=cf299d497d45ece302dedf92b67a13dc61d7e77f356beaf9444d6801ce99f089">
							  	</div>

								<div class="text-right">
 										<button type="button" class="btn btn-success" onclick="UpdateInfo()" > Update </button>
								</div>

            				</div>
            			</div>
            			<br>
            			
            			<div class="card">
            				<div class="card-body">
	            				<div class="row"> 
	            					<div class="col-md-10">
	            						<div class="form-group">
										    <label for="exampleInputEmail1">Select Stickers</label>
										    <input id='upload' name="upload[]" type="file" accept="image/png" multiple="multiple" />
									  	</div>
	            					</div>
	            				</div>
	            					
							  	<div style="width:100%;display:table;" id="imgArea"></div>
							  	<div id="hiddenArea"></div>
							  	<div id="removedArea"></div>
							  	
							  	<br>
							  	<div class="text-right">
 										<button type="button" class="btn btn-success" onclick="UpdateStickers()" > Update Stickers </button>
								</div>
            				</div>


            				
            			</div>

            		</div>
            	</div>
            </form>

        </div>
</div>

<?php  include('includes/_admin_bottom.php')?>

<script id="table-template" type="text/x-handlebars-template">

	<div class="stickerarea">
		{{#stickers}}
			<div class="card" style="width: 120px;margin:5px;float:left;">
				<img  class="previous_preview" style="padding:5px;margin:5px;width:100px" src="apis/userdata/{{../identifier}}/{{image_file}}.webp">
				<button  type="button" onclick="_removeSingle(this,{{@index}})" class="btn btn-danger btn-sm">Remove</button>
			</div>
		{{/stickers}}
	</div>

</script>

<script type="text/javascript">
	
	var _currentI=0;

function CalculateTotalStickers()
{
	return $('.previous_preview').length + $('.preview').length;	
}

function postSingle()
{
	$.ajax({
            type: "POST",
            data: {upload64:$($('.preview')[_currentI]).attr('src')},
            url: "apis/uploadSingleFile.php",
            success: function(data){
               console.log(data.trim())
			   $('#hiddenArea').append('<input type="hidden" name="upload64[]" value='+  data.trim() +'>');
			   $($('._row')[_currentI]).find('.status').text('Done');
			   
			   _currentI=_currentI+1;
			   	uploadAll();
                }
            });
}

function uploadAll()
	{
		if($('.preview').length >_currentI )
			{
				postSingle();
			}
			else
			{
				postForm()
			}
	}

function postForm()
{
	$.ajax({
	url:'apis/addpost.php',
	    method:'POST',
	   data:$('#newpackForm').serialize(),
	   success:function(){
		HoldOn.close();	   	
		ShowSuccess("Stickers Updated Successfully");
		_readData();
	   }
	})
}

function UpdateStickers()
{
	if(ValidateStickers()==true)
	{
		HoldOn.open({theme:'sk-rect'});
		uploadAll();
	}
}

	$(document).ready(function(){
		_readData();




$("#upload").change(function() {
				//$('#imgArea').html('');
				$('#hiddenArea').html('');
				var _totalSelectedImages=this.files.length;
	   var _currentFSIndex=0;
	   
				var names = [];
				
				for (var i = 0; i < $(this).get(0).files.length; ++i) {
					  var FR= new FileReader();
					
						
						FR.addEventListener("load", function(e) {
							var strim="";
							var _className="preview";
							IsOutOfSize=false;
							if(e.loaded / 1024 >= 100 )
							  {
								//IsOutOfSize=true;
								//_className="";
							  }

							  strim +='<div data-toggle="tooltip" data-placement="top" title="File size : '+ parseFloat(e.loaded / 1024).toFixed(1) +' kb "  IsOutOfSize="'+ IsOutOfSize +'" class="card sticker " style="width: 120px;margin:5px;float:left;">';
						  strim +='	<img class="'+_className+' card-img-top" style="padding:5px;margin:5px;width:100px" src="'+ e.target.result  +'" alt="Card image cap" />';
						  strim +='<button  type="button" onclick="_removeSingle(this)" class="btn btn-danger btn-sm">Remove</button>';
						  strim +='</div>';

						  $('.stickerarea').append(strim);

						  _currentFSIndex=_currentFSIndex+1;
						  if(_currentFSIndex==_totalSelectedImages)
						  {

						  }

						}); 
						
						var _strim="";
						FR.readAsDataURL( this.files[i] );
					
				}
				$("input[name=file]").val(names);
				$('#upload').val('');
			});

	});


	function _removeSingle(element,index)
	{
		if(index !=undefined)
		{
			$('#removedArea').append('<input type="hidden" name="removed[]" value='+  index +'>');	
		}
		$(element).parent().remove();
	}


	function _readData()
	{
		HoldOn.open({theme:'sk-rect'});
		$.ajax({
			url:'apis/alldata.php',
			success:function(data){
				var _stickerData=JSON.parse(data);
				var stickerPack=null;
				for(var i=0;i< _stickerData.sticker_packs.length;i++)
				{
					if( parseInt(_stickerData.sticker_packs[i].identifier)== parseInt(gup('id')) )
					{
						stickerPack=_stickerData.sticker_packs[i];
					}	    
				}
				console.log(stickerPack);

				$('#StickerPackName').val(stickerPack.name);
				$('#publisher').val(stickerPack.publisher);
				$('#publisher_email').val(stickerPack.publisher_email);
				$('#publisher_website').val(stickerPack.SignalStickerPackURL);
				$('#identifier').val(stickerPack.identifier);
				$('#StickerPackId').text("("+ stickerPack.identifier +")");
				
				var source = $("#table-template").html(); 
				var template = Handlebars.compile(source); 
				$('#imgArea').html(template(stickerPack));
				HoldOn.close();
			}
		})
	}


	function ValidateInfo()
	{
		if($("#StickerPackName").val()=="")
		{
			ShowError("Please enter Sticker Pack Name");
			return false;
		}
		if($("#publisher").val()=="")
		{
			ShowError("Please enter publisher");
			return false;
		}
		return true;	
	}

	function ValidateStickers()
	{
		if(CalculateTotalStickers() < 3)
		{
			ShowError("Minimum 3 Stickers are required in one Sticker Pack");
			return false;	
		}
		if( CalculateTotalStickers() > 30 )
		{
			ShowError("Maxximum 30 Stickers are Allowed in one Sticker Pack");
			return false;	
		}
		return true;
	}

	function UpdateInfo()
	{
		if(ValidateInfo()==true)
		{
			HoldOn.open({heme:'sk-rect'});
			$.ajax({
				//url:'apis/editpack.php?id='+$('#identifier').val()+'&name='+ $('#StickerPackName').val() +'&SignalStickerPackURL='+ $('#publisher_website').val() +'&publisher_website='+$('#publisher_website').val() +"&publisher="+$('#publisher').val(),
				url:'apis/editpack.php',
				method:'POST',
				data:$('#newpackForm').serialize(),
				success:function()
				{

					HoldOn.close();
					ShowSuccess("Updated Successfully");
				}
			});	
		}
	}

</script>