var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

$('.datum-input').datepicker({ dateFormat: 'yy-mm-dd' });

function compareTime(time1, time2) {
    return new Date(time1) < new Date(time2); // true if time1 is later
}

function showMsg(elid, txt, elClass) {
	$(elid).html(txt);
	$(elid).show();
	$(elid).removeClass();
	$(elid).addClass(elClass);
}

function copyText(el) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(el).html()).select();
  document.execCommand("copy");
  $temp.remove();
}

$("#frm_client_details").submit(function(e){
        e.preventDefault();
    });

function updateInpMess(client_id) {
	$.ajax({ 
		'url':'ajax/update-inp-mess.php', 
		'type':'POST', 
		'data': {post_client_id: client_id, post_agent: $('select[id=agent'+client_id+'] option:selected').val()},
		'success':function(retData) { 
			// success 
			if (retData == "true" || retData == "false") {
				$("#tr"+client_id).remove();
			} else {
				alert(retData);
			}
		}, 
		'error':function(e) { 
			//failed 
			alert("Failed updateInpMess");
		} 
	}); 
	//alert($('select[id=agent'+client_id+'] option:selected').val());
	
	getGroupedMessages();
		
}

function updateClientStatus(client_id, trID) {
	$.ajax({
		'url':'ajax/update-client-status.php', 
		'type':'POST', 
		'data': {post_client_id: client_id, 'status': $('select[id=client_ST'+client_id+'] option:selected').val()},
		'success':function(retData) { 
			// success 
			if (retData == "true" || retData == "false") {
				switch($('select[id=client_ST'+client_id+'] option:selected').val()) {
					case "0":
						$("#"+trID).removeClass("table-danger");
						$("#"+trID).removeClass("table-warning");
					break;
					case "1":
						$("#"+trID).removeClass("table-danger").addClass("table-warning"); 
					break;
					case "2":
						$("#"+trID).removeClass("table-warning").addClass("table-danger"); 
					break;
				}
				//$("#tr"+client_id).remove();
			} else {
				alert(retData);
			}
		}, 
		'error':function(e) { 
			//failed 
			alert("Failed updateClientStatus");
		} 
	}); 
	//alert($('select[id=agent'+client_id+'] option:selected').val());
		
}

$('#someScrollingDiv').on('scroll', function() {
    let div = $(this).get(0);
    if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
        // do the lazy loading here
    }
});

function isChatHovered() {
	var isHovered = $('.chat-history').filter(function() {
        return $(this).is(":hover");
    });

    if ( isHovered.length > 0 ) {
      return true;
    } else { 
	  return false;
    }
}

function getClientDetails(id) {
	$.getJSON( "ajax/get-client-details.php?id="+id, function( data ) {
		$("#client_number").val(data.client_number);
		$("#client_name").val(data.client_name);
		$("#client_date").val(data.client_date);
		$('#client_ag option[value='+data.ag+']').attr("selected", "selected");
		$("#client_description").val(data.description);
		$("#client_last_edited").html(data.last_edited);
		$("#client_id").val(data.client_id);
		$("#sum_blk").html(data.blk);
		$("#sum_tot_received").html(data.tot_received);
		$("#sum_24h").html(data.sum_24h);
		if (data.premium == "1") {
			$('#premium').prop('checked', true);
		} else {
			$('#premium').prop('checked', false);
		}
	});
}

function getMainChat(id, callback, from_record, reverse) {
	
	$("#div_main_chat_show_more").show();
	$("#btn_main_chat_showmore").data("clientid", id);
	
	$.getJSON( "ajax/get-main-chat.php?id="+id+"&from_record="+from_record, function( data ) {
		
	  $.each( data, function( key, val ) {
		  
		  var isLastElement = key == data.length -1;
		  
		  if ($("#li"+val.mess_id).length == 0) {
			  
			  var textEnd = "";
			  var classEnd = "my-message";
			  if (val.mess_whosent == "1") {
				  textEnd = "text-end";
				  classEnd = "other-message float-right";
			  }
			  
			  if (reverse == true) {
			  
					  $("<li class='clearfix' id='li"+val.mess_id+"'><div class='message-data "+textEnd+"'><span class='message-data-time'>"+val.mess_dateReadable+"</span></div><div class='message "+classEnd+"'><button class='btn btn-copy'><i class='far fa-copy'></i></button><span>"+val.mess_message+"</span> <i class='fas fa-check'></i></div></li>").prependTo("#ul-mainChat").ready(function() {
						  /*if (callback == true) {
							  $(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
						  }*/
						  if (isLastElement) { 
							countCurrentMainChatMessages();
						  }
					});
			  } else {
				  
					  $("<li class='clearfix' id='li"+val.mess_id+"'><div class='message-data "+textEnd+"'><span class='message-data-time'>"+val.mess_dateReadable+"</span></div><div class='message "+classEnd+"'><button class='btn btn-copy'><i class='far fa-copy'></i></button><span>"+val.mess_message+"</span> <i class='fas fa-check'></i></div></li>").appendTo("#ul-mainChat").ready(function() {
						  /*if (callback == true) {
							  $(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
						  }*/
						  
						  if (isLastElement) { 
							countCurrentMainChatMessages();
							if(!isChatHovered()) {
								
								$(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
							}
						  }
					});
					
					
			  }
		  }
	  });
	  
	});
	
	
	
	//$(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
}

function countCurrentMainChatMessages() {
	var n = $("#ul-mainChat li").length;
	
	$("#current_main_chat_grouped").html(n);
	$("#btn_main_chat_showmore").data("from", n);
	
	var clientID = $("#inp_reply_clientID").val();
	
	
	$.ajax({
		'url':'ajax/get-sum-main-chat-messages.php?client_id='+clientID, 
		'type':'GET', 
		'success':function(retData) { 
			// success 
			$("#total_main_chat_grouped").html(retData);
		}, 
		'error':function(e) { 
			//failed 
			alert("Error while fetching total numbers");
		} 
	});
}

$( "#btn_main_chat_showmore" ).on( "click", function() {
  getMainChat($(this).data("clientid"),false,$(this).data("from"),true);
});

function updateClientDetails() {
	$.ajax({
		'url':'ajax/update-client-details.php', 
		'type':'POST', 
		'data': $("#frm_client_details").serialize(),
		'success':function(retData) { 
			// success 
			if (retData == "true") {
				getClientDetails($("#client_id").val());
			} else {
				alert(retData);
			}
		}, 
		'error':function(e) { 
			//failed 
			alert("Failed updateClientDetails");
		} 
	});
}

function sendBlk() {
	$("#sp_blk_send").empty();
	var date_from = Date.parse($("#blk_date_from").val());
	var date_to = Date.parse($("#blk_date_to").val());
	var selected_option = $('select[name=blk_sel_option] option:selected').val();
	if (isNaN(date_from) == true && (selected_option == "0" || selected_option == "1")) {
		alert("Datum od incorrect value");
	} else if (isNaN(date_to) == true && (selected_option == "0" || selected_option == "1")) {
		alert("Datum do incorrect value");
	} else if (!compareTime(date_from, date_to) && (selected_option == "0" || selected_option == "1")) {
		alert("Datum od do incorrect");
	} else if (!$.trim($("#blk_message").val())) {
		alert("Unesite poruku");
	} else {
		$.ajax({
			'url':'ajax/input-bulk-send.php?ag='+current_ag,
			'type':'POST',
			'data':$("#frm_bulk").serialize(),
			'dataType':'json',
			'success':function(retData) {
				if(retData.send == "false") {
					alert(retData.reason);
				} else if (retData.send == "true") {
					$("#sp_blk_send").html(retData.reason);
				} else {
					alert(retData);
				}
			},
			'error':function(e) {
				alert("Failed sendblk");
			}
		});
	}
}