import Alpine from "./alpine.module.esm.min.js";
import persist from './persist.module.esm.min.js';

Alpine.plugin(persist)
window.Alpine = Alpine

Alpine.data("main", () => ({
	/*
	passwordDialog
	*/
	isDialogSetPasswordOpen: false,
	password: '',
	confirm_password: '',
	isLoading: false,
	error: '',
	openDialogSetPassword(){
		this.isDialogSetPasswordOpen = true;
	},
	closeDialogSetPassword(){
		this.isDialogSetPasswordOpen = false;
	},
	savePassword(userid) {
		this.error = '';
		if(!this.password) { this.error = "Password is required"; return; }
		if(this.password !== this.confirm_password) { this.error = "Passwords do not match"; return; }
		this.isLoading = true;
		fetch(BASEURL + '/setPassword', {
			method: 'PATCH',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ userid: userid, password: this.password })
		})
		.then(res => res.json())
		.then(data => {
			this.isLoading = false;
			if(data.status === 'success') {
				alert('Password changed successfully');
				this.password = '';
				this.confirm_password = '';
				this.closeDialogSetPassword();				
			} else {
				this.error = data.message || 'Unknown error occurred';
			}
		})
		.catch(err => {
			this.isLoading = false;
			this.error = 'Network error occurred. Please try again.';
			console.error(err);
		});
	}
}));

export default Alpine;