<?php namespace AloVoice; ?>
<center>
	<h3 class="h3 card-body">Настройки Telegram</h3> 
	<a href="#" onClick="addTgAccount()" data-toggle="modal" data-target="#alvModal" class="btn btn-primary title_line_button"><i class="fa fa-telegram"></i>+ Добавить аккаунт</a>
	
</center>
<br/>
<table class="table" id="stats_block_table" style="display:none; vertical-align: middle; text-align: center;">
	<thead>
		<tr>
			<th rowspan="2" style="vertical-align: middle; text-align: center;">Аккаунт</th>
			<th rowspan="2" style="vertical-align: middle; text-align: center;">Состояние</th>
			<th colspan="4" style="vertical-align: middle; text-align: center;">Исключения</th>
			<th rowspan="2" style="vertical-align: middle; text-align: center;">Действие</th>
		</tr>
		<tr>
			<th style="vertical-align: middle; text-align: center;">Группы</th>
			<th style="vertical-align: middle; text-align: center;">Каналы</th>
			<th style="vertical-align: middle; text-align: center;">Боты</th>
			<th style="vertical-align: middle; text-align: center;">АвтоLead</th>
		</tr>
	</thead>
	<tbody id="service_table_body"> <tr><td>Загрузка информации об Аккаунтах...</td></tr></tbody> 
</table>
<a href="#" onClick="testfunc()" class="btn btn-primary">Test</a>
<div id="testbox"></div>
<script>
var afterLoadPage = function(reload){
	if(typeof reload == 'undefined' ){ var reload = false; }
	AloTelegram("get_telegram_accounts",{},function(res){
		console.log("AloVoice TG settings RES:",res.length, res);
		if(res.length > 0){
			$("#stats_block_table").show();
			$("#service_table_body").html("");
			res.forEach(function(val){
				console.log("Each ACC:",val);
				var lineHTML = makeAccountLineHtml(val);
				$("#service_table_body").append(lineHTML);
			});
		}
	});
}
/*
setTimeout(function(){
	setInterval(function(){
		afterLoadPage(true);
	},5000);
},5000);
*/


function makeAccountLineHtml(val){
	var actHtml = (val.status == 'on') ? '<br><a href="#" onClick="stopTgAccount(\''+val.phone+'\');"><i class="fa fa-stop"></i> Остановить</a>' : '<br><a href="#" onClick="runTgAccount(\''+val.phone+'\');"><i class="fa fa-play"></i> Запустить</a>';
	var userHtml = (val.status == 'on') ? ' '+val.name+' ('+val.username+')' : '';
	var delHTML = '<a href="#" onClick="delTgAccount(\''+val.phone+'\');"><i class="fa fa-trash"></i> Удалить</a>';
	console.log("User HTML check:",userHtml);
	var grCheckBox = '<input type="checkbox" name="is_group_ex_'+val.phone+'">';
	var chanCheckBox = '<input type="checkbox" name="is_channel_ex_'+val.phone+'">';
	var botCheckBox = '<input type="checkbox" name="is_bot_ex_'+val.phone+'">';
	var isAutoLeadBox = '<input type="checkbox" name="is_auto_lead_'+val.phone+'">';
	var lineHTML = '<tr id="tg_line_'+val.phone+'">'
		+'<td id="tg_line_name_'+val.phone+'" ><i class="fa fa-telegram tgcolor"></i> <span>'+val.phone+''+userHtml+'</span></td>'
		+'<td id="tg_line_status_'+val.phone+'"> '+val.active+' </td>'
		+'<td style="text-align: center;"> '+grCheckBox+' </td>'
		+'<td style="text-align: center;"> '+chanCheckBox+' </td>'
		+'<td style="text-align: center;"> '+botCheckBox+' </td>'
		+'<td style="text-align: center;"> '+isAutoLeadBox+' </td>'
		+'<td  id="tg_line_actions_'+val.phone+'">'
			+delHTML
			+actHtml
		+'</td>'
		+'</tr>';
		
	return lineHTML;
}

function testfunc(){
	let dt = prompt('Чо искать?', 123456789);
	if(dt){
		loadAloVoiceInfo({ restmethod:"alovoice_findcontactinfo", 'number':dt },function(res){
			console.log("AloVoice TG TESTs:",res);
		});
		
		/*AloTelegram("get_loaduserphoto",{'dt':dt},function(res){
			console.log("AloVoice TG TESTs:",res);
		})*/
		/*
		AloTelegram("get_contact_bynumber",{'number':dt},function(res){
			console.log("AloVoice TG TESTs:",res);
		});*/
	}
	
	//AloTelegram("get_loadcontactslist",{},function(res){
	//	console.log("AloVoice TG TESTs:",res);
	//});
		
	/*let dt = prompt('Чо грузить?', 123);
	if(dt!=123){
		AloTelegram("get_testfunc",{'dt':dt},function(res){
			console.log("AloVoice TG TESTs:",res);
		});
		
	}*/
	//01000000182773072d9f0000000000001d3a41e62f1c9b0b
}

function stopTgAccount(tgnumber){
	console.log("Begin STOP tg accc.........",tgnumber);
	$("#tg_line_actions_"+tgnumber).html("Остановливается...");
	AloTelegram("stop_profile_by_number",{'TGNUMBER':tgnumber},function(res){
		console.log("AloVoice TG STOP RES:",res);
		setTimeout(function(){
			checkTgAccountStatus(tgnumber);
		},1000);
	});
}

function runTgAccount(tgnumber){
	console.log("Begin RUN tg accc.........",tgnumber);
	$("#tg_line_actions_"+tgnumber).html("Запускается...");
	AloTelegram("run_profile_by_number",{'TGNUMBER':tgnumber},function(res){
		console.log("AloVoice TG RUN RES:",res);
		//afterLoadPage();
		if(typeof res.answer !== 'undefined' && res.answer == 'sent' ){
			$("#tg_line_actions_"+tgnumber).html("Запущен!");
			//afterLoadPage(true);
			//$("#stats_block_table").show();
			setTimeout(function(){
				checkTgAccountStatus(tgnumber);
			},2000);
		}
	});
}

function checkTgAccountStatus(tgnumber){
	AloTelegram("get_telegram_account_status",{'TGNUMBER':tgnumber},function(res){
		console.log("AloVoice TG ACC s	tstus RES:",res);
		if(typeof res.phone !== 'undefined'){
			var lineHTML = makeAccountLineHtml(res)
			$("#tg_line_"+tgnumber).replaceWith(lineHTML);
			//$("#tg_line_status_"+tgnumber).html(lineHTML);
		}
	});
}

function delTgAccount(tgnumber){
	$("#tg_line_actions_"+tgnumber).html("Loading...");
	console.log("Begin DELETE tg accc.........",tgnumber);
	AloTelegram("delete_telegram_account",{'TGNUMBER':tgnumber},function(res){
		console.log("AloVoice TG DELETE RES:",res);
		if(typeof res.answer!=="undefined"){
			$("#tg_line_"+tgnumber).remove();
			//afterLoadPage(true);
		}
	});
}

function addTgAccount(){
	var confcodesent = false;
	console.log("Begin add tg accc.........");
	aloModal({
		label: "Добавить ТГ Аккаунт",
		body: '<br> <form><div class="form-group"><label for="tgnumber" class="col-form-label" id="tgaddformlabel">Введите номер Аккаунта:</label><input type="number" class="form-control" id="tgnumber"><small id="tgnumberBlock" class="form-text text-muted">Пример: 998991234567</small></div></form>',
		btn: "Отправить",
		nohide: true,
		callback: function(){
			var tgnumber = $("#tgnumber").val();
			console.log("Registering TG ACC: ", tgnumber);
			
			AloTelegram("register_account",{'TGNUMBER':tgnumber},function(res){
				console.log("AloVoice TG settings RES:",res);
				if(typeof res.answer !== 'undefined' && res.answer.length > 0){
					$("#stats_block_table").show();
				}
			});
			
			setTimeout(function(){
				var cntd = 30;
				
				console.log("Showing confirm win ACC: ", cntd);
				$("#tgaddformlabel").text("Введите код подтверждения:");
				$("#tgnumber").val("").attr("id","tgnumbercode");
				$("#tgnumberBlock").text("Код подтверждения из Telegramа или смс.").after('<span id="contdowntime">'+cntd+'</span>');
				$("#alvModalSendBtn").attr("class","btn btn-success").click(function(){
					if(confcodesent==false){
						var tgconfcode = $("#tgnumbercode").val();
						// $("#modalCloseBtn").click();
						console.log("Sending... AloVoice TG CONF CODE :",{'TGNUMBER':tgnumber,"TGCONFCODE":tgconfcode});
						AloTelegram("register_account_confcode",{'TGNUMBER':tgnumber,"TGCONFCODE":tgconfcode},function(res){
							console.log("AloVoice TG CONF CODE RES:",res);
							if(typeof res.answer !== 'undefined' && res.answer.length > 0){
								//afterLoadPage();
								console.log("Check CONF CODE Answer: ",res.answer);
								if(res.answer=="sent"){
									$("#contdowntime").remove();
									$("#modalCloseBtn").click();
								}
								
								if(res.answer=="waitpass"){
									cntd = 60;
									confcodesent = true;
									$("#tgaddformlabel").text("Введите двух факторный пароль:");
									$("#tgnumbercode").val("").attr("id","tgfapassword");
								}
							}
						});
					}
					else{
						cntd = 30;
						var tgfapassword = $("#tgfapassword").val();
						var passsendobj = {'TGNUMBER':tgnumber,"TGPASS":tgfapassword};
						console.log("Sending... AloVoice TG CONF CODE :",passsendobj);
						AloTelegram("register_account_fapassword",passsendobj,function(res){
							console.log("AloVoice TG 2FA Password sending Res:",res);
							$("#modalCloseBtn").click();
						});
					}
				});
				setInterval(function(){ if(cntd>0) { cntd = cntd-1; $("#contdowntime").text(cntd); } else{ $("#contdowntime").remove(); $("#tgnumberBlock").html("Время истекло!"); } },1000);
			},500);
		}
	});
	
}
</script>