// new input numbers
$(document).ready(function() {
	reloadAgents();
	reloadGroupedMessages();
	reloadErrorMessages();
	setInterval(reloadAgents, 5000);
	setInterval(reloadGroupedMessages, 5000);
	setInterval(getGroupedMessages, 5000);
	setInterval(reloadInactive, 5000);
	setInterval(reloadErrorMessages, 10000);
	
	$(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
	
	// new input messages
	
	$.getJSON( "ajax/get-new-numbers.php", function( data ) {
		var items = [];
		
		var subitems_agents = [];
		$.each(cf_agents, function(key,value) {
			subitems_agents.push("<option value='" + value + "'>" + value + "</option>");
		});
		
		
		$.each( data, function( key, val ) {
			
			if (val.init_message == null) {
				val.init_message = "";
			} 
			
			if (val.init_message.length > cf_howlongstrings ) {
				var init_message_short = val.init_message.slice(0,cf_howlongstrings);
			} else {
				var init_message_short = val.init_message;
			}
			
			items.push("<tr id='tr" + val.client_id + "' data-id=" + val.client_id + "><th scope='row' data-bs-toggle='tooltip' data-bs-placement='top' title='" + val.init_message + "'>" + init_message_short + "</th><td>" + val.client_number + "</td><td><form name='dodaj' method='post'><select name='agent' id='agent" + val.client_id + "'>" + subitems_agents.join("") + "</select><button class='btn btn-outline-secondary btn-sm' type='button' style='vertical-align: baseline;' onclick='updateInpMess(" + val.client_id + ");'>+</button></form></td></tr>");
			
		});
		
		$("#new_numbers").html(items.join(""));
	});
	
	var handlingInterval = null;
	$("#tbody_groupedMessages, #inactive").on('click', 'tr td:nth-child(2), tr th', function(param, callback) {
		$("#ul-mainChat").empty();
		var tbody_GM_ClientID = $(this).parent().data("id");
		getClientDetails(tbody_GM_ClientID);
		getMainChat(tbody_GM_ClientID, true);
		
		clearInterval(handlingInterval);
		handlingInterval = setInterval(function() { getMainChat(tbody_GM_ClientID); }, 5000);
		$(".chat-history").scrollTop($(".chat-history")[0].scrollHeight);
		//getMainChat($(this).parent().data("id"));
		showReplyForm($(this).parent().data("id"));
		$(this).parent().addClass('highlight').siblings().removeClass('highlight');        
        //get <td> element values here!!??
		
    });
	
	$('#ul-mainChat').on('click', '.btn-copy', function(){
    // do something here
		copyText($(this).next());
	});
	
	$('#btn_send_blk').on('click', function() {
		sendBlk();
	});
	
	$('#btn_inp_rnd').on('click', function() {
		$("#blk_message").val(randomNumber(14));
	});
	
	$('#outbox_numbers').on('click', 'button.error_btn_delete', function() {
		deleteMsg($(this).data("id"));
	});
	
	$('#outbox_numbers').on('click', 'button.error_btn_resend', function() {
		resendMsg($(this).data("id"));
	});
	
	$('#frm_bulk').on('keyup change paste', 'input, select, textarea, checkbox', function(){
		$("#sp_blk_send").empty();
	});
	
	$("select.sel_status_css").on('change', function() {
		updateClientStatus($(this).data("id"), $(this).parents('tr').attr('id'));
		//alert($(this).parents('tr').attr('id'));
	});
	//alert($('select[class=form-select1] option:selected').val())
	
});

function randomNumber(length) {
    var text = "";
    var possible = "123456789";
    for (var i = 0; i < length; i++) {
      var sup = Math.floor(Math.random() * possible.length);
      text += i > 0 && sup == i ? "0" : possible.charAt(sup);
    }
    return Number(text);
}

function deleteMsg(id) {
	if(confirm("Are you sure?")) {
        $.ajax({
			'url':'ajax/delete-message.php',
			'type':'POST',
			'data':{ "id": id},
			'success':function(retData) {
				if($.trim(retData) == "false") {
					alert("Error");
				} else if ($.trim(retData) == "true") {
					// delete this element
					$("#trerror"+id).remove();
				} else {
					alert(retData);
				}
			},
			'error':function(e) {
				alert("Failed deleteMsg");
			}
		});
    } else {
        e.preventDefault();
    }
}

function resendMsg(id) {
	$("#trerror"+id).remove();
	$.ajax({
		'url':'ajax/resend-message.php', 
		'type':'POST', 
		'data':{ "id": id},
		'success':function(retData) { 
			// success 
			if ($.trim(retData) == "true") {
				
			} else {
				
			}
		}, 
		'error':function(e) { 
			//failed 
			alert("Failed resendMsg");
		} 
	});
}

function showReplyForm(id) {
	$("#div_reply").show();
	$("#inp_reply_clientID").val(id);
	$("#inp_rnd_clientID").val(id);	
}

$('#txta_reply').keydown(function (e) {
	if (e.keyCode == 13) {
		if (!$.trim($("#txta_reply").val())) {
			alert("Unesite odgovor!");
		} else {
			$.ajax({
				'url':'ajax/input-reply.php?ag='+current_ag, 
				'type':'POST', 
				'data': $("#frm_reply").serialize(),
				'success':function(retData) { 
					// success 
					if ($.trim(retData) == "true") {
						$("#txta_reply").val('');
						// reload main chat for new messages!!!!!
						//getClientDetails($("#client_id").val());
					} else {
						alert(retData);
					}
				}, 
				'error':function(e) { 
					//failed 
					alert("Failed input-reply");
				} 
			});
		}
	}
});

$("#frm_rnd").on('click', '#btn_rnd', function () {
	$.ajax({
		'url':'ajax/input-rnd-send.php?ag='+current_ag,
		'type':'POST',
		'data': $("#frm_rnd").serialize(),
		'dataType':'json',
		'success':function(retData) { 
			// success 
			if(retData.send == "false") {
				alert(retData.reason);
			}
			/*
			if ($.trim(retData) == "true") {
				$("#txta_reply").val('');
				
			} else {
				
			}*/
		}, 
		'error':function(e) { 
			//failed 
			alert("Failed input-rnd-send");
		} 
	});
});


// Set interval for new messages
setInterval(function () {
	
	
	// new input messages left up
	$.getJSON( "ajax/get-new-numbers.php", function( data ) {
	  var items = [];
	  
	  // check each element!!!
	  $("#new_numbers tr").each(function (index) {
		  
		  var data_filter = data.filter( element => element.client_id == $(this).attr("data-id"));
		  if (data_filter.length > 0) {
			  
		  } else {
			  $(this).remove();
		  }
		  
		  /*
		  alert($(this).attr("data-id"));
		  
		  if (data.filter(element => element.client_id === $(this).attr("data-id")).length > 0) {
			  alert("postoji");
		  } else {
			  alert("ne postoji");
		  }*/
		  
		  
	  });
	  
	  var subitems_agents = [];
		$.each(cf_agents, function(key,value) {
			subitems_agents.push("<option value='" + value + "'>" + value + "</option>");
		});
		
		
	  $.each( data, function( key, val ) {
		  
		  if (val.init_message == null) {
				val.init_message = "";
			} 
			
			if (val.init_message.length > cf_howlongstrings ) {
				var init_message_short = val.init_message.slice(0,cf_howlongstrings);
			} else {
				var init_message_short = val.init_message;
			}
			
		  // if element does not exists?
		  if ($("#tr"+val.client_id).length == 0) {
			  $("<tr id='tr" + val.client_id + "' data-id=" + val.client_id + "><th scope='row' data-bs-toggle='tooltip' data-bs-placement='top' title='" + val.init_message + "'>" + init_message_short + "</th><td>" + val.client_number + "</td><td><form name='dodaj' method='post'><select name='agent' id='agent" + val.client_id + "'>" + subitems_agents.join("") + "</select><button class='btn btn-outline-secondary btn-sm' type='button' style='vertical-align: baseline;' onclick='updateInpMess(" + val.client_id + ");'>+</button></form></td></tr>").appendTo("#new_numbers");
		  }
		//items.push( "<li id='" + key + "'>" + val + "</li>" );
	  });
	 
	  
	});
	
	
	// new grouped messages center up
	
}, 10000);

function reloadInactive() {
	$.getJSON( "ajax/get-inactive.php?ag="+current_ag, function( data ) {
		
		$("#inactive tr").each(function (index) {
		  
		  var data_filter = data.filter( element => element.client_id == $(this).attr("data-id"));
		  if (data_filter.length > 0) {
			  
		  } else {
			  $(this).remove();
		  }		  
		  
		});
		
		
		$.each( data, function( key, val ) {
			
		  // if element does not exist?
		  if ($("#tr"+val.client_id).length == 0) {
			  $("<tr id='tr" + val.client_id + "' data-id=" + val.client_id + "><th scope='row' data-bs-toggle='tooltip' data-bs-placement='top'>" + val.client_number + "</th></td></tr>").appendTo("#inactive");
		  }
		//items.push( "<li id='" + key + "'>" + val + "</li>" );
		});
		
	});
}

function reloadErrorMessages() {
	$.getJSON( "ajax/get-error-messages.php?ag="+current_ag, function( data ) {
		
		$("#outbox_numbers tr").each(function (index) {
		  
		  var data_filter = data.filter( element => element.client_id == $(this).attr("data-id"));
		  if (data_filter.length > 0) {
			  
		  } else {
			  $(this).remove();
		  }		  
		  
		});
		
		
		$.each( data, function( key, val ) {
			
		  // if element does not exist?
		  if ($("#trerror"+val.mess_id).length == 0) {
			  $("<tr id='trerror" + val.mess_id + "' data-id='"+val.mess_id+"'><th scope='row' data-bs-toggle='tooltip' data-bs-placement='top' title='" + val.mess_message + "' ><i class='fa fa-duotone fa-circle-exclamation' style='color:red;'></i> "+val.shorten_message+"...</th><td>"+val.client_number+"</td><td><form method='post' style='display:inline;'><div class='btn-toolbar' role='toolbar'><div class='btn-group mr-2' role='group'><button class='btn btn-outline-secondary btn-sm error_btn_resend' type='button' data-id='"+val.mess_id+"'><i class='fa fa-sharp fa-solid fa-rotate-right'></i></button><button class='btn btn-outline-secondary btn-sm error_btn_delete' type='button' data-id='"+val.mess_id+"'><i class='fas fa-solid fa-trash'></i></button></div></div></form></td></tr>").appendTo("#outbox_numbers");			  
		  }
		//items.push( "<li id='" + key + "'>" + val + "</li>" );
		});
		
	});
}


function reloadAgents() {
	// reload agents
	$.getJSON( "ajax/reload-agents.php", function( data ) {
		
		$("#reloadagents a").each(function (index) {
					  
		  var data_filter = data.filter( element => element.ag == $(this).attr("data-ag"));
		  
		  if (!$(this).hasClass("active")) {
			  if (data_filter.length > 0)  {
				  $(this).removeClass("btn-primary").addClass("btn-danger"); 
				  //alert("ima"+$(this).attr("data-ag"));
			  } else {
				  $(this).removeClass("btn-danger").addClass("btn-outline-secondary");
				  //alert("nema"+$(this).attr("data-ag"));
				  //$(this).remove();
			  }
		  }
		});
	});
}

function sortGroupedMessages() {
	$('#tbody_groupedMessages tr').each(function() {
		 
	}).sort(function (a, b) {
		return $(a).data('date') < $(b).data('date');
	}).appendTo('#tbody_groupedMessages');
}



function getGroupedMessages(from_record) {
	$.getJSON( "ajax/get-new-grouped-messages.php?ag="+current_ag+"&from_record="+from_record, function( data ) {
		$.each( data, function( key, val ) {
			var gcval = "gc_"+val.mess_client_id;
			var class_red = "";
			var tr_class = "";
			var aktiv_selected = "";
			var pauz_selected = "";
			var blok_selected = "";
			if (val.mess_whosent == "0") {
				var class_red = "red";
			}
			if (val.status == "2") {
				var tr_class = "table-danger";
			} else if (val.status == "1") {
				var tr_class = "table-warning";
			}
			
			if (val.status == "1") {
				var pauz_selected = "selected";
			} else if (val.status == "2") {
				var blok_selected = "selected";
			} else {
				var aktiv_selected = "selected";
			}
			// if element doesnt exists, create it!
			if ($("#gc_"+val.mess_client_id).length > 0){
				
				
			} else {
				$("<tr class='"+tr_class+"' id='gc_"+val.mess_client_id+"' data-id='"+val.mess_client_id+"' data-date='"+val.js_mess_date+"'><th id='th_"+val.mess_client_id+"' scope='row' class='"+class_red+"'>"+val.client_number+"</th><td id='td_id_mess_"+val.mess_client_id+"' data-bs-toggle='tooltip' data-bs-placement='bottom' title='"+val.mess_message+"' data-bs-original-title='"+val.mess_message+"'>"+val.shorten_message+"</td><td id='td_id_date_"+val.mess_client_id+"'>"+val.mess_date+"</td><td><select id='client_ST"+val.mess_client_id+"' class='form-select sel_status_css' name='client_ST"+val.mess_client_id+"' data-id='"+val.mess_client_id+"'><option value='0' "+aktiv_selected+
				">Aktivan</option><option value='1' "+pauz_selected+">Pauziran</option><option value='2' "+blok_selected+">Blokiran</option></select></td></tr>").appendTo("#tbody_groupedMessages");
			}
		});
	});
	
	countCurrentMessages();
}

function countCurrentMessages() {
	var n = $("#tbody_groupedMessages tr").length;
	$("#current_grouped").html(n);
	$("#btn_grouped_showmore").data("from", n);
	
	$.ajax({
		'url':'ajax/get-sum-grouped-messages.php?ag='+current_ag, 
		'type':'GET', 
		'success':function(retData) { 
			// success 
			$("#total_grouped").html(retData);
		}, 
		'error':function(e) { 
			//failed 
			alert("Error while fetching total numbers");
		} 
	});
}

$( "#btn_grouped_showmore" ).on( "click", function() {
  getGroupedMessages($(this).data("from"))
});

function reloadGroupedMessages() {
	
	var n = $("#tbody_groupedMessages tr").length;
	// set how many current messages!
	countCurrentMessages();
	
	if (n > 0) {
		var arrayMe = []; 
		$("#tbody_groupedMessages tr").each(function(index) {
			arrayMe[index] = $(this).data("id");
		});
		
		var serialized_client_ids = arrayMe.join(",");
		
		$.getJSON( "ajax/reload-grouped-messages.php?serialized_client_ids="+serialized_client_ids, function( data ) {
			
			$.each( data, function( key, val ) {
				
				// number black or red depending if message is replied
				if (val.mess_whosent == "1") {
					$("#th_"+val.mess_client_id).removeClass("red");
				} else {
					$("#th_"+val.mess_client_id).addClass("red");
				}

				// reload inside message
				$("#td_id_mess_"+val.mess_client_id).attr('title', val.mess_message);
				$("#td_id_mess_"+val.mess_client_id).html(val.shorten_message);
				$("#td_id_date_"+val.mess_client_id).html(val.mess_date);
				$("#gc_"+val.mess_client_id).data("date", val.js_mess_date);
				
				// change status depends on return variable stao sam na selektoru za status!
				$("#client_ST"+val.mess_client_id).val(val.status);
				
				switch(val.status) {
					case "0":
						$("#gc"+val.mess_client_id).removeClass("table-danger table-warning"); 
					break;
					case "1":
						$("#gc_"+val.mess_client_id).removeClass("table-danger").addClass("table-warning"); 
					break;
					case "2":
						$("#gc_"+val.mess_client_id).removeClass("table-warning").addClass("table-danger"); 
					break;
				}
				
				//switch(val.status) {
			});
			
	    });
	} 
	
	
	sortGroupedMessages();
}