/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */

$(function(){

	//initialize tippy dropdown for share report / sort widgets
	tippy('#mf_share_report_button', {
		content: function(element){
			return document.getElementById('mf_share_report_content').innerHTML;
		},
		placement: 'bottom',
		onShown: function(instance){
			//bind event handlers to all links within the tooltip
			bind_sort_widgets_event();
			bind_share_report_link();
			bind_unshare_report_link();
		},
		trigger: 'click',
		interactive: true,
		ignoreAttributes: true,
		arrow: true
	});

	var widget_list = document.getElementById('mf_folder_list');
	var form_id 	= $("#mf_folder_list").data("formid");

	//build the widget list sorting
	if(widget_list != null){
		var sortable = Sortable.create(widget_list, {
						animation: 150,
						ghostClass: 'folder_move_highlight',
						onEnd: function(){
							var widget_pos = this.toArray();

							axios.post('save_widgets_position.php', {
								widget_positions: widget_pos,
								form_id: form_id
							})
							.then(function (response) {
								if(response.data.status == 'ok'){
									//display notifications on success
									Swal.fire({
									  toast: true,
									  position: 'center',
									  icon: 'success',
									  title: 'Widgets position saved',
									  showConfirmButton: false,
									  timer: 2000
									});
								}else if(response.data.status == 'session_expired'){
									Swal.fire({
										width: '30%',
										position: 'center',
										icon: 'warning',
										title: response.data.expiry_title,
										html: response.data.expiry_message,
										showConfirmButton: true,
										showCancelButton: false,
										confirmButtonText: 'Sign In Again',
										allowOutsideClick: false
									}).then((result) => {
										if(result.isConfirmed) {
											window.location.replace('index.php?from=' + btoa(window.location.pathname + window.location.search));
										}
									});
								}else{
									alert('Error: ' + response.data);
								}
							})
							.catch(function (error) {
								alert(error);
							});
						}
				   });
	}


	//attach event to the 'Sort Widgets' cancel link
	$("#report_sort_pane_cancel").on('click',function(){
		$("#report_sort_pane_apply").hide();
		$("#mf_folder_list").hide();
		$("#mr_report_list").show();
			
		if($("#mr_report_shared_span > a").length > 0){
			$("#mr_report_shared").show();
		}
		
		var form_id 	= $("#mf_folder_list").data("formid");
		window.location.replace('manage_report.php?id=' + form_id);

		return false;
	});
	

	//attach event to the Delete widget icon
	$("#mr_report_list").on('click', 'a.delete_icon', function(e) {
		var temps 	 = $(this).attr("id").split('_');
		var chart_id = temps[1];
		var form_id  	= $("#mf_folder_list").data("formid");
		var csrf_token  = $("#content").data("csrftoken");
		
		Swal.fire({
			title: 'Are you sure you want to delete this widget?',
			html: 'Only this widget will be deleted. Any related data will remain intact.',
			footer: 'This action cannot be undone.',
			icon: 'warning',
			width: '40%',
			customClass: {
				htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom',
				footer: 'swal2-footer-warning',
				title: 'swal2-title-warning'
			},
			showCancelButton: true,
			confirmButtonText: 'Yes. Delete this widget.',
			showLoaderOnConfirm: true,
			preConfirm: () => {
				return axios.post('delete_widget.php', {
					form_id: form_id,
					chart_id: chart_id,
					csrf_token: csrf_token
				})
				.then(function (response) {
					if(response.data.status == 'ok'){
						
						$("#li_" + response.data.chart_id).fadeOut(function(){
							$(this).remove();
						});
						$("#widget_" + response.data.chart_id).remove();

						 //remove the widget from the sortable list
						 $("#li_widget_" + chart_id).remove();

						return response;
					}else if(response.data.status == 'session_expired'){
						Swal.fire({
							width: '30%',
							position: 'center',
							icon: 'warning',
							title: response.data.expiry_title,
							html: response.data.expiry_message,
							showConfirmButton: true,
							showCancelButton: false,
							confirmButtonText: 'Sign In Again',
							allowOutsideClick: false
						}).then((result) => {
							if(result.isConfirmed) {
								window.location.replace('index.php?from=' + btoa(window.location.pathname + window.location.search));
							}
						});
					}else{
						Swal.showValidationMessage('Error: Unable to process. Please try again later.');
					}
				})
				.catch(function (error) {
					Swal.showValidationMessage("Error: " + error);
				})
			},
			allowOutsideClick: () => !Swal.isLoading()
		});
		
		return false;
	});

	//attach event to the Duplicate widget icon
	$("#mr_report_list").on('click', 'a.duplicate_icon', function(e) {
		var temps 	 = $(this).attr("id").split('_');
		var current_chart_id = temps[1];
		var current_form_id  = $("#mf_folder_list").data("formid");
		var csrf_token  = $("#content").data("csrftoken");

		if($(this).text() == 'Duplicating...'){
			return false; //prevent the user from clicking multiple times
		}

		//change the 'Duplicate' text
		$(this).html('<span class="icon-files" style="margin-right: 5px;font-size: 120%"></span>Duplicating...');
			
		//do the ajax call to duplicate the widget
		axios.post('duplicate_widget.php', {
			form_id: current_form_id,
			chart_id: current_chart_id,
			csrf_token: csrf_token
		})
		.then(function (response) {
				if(response.data.status == 'ok'){
					window.location.replace('manage_report.php?id=' + response.data.form_id);
				}else if(response.data.status == 'session_expired'){
					Swal.fire({
						width: '30%',
						position: 'center',
						icon: 'warning',
						title: response.data.expiry_title,
						html: response.data.expiry_message,
						showConfirmButton: true,
						showCancelButton: false,
						confirmButtonText: 'Sign In Again',
						allowOutsideClick: false
					}).then((result) => {
						if(result.isConfirmed) {
							window.location.replace('index.php?from=' + btoa(window.location.pathname + window.location.search));
						}
					});
				}else{
					Swal.fire({
						width: '30%',
						position: 'center',
						icon: 'error',
						title: 'Error. Unable to complete the task.',
						html: response.data,
						showConfirmButton: false,
						showCancelButton: true,
						cancelButtonText: 'Close',
						allowOutsideClick: true
					});
				}
		})
		.catch(function (error) {
				Swal.fire({
					width: '30%',
					position: 'center',
					icon: 'error',
					title: 'Error. Unable to complete the task.',
					text: 'Unexpected error occurred. Please try again later.',
					showConfirmButton: false,
					showCancelButton: true,
					cancelButtonText: 'Close',
					allowOutsideClick: true
				});
		});

		return false;
	});


});

//attach event to the sort widgets link on the tooltip
function bind_sort_widgets_event(){
	//attach event to the 'Sort Widgets' dropdown
	$("#sort_widget_link").on('click',function(){
		$("#mr_report_list,#mr_report_shared").hide();
		$("#mf_folder_list").slideDown(function(){
			$("#report_sort_pane_apply").show();
		});

		$('#mf_share_report_button')[0]._tippy.hide();

		//we need to unbind the event, otherwise it will add up each time the tooltip displayed
		$("#sort_widget_link").off("click");

		return false;
	});
}

function bind_share_report_link(){
	//attach event to the Share This Report link
	$("#share_report_link").on('click',function(){
		var form_id  	= $("#mf_folder_list").data("formid");
		var csrf_token  = $("#content").data("csrftoken");

		Swal.fire({
			title: 'This report will be made public',
			html: 'Anyone with the link can access it; no sign-in is required.',
			icon: 'warning',
			width: '35%',
			customClass: {
				htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom',
				title: 'swal2-title-warning'
			},
			showCancelButton: true,
			confirmButtonText: '<span class="icon-link4"></span> Yes. Share this report.',
			showLoaderOnConfirm: true,
			preConfirm: () => {
				return axios.post('share_report.php', {
					form_id: form_id,
					csrf_token: csrf_token
				})
				.then(function (response) {
					if(response.data.status == 'ok'){
						$("#li_share_report").hide();
						$("#li_unshare_report").show();

						$("#mr_report_shared_span").html(response.data.report_link);
						$("#mr_report_shared").slideDown();

						return response;
					}else if(response.data.status == 'session_expired'){
						Swal.fire({
							width: '30%',
							position: 'center',
							icon: 'warning',
							title: response.data.expiry_title,
							html: response.data.expiry_message,
							showConfirmButton: true,
							showCancelButton: false,
							confirmButtonText: 'Sign In Again',
							allowOutsideClick: false
						}).then((result) => {
							if(result.isConfirmed) {
								window.location.replace('index.php?from=' + btoa(window.location.pathname + window.location.search));
							}
						});
					}else{
						Swal.showValidationMessage('Error: Unable to process. Please try again later.');
					}
				})
				.catch(function (error) {
					Swal.showValidationMessage("Error: " + error);
				})
			},
			allowOutsideClick: () => !Swal.isLoading()
		});

		//we need to unbind the event, otherwise it will add up each time the tooltip displayed
		$("#share_report_link").off("click");
		
		return false;
	});
}

function bind_unshare_report_link(){
	//attach event to the Unshare Report link
	$("#unshare_report_link").on('click',function(){
		var form_id  	= $("#mf_folder_list").data("formid");
		var csrf_token  = $("#content").data("csrftoken");

		Swal.fire({
			title: 'This report will be made private',
			html: 'No one else will be able to view it anymore.',
			icon: 'warning',
			width: '35%',
			customClass: {
				htmlContainer: 'swal2-html-container-bold swal2-html-container-padding-bottom',
				title: 'swal2-title-warning'
			},
			showCancelButton: true,
			confirmButtonText: '<span class="icon-unlink4"></span> Yes. Unshare this report.',
			showLoaderOnConfirm: true,
			preConfirm: () => {
				return axios.post('unshare_report.php', {
					form_id: form_id,
					csrf_token: csrf_token
				})
				.then(function (response) {
					if(response.data.status == 'ok'){
						$("#li_share_report").show();
						$("#li_unshare_report").hide();

						$("#mr_report_shared").slideUp();

						return response;
					}else if(response.data.status == 'session_expired'){
						Swal.fire({
							width: '30%',
							position: 'center',
							icon: 'warning',
							title: response.data.expiry_title,
							html: response.data.expiry_message,
							showConfirmButton: true,
							showCancelButton: false,
							confirmButtonText: 'Sign In Again',
							allowOutsideClick: false
						}).then((result) => {
							if(result.isConfirmed) {
								window.location.replace('index.php?from=' + btoa(window.location.pathname + window.location.search));
							}
						});
					}else{
						Swal.showValidationMessage('Error: Unable to process. Please try again later.');
					}
				})
				.catch(function (error) {
					Swal.showValidationMessage("Error: " + error);
				})
			},
			allowOutsideClick: () => !Swal.isLoading()
		});

		//we need to unbind the event, otherwise it will add up each time the tooltip displayed
		$("#unshare_report_link").off("click");
		
		return false;
	});
}