<?php

//////////////////////////////////////////////////////////////
//===========================================================
// vpsretore_theme.php
//===========================================================
// SOFTACULOUS VIRTUALIZOR
// Version : 2.1.9
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Suyash
// Date:       25th July 2017
// Time:       15:42 hrs
// Site:       https://www.virtualizor.com/ (SOFTACULOUS VIRTUALIZOR)
// ----------------------------------------------------------
// Please Read the Terms of use at https://www.virtualizor.com
// ----------------------------------------------------------
//===========================================================
// (c)Softaculous Ltd.
//===========================================================
//////////////////////////////////////////////////////////////

if(!defined('VIRTUALIZOR')){

	die('Hacking Attempt');

}

function vpsrestore_theme(){

global $theme, $globals, $kernel, $user, $l, $error, $cluster, $backup_servers, $vpses, $storages, $servers, $backup_server;
	
softheader($l['<title>']);

$GLOBALS['breadcrumbs'] = ['dashboard', 'lms_vpsrestore'];
					
echo page_header(__('Restore VPS Backups'), 'icon icon-databackup', '', 0, 0, '');

error_handle($error);

// Is it offline ?
$hypervisor_status = $cluster->statewise($globals['server']);
if($hypervisor_status == 0 || $hypervisor_status == 2){

	echo '<div class="e_notice"><b>'.__('Note').' : </b> &nbsp; '.$globals['hypervisor_status'][$hypervisor_status].'</div>';

} else {

	echo ' <script type="text/javascript" charset="utf8" src="'.$theme['url'].'/js/jquery.dataTables.min.js"></script>
	<script type="text/javascript" charset="utf8" src="'.$theme['url'].'/js2/jquery-simple-tree-table.js"></script>
	<script language="javascript" type="text/javascript">


	$(document).ready(function() {

		$.fn.dataTableExt.sErrMode = "none";


		$(".get-backups").change(function() {
			$("#no_backups, #backup_list, #backuply_div").hide();
			$("#backups-tab").trigger("click");
			$("#restore_form").trigger("submit");
		});
		
		$("#dir").change(function() {
			$("#no_backups, #backup_list, #backuply_div").hide();
			$("#backups-tab").trigger("click");
			
			if($(this).val() == "other") {
				$("#row_scan_dir").show();
				return;
			}
				
			$("#row_scan_dir").hide();

			$("#restore_form").trigger("submit");
		});
		
		$("#scan").click(function() {
			$("#no_backups, #backup_list, #backuply_div").hide();
			
			$("#vps").val(0);
			
			if(!$("#scan_dir:visible").val()) {
				showalert("'.__('Please specify a valid backup directory').'" ,"1");
				return false;
			}
			$("#restore_form").trigger("submit");
		});

		$("#import").click(function() {
			$("#import_backup").val(1);
			$("#scan").trigger("click");
		});
		
		$("#scan_dir").keyup(function (e) {
			// Enter key pressed
			if (e.which == 13) {
				$("#dir").val("");
				$("#scan").trigger("click");
				return false;
			}
		});
		
		$("#restore_form").submit(function(event) {
			
			$("#progress_bar").show();
			$("#backuply_div").hide();
			
			// Set the directory
			let dir = $("#dir").val();
			$("#dir_input").val(dir);
			
			let date = $("#date").val();
			let bid = $("#bid").val();
			let vpsid = $("#vps").val();
			let serid = $("#serid").val();
			let backup_type = $("input[name=\"backup_type\"]:checked").val();
			
			// get backups from scanning directories
			let scan_dir = $("#scan_dir:visible").val()

			let import_backup = 0;

			if(scan_dir) {
				import_backup = $("#import_backup").val();
			} 

			dataTableObj = {
				processing : true,
				serverSide : true,
				searchDelay: 400,
				pageLength : '.$globals['reslen'].',
				ajax : {
					url : "'.$globals['index'].'act=vpsrestore&api=json"+(backup_type == "use_backuply" ? "&use_backuply=1" : "")+"&reslen='.$globals['reslen'].'",
					type : "POST",
					data : function(d){
						const sortHead = (backup_type == "use_backuply") ? ["", "vpsid", "filename"] : ["filename", "size"];
						return {
							"page" : parseInt(d.start/d.length)+1,
							"reslen" : d.length,
							"dir" : dir,
							"scan_dir" : scan_dir,
							"import_backup" : import_backup,
							"import_dir" : scan_dir,
							"backup_type" : backup_type,
							"bid" : bid ? bid : -1,
							"date" : date,
							"vpsid" : vpsid,
							"serid" : serid,
							"search" : d.search.value,
							"sortcolumn" : sortHead[d.order[0].column],
							"sortby" : d.order[0].dir,
							"op" : "get_backups"
						}
					},
					dataSrc: function(data) {

						$("#import_backup").val(0)

						if ("error" in data) {
							let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
							showalert(err, "1");
							return [];
						}

						if("import_backups_actid" in data){
							showalert("'.__J('Import Backups Task Started').'");
							return [];
						}
						
						$("#dir").empty();
						
						$("<option />")
							.val("")
							.text("'.__('Select').'")
							.appendTo("#dir");
						
						if(!empty(data["vps_backup_dir"]) && !data["directories"].includes(data["vps_backup_dir"])){
							data["directories"].push(data["vps_backup_dir"]);
						}
						
						$.each(data["directories"], function(key, dir) {
						    const $opt = $("<option />")
											.val(dir)
											.text(dir);

							if (data.dir && data.dir === dir) {
								$opt.attr("selected", true);
							}
								
							$opt.appendTo("#dir");
						});
						
						$("<option />")
							.val("other")
							.text("'.__('Other').'")
							.appendTo("#dir");
						
						$("#row_dir").show();
						
						var selected = $("#date").val();
						
						$("#date").empty();

						$("<option />")
							.val("")
							.text("'.__('Select').'")
							.attr("selected", true)
							.appendTo("#date");
						
						if(empty(data.backup_list)) {
							$("#no_backups").show();
							
						} else if(Object.keys(data["backup_list"]).length > 0){

							if(!empty(data["use_backuply"])){

								let rows = [];

								$.each(data["backup_list"], function(time, files) {

									let parent = {
										bkid: files.bkid,
										node_id: time,
										node_pid: (files.parent_bkply_id != 0 ? files.parent_bkply_id : time),
										vpsid: files.vpsid,
										hostname: files.hostname,
										filename: files.filename,
										htime: files.htime,
										type: files.type,
										size: files.size,
										is_parent: (files.type == "full" ? true : false),
										formattedTime: time,
										formatted_htime: formatHTime(files.htime),
										childrens_count: files.children ? Object.keys(files.children).length : 0,
										is_vps_present: files.is_vps_present,
										serid: files.serid,
										bid: files.bid,
										dir: files.dir,
										note: files.note,
										folder_format: files.folder_format
									};

									rows.push(parent);
									
									// Child rows
									if (!empty(files.children)) {
										$.each(files[\'children\'], (k, file) => {
											let matches = file.filename.match(/^(\d+)/i);
											let vpsid = matches ? matches[1] : file.filename.split("-")[2];
											
											rows.push({
												bkid: file.bkid,
												node_pid: file.parent_bkply_id,
												vpsid: files.vpsid,
												hostname: files.hostname,
												filename: file.filename,
												htime: file.htime,
												type: file.type,
												size: file.size,
												is_parent: false,
												formattedTime: time,
												formatted_htime: formatHTime(file.htime),
												childrens_count: 0,
												is_vps_present: file.is_vps_present,
												serid: file.serid,
												bid: file.bid,
												dir: file.dir,
												note: file.note,
												folder_format: file.folder_format
											});
										});
									}
								});
								
								return rows;

							} else {
							 
								$.each(data["backup_list"], function(key, value) {

									var date_str = key.substr(0, 4) + "/" + key.substr(4, 2) + "/" + key.substr(6, 2);

									const $opt = $("<option />")
										.val(key)
										.text(date_str);

									if (data.date && data.date == key) {
										$opt.attr("selected", true);
									}
										
									$opt.appendTo("#date");

									if(!empty(value)) {
										backups_list = value;
									}
										
								});
								
								// Sort by date desc
								var sorted = $("#date option").sort(function(a, b) { return b.value - a.value });
								$("#date").html(sorted);
								
								if($("#date option").length > 0) {
									$("#row_date").show();
								}

								if(!date) {
									return [].concat(...Object.values(data.backup_list));
								}
									
								return data.backup_list[date];
							}
						}

						return [];
					},
					complete: function(data) {
						$("#progress_bar").hide();
					}
				},
				columnDefs : [
					{ targets: [0, 3, 4, 5, 6], orderable: false }
				],
				columns: [
					{ 
						data: "bkid", 
						render: function(data, type, row) { return `<div align="center">${row.bkid > 0 ? row.bkid : "NA"}</div>`; }
					},
					{ 
						data: "filename", 
						render: function(data, type, row) {
							return `${data} ${row.is_vps_present == 1 ? `&nbsp;&nbsp;<a class="linkflare font-weight-bold" href="index.php?act=managevps&vpsid=${row.vpsid}">${row.vpsid}</a>` : ``}`;
						}
					},
					{ data: "size", render: d => `${(parseFloat(d)/1024/1024).toFixed(2)} M` },
					{ 
						data: null, 
						render: function(data, type, row) {
							return `<div align="center">${row.is_vps_present == 1 ? \'<a href="#" onclick="return restore(this, 0)" title="'.__('Restore').'"><h6><i class="fas fa-undo text-warning"></i></h6></a>\' : ``}</div>`;
						}
					},
					{ data: null, defaultContent: \'<div align="center"><a href="#" onclick="return restore_details(this)" title="'.__('Restore To New').'"><h6><i class="fas fa-undo text-warning"></i></h6></a></div>\' }, 					
					{ 
						data: null, 
						render: function(data) {

							var fa = data.note ? "fa" : "far";
							return `<div class="file-container custom-control custom-checkbox" style="position: relative;"> \
								<input type="hidden" name="note" id="${data.bkid}" value="${data.note}"> \
								<span class="file-icon text-center" style="cursor:pointer;" onclick="displayNote(this, \'${data.bkid}\')"><i class="${fa} fa-file fa-book"></i></span> 
							</div>`;
						}
					},
					{ data: null, defaultContent: \'<a href="#" onclick="return Delbackup(this)" title="'.__('Delete').'"><h6><i class="fas fa-trash text-danger"></i></h6></a>\' },
					{ 
						data: null, 
						render: function(row) {
							return `<div class="custom-control custom-checkbox"> \
								<input type="checkbox" class="ios custom-control-input" id="vpsbackup_list_${row.bkid}" name="vpsbackup_list[]"> \
								<label class="custom-control-label" for="vpsbackup_list_${row.bkid}"></label> \
							</div>`;
						}
					}
				],
				createdRow: function(row, data, dataIndex) {

					$("#no_backups").hide();
					
					var vpsid;
					var file = data["filename"];
					var matches = file.match(/^(\d+)/i);
					
					if(empty(matches)){
						var tmp_m1 = file.split(".");
						var tmp_m2 = tmp_m1[0].split("-");
						var vpsid = tmp_m2[2];
					} else {  
						vpsid = matches[1];
					}

					$(row)
						.attr("data-bkid", data["bkid"])
						.attr("data-vpsid", vpsid)
						.attr("data-file", file)
						.attr("data-serid", data["serid"])
						.attr("data-bid", data["bid"])
						.attr("data-dir", data["dir"])
						.attr("data-date", data["date"]);

				},
				drawCallback: function(oSettings) {
					$("#table_backup_list td.sorting_1").removeClass("sorting_1");
					$("#table_backup_list td.sorting_2").removeClass("sorting_2");
					refresh_note();
				}
			};

			backup_temp_table = "#table_backup_list";

			if(backup_type == "use_backuply") {
				backup_temp_table = "#backuply_table_list"

				var groupColumn = 0;

				var backuplyObj = {
					columnDefs: [
						{ "visible": false, "targets": groupColumn },
						{ "targets": [0, 1, 4, 5, 6, 7], "orderable": false }
					],
					order: [[ groupColumn, "desc" ]],
					displayLength: 25,
					columns: [
						{
							data: null
						},
						{
							data: null,
							render: d => d.bkid
						},
						{
							data: null,
							render: d => `${d.vpsid} (${d.hostname || ""})`
						},
						{
							data: "filename",
							render: (d, t, row) => row.is_parent ? d : `<span class="pl-4">${d}</span>`
						},
						{
							data: "type",
							render: d => `<span class="badge p-1 badge-pill blue_btn">${d || "full"}</span>`
						},
						{
							data: "size",
							render: d => `${(parseFloat(d)/1024/1024).toFixed(2)} MB`
						},
						{
							data: "formatted_htime"
						},
						{
							data: null,
							render: function(data) {
								
								var fa = data.note ? "fa" : "far";
								return `<div class="file-container custom-control custom-checkbox" style="position: relative;"> \
									<input type="hidden" name="note" id="${data.bkid}" value="${data.note}"> \
									<span class="file-icon text-center" style="cursor:pointer;" onclick="displayNote(this, \'${data.bkid}\')"><i class="${fa} fa-file fa-book"></i></span>
								</div>`;
							}
						},
						{
							data: null,
							render: function(data, type, row) {
								let row_div = `<div class="row">`;

								if(data.is_vps_present == 1) {
									row_div += `<div class="col-4 px-1">
										<a href="javascript:void(0);" title="'.__('Restore').'" onclick="backuply_restore_bkup(this)">
											<i class="fas fa-history restore-icon"></i>
										</a>
									</div>`;
								}
								
								row_div += `
									<div class="col-4 px-1">
										<a href="javascript:void(0);" title="'.__('Restore To New VPS').'"  onclick="restore_details(this)">
											<i class="fas fa-history text-warning restore-icon"></i>
										</a>
									</div>
									<div class="col-4 px-1">
										<a href="javascript:void(0);" title="'.__('Delete').'" onclick="backuply_delete_bkup(this)">
											<i class="fas fa-trash text-danger"></i>
										</a>
									</div>
								</div>`

								return row_div;
								
							}
						}
					],
					createdRow: function(row, data, dataIndex) {

						$("#backuply_div").show();
						$("#no_backups").hide();
						
						$(row)
							.attr("data-node-pid", data.node_pid)
							.attr("data-node-id", data.node_id)
							.attr("data-serid", data.serid)
							.attr("data-bkid", data.bkid)
							.attr("data-vpsid", data.vpsid)
							.attr("data-bid", data.bid)
							.attr("data-dir", data.dir)
							.attr("data-folder_format", data.folder_format)
							.attr("data-chain", data.node_pid)
							.attr("data-htime", data.htime)
							.attr("data-file", data.filename);
					},
					drawCallback: function ( settings ) {
					
						let api = this.api();
						var rows = api.rows( {page:"current"} ).nodes();
						var last = null;
			
						api.column(groupColumn, {page:"current"} ).data().each( function ( group, i ) {

							if(!empty(group) && (last == null || last["node_pid"] !== group["node_pid"])) {

								$(rows).eq(i).before(
									`<tr class="group simple-tree-table-root simple-tree-table-opened" data-node-id="${group.node_id}">
										<td colspan="8">
											${group.is_vps_present == 1 ? 
											`<a class="linkflare font-weight-bold" href="index.php?act=managevps&vpsid=${group.vpsid}">${group.vpsid} (${group.hostname})</a>&nbsp;&nbsp;` : 
											`<span class="font-weight-bold">${group.vpsid} (${group.hostname})</span>`}
											${timeConverter(group.formattedTime)} <span class="badge p-1 badge-pill blue_btn ml-2">${group.childrens_count + 1}</span>
										</td>
									</tr>`
								);
			
								if($(rows).eq( i ).prev().attr(\'data-node-id\') == $(rows).eq( i ).attr(\'data-node-id\')){
									$(rows).eq( i ).removeAttr(\'data-node-id\')
								}
									
								last = group;
							}
						});
						
						$("#backuply_table_list").simpleTreeTable({
							store: "session",
							storeKey: "backuply_table_list"
						});

						$(".backuply_table").parent().addClass("sticky scrollbar-virt").scrollbar();

					}
				}
				dataTableObj = Object.assign(dataTableObj, backuplyObj);
			}

			// Destroy the old DataTable
			if($.fn.DataTable.isDataTable(backup_temp_table)) {
				$(backup_temp_table).DataTable().destroy();
				$(backup_temp_table+" tbody").html("");
			}

			// Create new  DataTable
			$(backup_temp_table).DataTable(dataTableObj);

			return false;
			
		});
		
		$("#restore_form").trigger("submit");

		refresh_tasks();
		
		// Refresh tasks every 10 secs
		setInterval(refresh_tasks, 10000);

		$("#import_backup").val(0);
		
	});

	function displayNote(icon, bkid){

		const $popover = $("#bkp_edit_notePopover");

		// Get the icons position
		const rect = icon.getBoundingClientRect();
		const scrollX = window.scrollX;
		const scrollY = window.scrollY;

		// Calculate translate position to place above the icon
		const translateX = scrollX + rect.left;
		const translateY = scrollY + rect.top - $popover.outerHeight() - 10;

		// Apply styles to position the popover
		$popover.css({
			"transform": `translateX(${translateX}px) translateY(${translateY}px) translateZ(0px)`,
			"top": "-156px",
			"left": "-335px",
			"position": "absolute",
			"z-index": 2000
		});

		
		// Load note into textarea
		let note = $("#"+bkid).val();

		$popover.find("#bkp_edit_note").val(note);
		$popover.find("#bkid").val(bkid);

		$("#bkp_edit_notePopover").fadeToggle();
	}


	function bkp_editNote(){

		var bkid =  $("#bkid").val();
		var updatedNote =  $("#bkp_edit_note").val();

		var data = {
			"bkid": bkid,
			"note": updatedNote
		};

		$.ajax({
				type: "POST",
				url: "'.$globals['index'].'act=vpsrestore&api=json&update_note=1",
				dataType : "json",
				data: data,
				success:function(res){
					
					$("#bkp_edit_notePopover").hide();

					if(!empty(res["error"])){
						error(res["error"]);
						return;
					}

					if(!empty(res["done"])){
						done(res["done"]);
						$("#"+bkid).val(updatedNote);
						// Change the icon but keep other classes intact
						$("#" + bkid).closest("tr").find("i.fa-file").attr("class", (updatedNote ? "fa" : "far") + " fa-file fa-book");
					}
				}
			});

	}

	function backuply_delete_bkup(el){

		let del_data = $(el).closest("tr").data();

		del_data["use_backuply"] = ($("input[name=\"backup_type\"]:checked").val() == "use_backuply" ? 1 : 0);

		if(!del_data["use_backuply"]){
			return false;
		}

		showalert("'.__J('Are you sure, you want to delete the selected item(s) ?').'" ,"3" ,function(confirm){
			
			if(!confirm){
				return false;
			}
			
			$("#progress_bar").show();

			$.ajax({
				type: "POST",
				url: "'.$globals['index'].'act=vpsrestore&api=json&backuply_delete=1&use_backuply=1",
				dataType : "json",
				data: del_data,
				success:function(res){
					$("#progress_bar").hide();

					if("delete_done" in res){
						setTimeout(function(){
							// Remove all deleted rows
							$.each(backup_list, function(key, value) {
								$("tr[data-chain=\'" + del_data["chain"] + "\']").remove();
							});
							refresh_tasks();
							showalert("'.__J('The backup(s) have been deleted successfully.').'");
							$("#restore_form").trigger("submit");
						}, 200);
					}
					
					if("error" in res) {
						setTimeout(function(){
							let err = `<ul>${Object.values(res.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
							showalert(err ,"1");
							return false;
						}, 200);
					}
				}
			});

		})
	}

	function backuply_restore_bkup(el){
		var use_backuply = ($("input[name=\"backup_type\"]:checked").val() == "use_backuply" ? 1 : 0);
		
		if(!use_backuply){
			return false;
		}

		showalert("'.__J('Are you sure you want to restore this ?').'" ,"3" ,function(confirm){

			if(confirm == false){
				return false;
			}
				
			$("#progress_bar").show();

			let post_data = $(el).closest("tr").data();

			$.ajax({
				type: "POST",
				url: "'.$globals['index'].'act=vpsrestore&api=json&backuply_restore=1&use_backuply=1",
				data: post_data,
				dataType : "json",
				success: function(data){
					$("#progress_bar").hide();
					if("restore_done" in data){
						animate_task("'.__J('Restore to new task started').'");
						setTimeout(function(){showalert("'.__J('The restore process has been started and is running in the background.').'")}, 100);
						refresh_tasks();
					}
					if("error" in data) {
						setTimeout(function(){
							let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
							showalert(err ,"1");
							return false;
						} ,200);
					}
				}
			});
		})
	}
	
	function restore_new() {
		
		if(empty($("#hostname").val())) {
			showalert("'.__J('Please enter a valid hostname').'" ,"1");
			return false;
		}
		
		if(empty($("#uid").val())) {
			showalert("'.__J('Please select a valid user').'" ,"1");
			return false;
		}
		
		$("#progress_bar2").show();
		$("#restore_new_form").hide();

		$.ajax({
			type: "POST",
			url: "'.$globals['index'].'act=vpsrestore&api=json",
			data: $("#restore_new_form").serialize(),
			dataType : "json",
			success: function(data){
				if("restore_done" in data) {
					animate_task("'.__J('Restore to new task started').'");
					showalert("'.__J('The restore process has been started and is running in the background.').'");
					refresh_tasks();
				}
				
				if("error" in data) {
					let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
					showalert(err ,"1");
					return false;
				}
				
				$("#common_modal").modal("hide");
			},
			complete: function(data) {
				$("#progress_bar2").hide();
				$("#restore_new_form").show();
			}
		});
		
		return false;
		
	}

	function update_ips(el){
		var serid = $(el).val();
		$("#ips_loader").show();
		$.ajax({
			type: "POST",
			url: "'.$globals['index'].'act=vpsrestore&api=json",
			data: {
				update_ips: serid,
			},
			dataType : "json",
			success: function(data){
				
				$("#ips_loader").hide();

				if("error" in data) {
					let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
					showalert(err ,"1");
					return false;
				}

				ip_arr_list = new Array("ips", "ips_int", "ips6", "ips6_subnet");
				//ip_arr = new Array("ips", "ips6", "ips6_subnet", "ips_int");
				ips_opt_html = "";

				$.each(ip_arr_list, function(k, ip_key){

					if(ip_key == "ips" || ip_key == "ips_int"){ 
						$.each(data["updated_ips"]["ips_list"][ip_key], function(ipid, val){
							ips_opt_html += \'<option value="\'+data["updated_ips"]["ips_list"][ip_key][ipid]["ip"]+\'">\'+data["updated_ips"]["ips_list"][ip_key][ipid]["ip"]+\'</option>\';
							
						});
						
						$("."+ip_key+"_sel").empty().append(ips_opt_html);
					
						ips_opt_html = "";										
					}

					if(data["updated_ips"]["free_ips"][ip_key] < $("#"+ip_key+"_count").val() || empty(data["updated_ips"]["free_ips"][ip_key])){
						$("#"+ip_key+"_count").removeClass("text-muted");
						$("#"+ip_key+"_count").addClass("text-danger");
					}else{
						$("#"+ip_key+"_count").addClass("text-muted");
						$("#"+ip_key+"_count").removeClass("text-danger");
					}
					
					$("#"+ip_key+"_count").html(data["updated_ips"]["free_ips"][ip_key]+" '.__J('Free').'");

				});	
			}
		});
	}
		
	function restore_details(el){

		$("#progress_bar").show();

		let post_data = $(el).closest("tr").data();

		post_data["restore_details"] = post_data.vpsid;
		post_data["use_backuply"] = ($("input[name=\"backup_type\"]:checked").val() == "use_backuply" ? 1 : 0);

		let table = "#" + (post_data["use_backuply"] ? "backuply_div" : "backup_list");
		
		$(table).hide();

		$.ajax({
			type: "POST",
			url: "'.$globals['index'].'act=vpsrestore&api=json",
			data: post_data,
			dataType : "json",
			success: function(data){
				if("error" in data) {
					let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
					showalert(err ,"1");
					return false;
				}
				
				var restore_details = data["restore_details"];
				
				// Show the restore dialog
				var $modal_form = $(\'<form id="restore_new_form" action="" method="post" onsubmit="return restore_new()"> \
									<input type="hidden" id="restore" name="restore" value="1" /> \
									<input type="hidden" id="fromserver" name="fromserver" /> \
									<input type="hidden" id="vpsid" name="vpsid" /> \
									<input type="hidden" id="bid2" name="bid" /> \
									<input type="hidden" id="dir2" name="dir" /> \
									<input type="hidden" id="folder_format" name="folder_format" /> \
									<input type="hidden" id="file_name" name="file" /> \
									<input type="hidden" id="date2" name="date" /> \
									<input type="hidden" id="chain" name="chain" /> \
									<input type="hidden" id="htime" name="htime" /> \
									<input type="hidden" id="use_backuply" name="use_backuply" /> \
									<input type="hidden" id="newvps" name="newvps" value="1" /> \
									<input type="hidden" id="bkid" name="bkid" value="0"/> \
									<div class="row mx-auto w-100 my-3"> \
										<div class="col-sm-3"> \
											<label class="control-label">'.__J('Hostname').'&nbsp;<a class="info" data-placement="right" tooltip="'.__J('Enter the hostname for the VPS. e.g. www.domain.com').'"><i class="fas text-primary fa-info-circle"></i></a></label> \
										</div> \
										<div class="col-sm-9"> \
											<input type="text" class="form-control" name="hostname" id="hostname" size="30" value=""> \
										</div> \
									</div> \
									<div class="row mx-auto w-100 my-3"> \
										<div class="col-sm-3"> \
											<div class="d-flex align-items-center">\
												<label class="control-label">'.__J('Select User').'&nbsp;<a class="info" data-placement="right" tooltip="'.__J('Select the user for the VPS').'"><i class="fas text-primary fa-info-circle"></i></a></label>\
												<div class="loader ml-2" style="display:none;" id="ajax_user_loader"></div> \
											</div>\
										</div> \
										<div class="col-sm-9"> \
											<select class="virt-select" id="uid" name="uid"> \
												<option value="0">'.__J('Select').'</option> \
											</select> \
										</div> \
									</div> \
									<div class="row mx-auto w-100 my-3" id="os_div" style="display:none"> \
										<div class="col-sm-3"> \
											<label class="control-label">'.__J('Select OS').' &nbsp;<a class="info" data-placement="right" tooltip="'.__J('Please select the OS to show distro logo for this VPS').'"><i class="fas text-primary fa-info-circle"></i></a></label> \
										</div> \
										<div class="col-sm-9"> \
											<select class="virt-select" id="osid" name="osid"> \
												<option value="0">'.__J('Select').'</option> \
											</select> \
										</div> \
									</div> \
									<div class="row mx-auto w-100 my-3" id="iso_div" style="display:none"> \
										<div class="col-sm-3"> \
											<label class="control-label">'.__J('Select ISO').' &nbsp;<a class="info" data-placement="right" tooltip="'.__J('Please select the ISO to show distro logo for this VPS').'"><i class="fas text-primary fa-info-circle"></i></a></label> \
										</div> \
										<div class="col-sm-9"> \
											<select class="virt-select" id="iso" name="iso"> \
												<option value="0">'.__J('Select').'</option> \
											</select> \
										</div> \
									</div> \
									<div class="row mx-auto w-100 my-3" id="newserid_div"> \
										<div class="col-sm-3"> \
											<label class="control-label">'.__J('Select Server').'&nbsp;<a class="info" data-placement="right" tooltip="'.__J('Select the server where you want to restore the backup of the VPS').'"><i class="fas text-primary fa-info-circle"></i></a></label> \
										</div> \
										<div class="col-sm-9">\
											<select name="newserid" id="newserid" class="virt-select newserid" onchange="update_storage(this);update_ips(this);">\
												';
												foreach($servers as $k => $v){
													$multi_virt = str_replace(' ', '_', $servers[$k]['virt']);
													echo '<option class="hide_option" value = '.$servers[$k]['serid'].' data-virt='.$multi_virt.' >'.$servers[$k]['server_name'].' ('.$servers[$k]['ip'].')</option>\\';
												}
												echo'
											</select>\
										</div> \
										<div class="loader ml-2" style="display:none;" id="ips_loader"></div> \
									</div> \
									<div class="row mx-auto w-100 my-3" id="main_disk" style="display:none;"> \
										<div class="col-sm-3"> \
											<label class="control-label">'.__J('Select Storage').'&nbsp;<a class="info" data-placement="right" tooltip="'.__J('Select the storage for the VPS disk(s)').'"><i class="fas text-primary fa-info-circle"></i></a></label> \
										</div> \
										<div class="col-sm-9" id="disks"></div> \
									</div> \
									<div id="ips_row"> \
									</div> \
									<div id="ips_list_row"> \
									</div> \
									<div class="row mx-auto w-100 my-3" id="os_check_note"> \
										<div class="col-sm-12 notice"> \
										<b> '.__J('Note').' : </b> \
										<span id="os_err_note"></span> \
										</div> \
									</div> \
									<div class="row mx-auto w-100"> \
										<div class="col-sm-12 text-center mb-3"> \
											<input class="go_btn" value="'.__J('Restore').'" type="submit"> \
										</div> \
									</div> \
									<div class="row mx-auto w-100" id="os_notice" style="display:none;"> \
										<div class="col-sm-12 text-center mb-3"> \
											<div class="notice">'.__J('<b>NOTE:</b> We will not format the VPS with selected OS').'</div>\
										</div> \
									</div> \
								</form> \
								<div id="progress_bar2" style="display:none;"> \
									<br /> \
									<center> \
										<font id="progress_txt" size="4">'.__J('Please wait, Action in Progress.').'</font> \
									</center> \
									<div class="my-2" align="center"> \
										<div class="progress w-50"> \
											<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100"> \
											</div> \
										</div> \
									</div> \
									<center> \
										'.__J('You will be notified once the Action is Completed.').' \
									</center> \
									<br>\
								</div> \');

				// Set form date
				$modal_form.find("#vpsid").val(post_data.vpsid);
				$modal_form.find("#fromserver").val(post_data.serid);
				$modal_form.find("#file_name").val(post_data.file);
				$modal_form.find("#bkid").val(post_data.bkid);
				$modal_form.find("#bid2").val(post_data.bid);
				$modal_form.find("#dir2").val(post_data.dir);
				$modal_form.find("#folder_format").val(post_data.folder_format);
				$modal_form.find("#date2").val(post_data.date);
				$modal_form.find("#htime").val(post_data.htime);
				$modal_form.find("#use_backuply").val(post_data.use_backuply);
				$modal_form.find("#chain").val(post_data.chain);
				$modal_form.find("#hostname").val(restore_details["hostname"]);
				$modal_form.find("#newserid").val(post_data.serid).change();
				if(restore_details["ignore_os_check"] != ""){
					$modal_form.find("#os_check_note").addClass("d-flex");
					$modal_form.find("#os_err_note").text(restore_details["ignore_os_check"]);
				}else{
					$modal_form.find("#os_check_note").addClass("d-none");
				}
				$modal_form.find(".newserid option").each(function(){
					if(!$(this).data("virt").includes(restore_details["vps_virt"])){
						$(this).remove();
					}
				});
				
				var storages_row = "";

				if(!empty(restore_details["disks"])){
					$modal_form.find("#main_disk").css("display", "");
				}
				
				if(!restore_details["bus_driver"]){

					storages_row += \'<div class="row mx-auto w-100 disk_row"> \
									<div class="col-sm-3 p-2"> \
										<label class="control-label disk-number"></label><br> \
										<span class="help-block disk-size"></span> \
									</div> \
									<div class="col-sm-2 p-2" id="size_div"> \
										<input class="form-control size" type="number" id="hdd_0" step="0.001" size="30"/> \
									</div> \
									<div class="col-sm-7 p-2" id="disk_div"> \
										<select class="custom-select st_uuid"> \ ';
											foreach($storages as $storage) {
												echo '<option value="'.$storage['st_uuid'].'">'.$storage['name'].'&nbsp;('.$storage['free'].' GB '.(empty($storage['oversell']) ? __J('Free') : __J('Overcommitted Free Space')).')</option>';
											}
										echo '</select> \ ';
				
									echo '</div> \
								</div>\'; 
				}else{
					
					storages_row += \'<div class="row mx-auto w-100 disk_row"> \
						<div class="col-sm-3 p-0"> \
							<label class="control-label disk-number"></label><br> \
								<span class="help-block disk-size"></span> \
						</div> \
						<div class="col-sm-2 p-0" id="bus_driver_div"> \
							<span class="help-block bus_driver"></span> \
							</div> \
							<div class="col-sm-2 p-0" id="bus_driver_num_div">\
							<span class="help-block bus_driver_num"></span> \
							</div> \
								<div class="col-sm-2 p-1" id="size_div"> \
									<input class="form-control size" type="number" id="hdd_0" step="0.001" size="30"/> \
									</div> \
								<div class="col-sm-3 p-1"  id="disk_div"> \
								<select class="custom-select st_uuid"> \ ';
									foreach($storages as $storage) {
										echo '<option value="'.$storage['st_uuid'].'">'.$storage['name'].'&nbsp;('.$storage['free'].' GB '.(empty($storage['oversell']) ? __J('Free') : __J('Overcommitted Free Space')).')</option>';
									}
								echo '</select> \
								</div> \
					</div> \
					</div>\'; 
				}
				
				$.each(restore_details["disks"], function(did, disk) {
					$row = $(storages_row).clone();
				
					$row.find(".disk-number").text("DISK "+(did+1));
					$row.find(".disk-size").text(disk["size"] + " GB");
					$row.find(".st_uuid").val(disk["st_uuid"]).attr("name", "st_uuid_" + did);
					$row.find(".size").val(disk["size"]).attr("name", "size_" + did);
					$row.find(".bus_driver").html("'.__J('Bus Driver').'<br>"+(disk["bus_driver"]));
					$row.find(".bus_driver_num").html("'.__J('Bus Driver Num').'<br>"+(disk["bus_driver_num"]));
					
					$modal_form.find("#disks").append($row);
				});

				var ip_lang = new Array();
				var ip_lang_ind = new Array();
				';
				
				$ip_arr_lang = [
								'ips_int' => __J('Number of Internal IP Addresses'),
								'ips' => __J('Number of IP Address'),
								'ips6_subnet' => __J('Number of IPv6 Subnet'),
								'ips6' => __J('Number of IPv6 Addresses'),
								'ips_int_ind' => __J('Internal IP Addresses'),
								'ips_int_ind_exp' => __J('You can specify the Internal IPs to assign'),
								'ips_ind' => __J('IP Address'),
								'ips_ind_exp' => __J('You can specify the IPs to assign')
							];

				$ip_arr = array('ips_int','ips','ips6_subnet','ips6');

				foreach($ip_arr as $ip_key){
					echo 'ip_lang["'.$ip_key.'"] = "'.$ip_arr_lang[$ip_key].'";';
					echo 'ip_lang["'.$ip_key.'_exp"] = "'.$ip_arr_lang[$ip_key].'";';
					if(in_array($ip_key, array('ips_int','ips'))){
						echo 'ip_lang_ind["'.$ip_key.'"] = "'.$ip_arr_lang[$ip_key.'_ind'].'";';
						echo 'ip_lang_ind["'.$ip_key.'_exp"] = "'.$ip_arr_lang[$ip_key.'_ind_exp'].'";';
					}

				}
				
				echo'
				ip_arr = new Array("ips", "ips_int", "ips6", "ips6_subnet");
				ip_html = "";
				$.each(ip_arr, function(k, ip_key){
					var txt_color = "text-muted";
					if(restore_details["free_ips"][ip_key] < restore_details["vps_ips"][ip_key] || empty(restore_details["free_ips"][ip_key])){
						txt_color = "text-danger";
					}
					ip_html += \'<div class="row mx-auto w-100 my-3">\
									<div class="col-sm-3"> \
										<label class="control-label">\'+ip_lang[ip_key]+\'&nbsp;<a class="info" data-placement="right" tooltip="\'+ip_lang[ip_key+"_exp"]+\'"><i class="fas text-primary fa-info-circle"></i></a></label> \
									</div> \
									<div class="col-sm-9" id="ips_div"> \
										<input type="text" name="num_\'+ip_key+\'" class="form-control" value="\'+restore_details["vps_ips"][ip_key]+\'"><span id="\'+ip_key+\'_count" class="\'+txt_color+\'">\'+restore_details["free_ips"][ip_key]+\' '.__J('Free').'</span>\
									</div>\
								</div>\';
					
				});	
				$modal_form.find("#ips_row").html(ip_html);

				ip_arr_list = new Array("ips", "ips_int");
				ips_list_html = "";
				ips_opt_html = "";

				$.each(ip_arr_list, function(k, ip_key){
					
					if(!empty(restore_details["ips_list"][ip_key])){


						$.each(restore_details["ips_list"][ip_key], function(ipid, val){
							ips_opt_html += \'<option value="\'+restore_details["ips_list"][ip_key][ipid]["ip"]+\'">\'+restore_details["ips_list"][ip_key][ipid]["ip"]+\'</option>\';
								
						});

						ips_list_html += \'<div class="row mx-auto w-100 my-3">\
												<div class="col-sm-3"> \
													<label class="control-label">\'+ip_lang_ind[ip_key]+\'&nbsp;<a class="info" data-placement="right" tooltip="\'+ip_lang_ind[ip_key+"_exp"]+\'"><i class="fas text-primary fa-info-circle"></i></a></label> \
												</div> \
												<div class="col-sm-9" id="disk_div"> \
													<select class="\'+ip_key+"_sel"+\' custom-select"  name="\'+ip_key+"[]"+\'" multiple="multiple"> \'+ips_opt_html+\' </select> \
												</div>\
											</div>\';

								
						
						ips_opt_html = "";										
					}

				});	

				$modal_form.find("#ips_list_row").html(ips_list_html);

				var $select = $modal_form.find("#uid");
				
				$.each(restore_details["users"], function(uid, email) {
					var $option = $("<option />").val(uid)
						.text(email);
					
					if(uid == restore_details["uid"]) {
						$option.attr("selected", true);
					}
					
					$option.appendTo($select);
				});

				if(!empty(restore_details["os"])){
					$modal_form.find("#os_div").css("display", "");
					$modal_form.find("#os_notice").css("display", "");
					var $select = $modal_form.find("#osid");
				
					$.each(restore_details["os"], function(distro, oses) {
							$.each(oses, function(k, v){
								var $option = $("<option />").val(k)
								.text(v["name"]);
							
							$option.appendTo($select);
						});
					});
				}

				if(!empty(restore_details["iso"])){
					$modal_form.find("#iso_div").css("display", "");
					$modal_form.find("#os_notice").css("display", "");
					var $select = $modal_form.find("#iso");
					
					$.each(restore_details["iso"], function(k, v){
						var $option = $("<option />").val(k)
						.text(v["name"]);
					
						$option.appendTo($select);
					});
				}
				
				// Show dialog for user select
				$("#common_modal").modal("show");
				$("#common_modal .fhead").text("'.__J('Restore To New VPS').'");
				$("#common_modal_body").css("padding", "10px");
				$("#common_modal_body").html($modal_form);
				
				update_storage($modal_form.find(".newserid"));
				$(".virt-select, .ips_sel, .ips_int_sel").select2({
					width:"100%"
				});
				show_tooltip();
				//ajax user handling 
				load_ajax_user("uid", "'.$globals['index'].'act=vpsrestore&api=json&load_ajax_user=1");
			},
			complete: function(data) {
				$("#progress_bar").hide();
				$(table).show();
			}
		});
		
		return false;
	}

	function update_storage(el){
		var serid = $(el).val();
		var ui_new_storage = "";
		$.ajax({
			type: "POST",
			url: "'.$globals['index'].'act=vpsrestore&api=json",
			data: {
				update_storage: serid,
			},
			dataType : "json",
			success: function(data){
				var newstorage = data["newstorage"];
				ui_new_storage = "<select class=\"custom-select st_uuid\">";
				$.each(newstorage, function(k, v) {
					$.each(v, function(k, v){
						var label = "";
						if(empty(v["oversell"])){
							label="'.__J('Free').'";
						}else{
							label="";
						}
						ui_new_storage +="<option value="+v["st_uuid"]+">"+v["name"]+"&nbsp;("+v["free"]+" GB "+label+")";
					});
				});
				ui_new_storage += "</select>";
				var i = -1;
				$(".disk_row").each(function(){
					i++;
					$(this).find("#disk_div").html(ui_new_storage);
					$(this).find("#disk_div").find(".st_uuid").attr("name","st_uuid_"+i);
				});
			}
		});
	}
	
	function restore(el) {

		let post_data = $(el).closest("tr").data();
		post_data["restore"] = 1;
		
		showalert("'.__J('Are you sure you want to restore this ?').'" ,"3" ,function(confirm){
		
			if(confirm == false){
				return false;
			}

			$("#progress_bar").show();

			$.ajax({
				type: "POST",
				url: "'.$globals['index'].'act=vpsrestore&api=json",
				data: post_data,
				dataType : "json",
				success: function(data){
					if("restore_done" in data) {
						animate_task("'.__J('Restore task started').'");
						setTimeout(function(){showalert("'.__J('The restore process has been started and is running in the background.').'");
						refresh_tasks();} ,200);
					}
					
					if("error" in data) {
						setTimeout(function(){
							let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
							showalert(err ,"1");
							return false;
						}, 200)
					}
				},
				complete: function(data) {
					$("#progress_bar").hide();
				}
			});
		});
		
		return false;
	}
	
	function Delbackup(el){
		
		// List of ids to delete
		var backup_list = new Array();

		let attr = !empty($("#scan_dir:visible").val()) ? "file" : "bkid";
		
		if(!el){
			
			if($("#backup_task_select").val() != 1){
				showalert("'.__J('No action selected !').'" ,"1");
				return false;
			}
			
			$(".ios:checked").each(function() {
				backup_list.push($(this).closest("tr").data(attr));
			});
			
		} else {
			backup_list.push($(el).closest("tr").data(attr));
		}

		if(backup_list.length < 1){
			showalert("'.__J('Nothing selected !').'" ,"1");
			return false;
		}
		
		showalert("'.__J('Are you sure, you want to delete the selected item(s) ?').'" ,"3" ,function(confirm){
			
			if(confirm == false){
				return false;
			}

			$("#progress_bar").show();

			let post_data = {
				"delete" : 1,
			};
			
			post_data[attr] = backup_list.join(",");

			if(attr == "file"){

				if(!$("#scan_dir:visible").val()) {
					showalert("'.__('Please specify a valid backup directory').'" ,"1");
					return false;
				}

				post_data["serid"] = $("#serid").val();
				post_data["bid"] = $("#bid").val();
				post_data["dir"] = $("#scan_dir:visible").val();
				post_data["date"] = $("#date").val();
			}

			$.ajax({
				type: "POST",
				url: "'.$globals['index'].'act=vpsrestore&api=json",
				data : post_data,
				dataType : "json",
				success: function(data){

					if("delete_done" in data){
						setTimeout(function(){
							// Remove all deleted rows
							$.each(backup_list, function(key, value) {
								$("tr[data-file=\'" + value + "\']").remove();
							});
							refresh_tasks();
							showalert("'.__J('The backup(s) have been deleted successfully.').'");
							$("#restore_form").trigger("submit");
						}, 200);
						$("#restore_form").trigger("submit");
					}

					if("error" in data) {
						setTimeout(function(){
							let err = `<ul>${Object.values(data.error).map(e => `<li>${e}</li>`).join("")}</ul>`;
							showalert(err ,"1");
							return false;
						}, 200);
					}
				},
				complete: function() {
					$("#progress_bar").hide();
				}
			});
		});

		return false;
	}
	
	function refresh_note() {
		// Show note if no backups found
		if($("#table_backup_list tbody tr").length > 0 && $("#table_backup_list tbody tr").find(".dataTables_empty").length < 1) {
			$("#backup_list").show();
			$(".notice").hide();
		} else {
			$("#backup_list").hide();
			$(".notice span").text("'.__J('No backups found!').'");
			$(".notice").show();
		}
	}
	
	function refresh_tasks() {
		var cols = new Object();
		cols["actid"] = {"l" : "'.__J('Act ID').'", width: 60 ,"centered" : true};
		cols["vpsid"] = {"l" : "'.__J('VPS ID').'", width: 60, "centered" : true};
		cols["user"] = {"l" : "'.__J('User').'", "centered" : true};
		cols["server"] = {"l" : "'.__J('Server').' '.'('.__J('Id').')", "centered" : true};
		cols["started"] = {"l" : "'.__J('Started').'", width: 100, "centered" : true};
		cols["updated"] = {"l" : "'.__J('Updated').'", width: 100, "centered" : true};
		cols["ended"] = {"l" : "'.__J('Ended').'", width: 100, "centered" : true};
		cols["action_txt"] = {"l" : "'.__J('Action').'", width: 100};
		cols["status_txt"] = {"l" : "'.__J('Status').'", width: 200};
		cols["progress"] = {"l" : "'.__J('Progress').'"};
		cols["logs"] = {"l" : "'.__J('Logs').'", width: 80, "centered" : true};
		
		$.ajax({
			type: "GET",
			url: "'.$globals['index'].'act=tasks&action=restorevps_plan,backuply_restorevps_plan&api=json&page=0&reslen=20",
			dataType : "json",
			success: function(data){
				
				if(empty(data["tasks"])) {
					// Show no tasks note if table empty
					$("#table_tasks_container").html("<div class=\"notice\"><b>'.__J('Note').' : </b> &nbsp; '.__J('No Restore tasks found').'</div>");
					return;
				}
				
				var rows = Array();
				
				$.each(data["tasks"], function(k, task) {
					
					rows[k] = new Object();
					rows[k]["actid"] = task["actid"];
					rows[k]["vpsid"] = task["vpsid"];
					rows[k]["user"] = empty(task["uid"]) ? "root" : task["email"];
					rows[k]["server"] = task["server_name"] + "(" + task["serid"] + ")";
					rows[k]["started"] = task["started"];
					rows[k]["updated"] = task["updated"];
					rows[k]["ended"] = task["ended"];
					rows[k]["action_txt"] = task["action_txt"];
					rows[k]["status_txt"] = task["status_txt"];
					rows[k]["progress"] = "<div class=\"progress-cont\" id=\"progress-cont"+task["actid"]+"\"><center><div class\"text-center h6\" id=\"pbar"+task["actid"]+"\">"+task["progress"]+"%</center><div class=\"progress\"><div class=\"progress-bar bg-primary progress-bar-striped progress-bar-animated\" id=\"progressbar"+task["actid"]+"\"></div></div>";
					rows[k]["logs"] = "<button class=\"btn px-2 py-1\" onclick=\"loadlogs("+task["actid"]+");\">'.__J('Show').'</button>";
					
				});
				
				rows.sort(function(a, b){
					a = parseInt(a["actid"]);
					b = parseInt(b["actid"]);
					if(a < b) return 1;
					if(a > b) return -1;
					return 0;
				});
				
				table({"id" : "table_tasks_container", "tid" : "table_tasks", "width" : "100%"}, cols, rows);
				
				$.each(data["tasks"], function(index, task) {
					
					if(task["progress"] == 100){
						$("#status"+index).text("'.__J('Completed').'");
						$("#pbar"+index).text("100% '.__J('Completed').' !");
						$("#progressbar"+index).hide();
						$("#progressbar"+index).parent().css("border", "0px");
						$("#progressbar"+index).parent().removeClass("progress");
					}else if(task["status"] == -1){
						$("#status"+index).html(task["status_txt"]);
						$("#pbar"+index).text("'.__J('Task could not be Completed.').'");
						$("#progressbar"+index).hide();
						$("#progressbar"+index).parent().css("border", "0px");
						$("#progressbar"+index).parent().removeClass("progress");
					}else {
						if(isNaN(task["progress"])){
							$("#pbar"+index).text(task["progress"]);
							$("#progressbar"+index).hide();
						}else{
							make_progress(index, Number(task["progress"]));
							$("#progressbar"+index).show();
						}
					}
					
				});
				
			}
		});
		
	}

	function make_progress(index, progress){
		var steps = 20;
		var start = $("#pbar"+index).text();
		start = (start.slice(0, -1));
		if(isNaN(start)){
			start = 0;
		}
		var step = (progress - start)/steps;
		if(step < 0){ step = 0;}
		var increment = function(){
			var val = $("#pbar"+index).text();
			val = Number(val.slice(0, - 1));
			prog = parseInt(val + Math.round(step));
			//alert("progr"+prog);
			if(prog > progress){ prog = progress;}
			if(prog < parseInt("100")){
				$("#pbar"+index).text(prog + "%");
				$("#progressbar"+index).width(prog + "%");
			}else{
				$("#progressbar"+index).width(100 + "%");
			}
			if (prog < progress){setTimeout(increment, 500);}
		};
		increment();
	}

	function formatHTime(htime){
		let parts = htime.split("-");
		return parts[0].replace(/_/g, "/") + " " + parts[1].replace(/_/g, ":");
	}
		
	</script>
	
	<style type="text/css">

		.panel {
			min-height: 120px;
		}
		.panel-content {
			max-height: 400px;
			overflow: hidden;
		}
		.panel.panel-blue-grey {
			border-color: #607D8B;
		}
		.panel.panel-blue-grey .panel-heading {
			background-color: #607D8B;
			border-color: #607D8B;
			color: #fff;
		}
		.table-dash {
			margin-bottom: 4px;
		}
		.table-dash tbody tr td {
			vertical-align: middle;
		}
		.table-dash tr td:first-child, .table-dash tr th:first-child {
			padding-left: 16px;
		}
		.table-dash tr td:last-child, .table-dash tr th:last-child {
			padding-right: 16px;
		}
		.btn-logs {
			margin: 0;
			padding: 4px 8px;
			font-size: 12px;
		}
		#table_tasks_container table thead th{
			position:sticky;
			top:0px;
			padding:10px 5px !important;
		}
		.sorting_1 .text-warning {
			color: white !important;
		}

		table.backuply_table tbody tr, 
		.dark table.legacy_table tbody tr {
			background-color: var(--data-table-bg);
			color: var(--black);
		}
			
	</style>';

	echo '
	<div class="card p-2 mx-3">
		<form id="restore_form" name="restore_form">
			<input type="hidden" id="op" name="op" value="" />
			<input type="hidden" id="dir_input" name="dir" value="" />
			<input type="hidden" id="import_backup" name="import_backup" value="0" />
			<div class="row mx-auto w-100 pt-3">
				<div class="col-sm-4 p-0">';
				echo '<div class="row mx-auto w-100">
						<div class="col-sm-12">
							<label class="control-label">'.__('Select Server').'</label>
							<select id="serid" class="virt-select get-backups" name="serid">
								<option value="-1">Select</option>';
								foreach($servers as $k => $v) {
									if(($v['serid'] == 0) && !empty($globals['is_master_only'])) $v['virt'] = 'msonly';
									echo '<option value="'.$k.'" '.((!empty($_POST['serid']) && $_POST['server'] == $k) ? 'selected' : '').' data-virt="'.$v['virt'].'">'.$v['server_name'].' ('.$v['ip'].')'.($v['locked'] == 0 ? '' : ' (Locked)').'</option>';
								}
						echo '</select>
						</div>
					</div><br />
				</div>
				
				<div class="col-sm-4">
					<label class="control-label">'.__J('Select VPS').'</label><br>
					<select class="virt-select get-backups" name="vpsid" id="vps">
						<option value="0" selected="selected">'.__('Select').'</option>';
						foreach($vpses as $vpsid => $vps) {
							echo '<option value="'.$vpsid.'">[VID: '.(!empty($vps['vps_name']) ? $vps['vps_name'] : 'NA').'] [ID: '.$vpsid.'] ['.$vps['hostname'].']</option>';
						}
				echo '</select>
				</div>
				
				<div class="col-sm-4">
					<label class="control-label my-0">'.__J('Select Backup Server').'</label><br>
					<select class="virt-select get-backups" name="bid" id="bid">
						<option value="-1" selected="selected">'.__('Select').'</option>
						<option value="0">'.__J('Local').'</option>';
							
						foreach($backup_servers as $bid => $bs) {
							echo '<option value="'.$bid.'">'.$bs['name'].' ('.$bs['hostname'].')</option>';
						}
				echo '</select>
				</div>
			</div>

			<div class="row mx-auto w-100 py-2">
				<div class="col-sm-4">	
					<label class="control-label">'.__('Select Backup Directory').'</label><br>
					<select class="custom-select" id="dir">
						<option value="" selected="selected">'.__('Select').'</option>
					</select>
				</div>

				<div class="col-sm-4" id="row_date">		
					<label class="control-label">'.__('Select Backup Date').'</label><br>
					<select class="custom-select get-backups" name="date" id="date">
						<option value="" selected="selected">'.__('Select').'</option>
					</select>
				</div>
				
				<div class="col-sm-4">
					<label class="control-label">'.__('Select Backup Type').'</label><br>
					<div class="row mx-auto w-100 d-flex align-items-center pt-1">
						<div class="col-sm-6 p-0">
							<label class="custom-control custom-radio">
								<input type="radio" class="custom-control-input get-backups" name="backup_type" value="use_backuply" '.(has_plugin_license('backuply') ? 'checked="checked"' : '').'>
								<span class="custom-control-label">Use Backuply Backups</span>
							</label>
						</div>
						<div class="col-sm-6 p-0">
							<label class="custom-control custom-radio">
								<input type="radio" class="custom-control-input get-backups" name="backup_type" value="use_normal_backup">
								<span class="custom-control-label">Use Normal Backups</span>
							</label>
						</div>
					</div>
				</div>
			</div>
			
			<div class="row mx-auto w-100 my-3 mt-4" id="row_scan_dir" style="display:none">
				<div class="col-sm-6">
					<label class="control-label">'.__('Enter Backup Directory').'</label><br>
					<div class="input-group">
						<input id="scan_dir" name="scan_dir" type="text" class="form-control rounded">&nbsp;
						<span class="input-group-btn mx-2">
							<button id="scan" class="btn btn-default px-2 py-1" type="button">'.__('Scan Directory').'</button>
						</span>
						<span class="input-group-btn">
							<button id="import" class="btn btn-default px-2 py-1" type="button">'.__('Import Backups From').'</button>
						</span>
					</div>
				</div>
			</div>
		</form>
	
		<div id="restore-tab-card" class="col-lg-12 col-sm-6 col-md-6 px-lg-0 mb-3 blue_tab px-0 py-3">
			<div>
				<div class="mx-2">
					<ul class="nav nav-tabs" role="tablist">
						<li class="nav-item" role="presentation">
							<a class="nav-link w-100 active" id="tasks-tab" data-toggle="tab" href="#tasks-justified" role="tab" aria-controls="tasks" aria-selected="true" style="font-size: 16px;">
							<i class="icon icon-tasks float-left mr-1"></i>'.__('Last 20 Restore Tasks').'</a>
						</li>
						<li class="nav-item" role="presentation">
							<a class="nav-link w-100" id="backups-tab" data-toggle="tab" href="#backups-justified" role="tab" aria-controls="backups" aria-selected="false" style="font-size: 16px;">
							<i class="icon icon-databackup text-admin mr-1"></i> '.__('Backups').'</a>
						</li>
					</ul>
				</div>

				<div class="tab-content pt-2" id="restore-tab-content">
				
					<div class="tab-pane fade show active" id="tasks-justified" role="tabpanel" aria-labelledby="tasks-tab">
						<div class="row m-2 card p-3">
							<div class="col-sm-12 p-0">
								<div id="panel-tasks" class="">
									<div class="panel-content scrollbar-virt">
										<div id="table_tasks_container"><center><br><br><div class="loader-lg"></div></center></div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<div class="tab-pane fade" id="backups-justified" role="tabpanel" aria-labelledby="backups-tab">
						<div class="row m-2 card p-3">
							<div id="backup_list" style="display:none;" class="p-3">
								<div class="mx-auto sticky">
									<table id="table_backup_list" class="table table-hover legacy_table tablesorter" width="100%" cellspacing="1" cellpadding="8" border="0" align="center">
										<thead>
											<tr>
												<th align="center">Bkid</th>
												<th align="center">'.__('Name').'</th>
												<th width="100px" align="center">'.__('Size').'</th>
												<th class="min_width" align="center">'.__('Restore').'</th>
												<th width="140" align="center">'.__('Restore To New').'</th>
												<th width="140" align="center">'.__('Note').'</th>
												<th class="min_width" align="center">'.__('Delete').'</th>
												<th class="z-index-1 min_width" align="center">
													'.get_checkbox('select_all', '', 'select_all', array('chk_it' => 0), '', 'select_all').'
												</th>
											</tr>
										</thead>
										<tbody></tbody>
									</table>
								</div>
								<div class="row mx-auto w-100 mt-5">
									<div class="col-sm-4 col-lg-4 col-md-6 text-right mb-3">
										<div class="bottom-menu float-right w-100">
											<div class="row my-auto">
												<div class="p-0">
													<label>'.__('With Selected').'</label>
												</div>
												<div class="col p-0">
													<select name="backup_task_select" class="custom-select" id="backup_task_select">
														<option value="0">---</option>
														<option value="1">'.__('Delete').'</option>
													</select>
												</div>
												<div class="pl-2">
													<button type="submit" class="go_btn" id="backup_submit" name="backup_submit" onclick="Delbackup(); return false;">'.__('Go').'</button>
												</div>
											</div>
										</div>
									</div>
									<div class="col-sm-8 col-lg-8 col-md-6 mb-3 p-0">
									</div>
								</div>
							</div>

							<div class="row mx-auto w-100 py-4" id="backuply_div" style="display:none;">
								<div class="col-sm-12" id="backuply_table_div">
									<table class="table table-hover border-0 backuply_table common-table" width="100%" id="backuply_table_list">
										<thead>
											<tr class="table_heading">
												<th style="width:220px;" data-orderable="false"></th>
												<th>Bkid</th>
												<th>'.VM_SHORT.'</th>
												<th>'.__('Files').'</th>
												<th width="3%">'.__('Type').'</th>
												<th>'.__('Size').'</th>
												<th>'.__('Time').'</th>
												<th>'.__('Note').'</th>
												<th>'.__('Actions').'</th>
											</tr>
										</thead>
										<tbody></tbody>
									</table>
								</div>
							</div>

							<div id="no_backups" class="notice" style="display:none"><b>NOTE : </b>&nbsp;<span>'.__('No backups found!').'</span></div>

							<div id="progress_bar" style="display:none;">
								<br />
								<center>
									<font id="progress_txt" size="4">'.__('Please wait, Action in Progress.').'</font>
								</center>
								<div class="my-2" align="center">
									<div class="progress w-50">
										<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100">
										</div>
									</div>
								</div>
								<center>
									'.__('You will be notified once the Action is Completed.').'
								</center>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- for editing note -->
		<div id="bkp_edit_notePopover" class="popover-box shadow border" style="display:none;">
			<textarea id="bkp_edit_note" class="form-control mb-2" rows="5" maxlength="255" placeholder="'.__('Write your note...').'"></textarea>
			<div class="d-flex justify-content-around align-items-center">
				<input type="hidden" id="bkid" value="">
				<button id="bkp_editNote" class="btn btn-primary btn-sm me-1" onclick="bkp_editNote()">'.__('Save Changes').'</button>
				<button id="cancelNote" class="btn btn-cancel btn-sm" onclick="document.getElementById(\'bkp_edit_notePopover\').style.display=\'none\'">'.__('Cancel').'</button>
			</div>
		</div>
	</div>';

}// End of Server Offline if	

echo '</div>';
softfooter();

}

