$(document).ready(function(){
// $('.editUserBtn').click(function(evnt){

// });
	//
	console.log('foo bar');
	$('#editAllowedApps').select2({
		// width: "resolve",
		dropdownParent: $('#editUserModal'),
		placeholder : "Select options, multiple allowed"

	});

	$('#allowedApps').select2({
		// width: "resolve",
		dropdownParent: $('#addUserModal'),
		placeholder : "Select options, multiple allowed"
	});

	$('#inputPermissions').select2({
		// width: "resolve",
		dropdownParent: $('#editUserModal'),
		placeholder : "Select options, multiple allowed"
	});

	$('.editUserBtn').click(function(evnt){
		evnt.preventDefault();
		var selectedUserId = $(this).siblings('.userIdinput').val();

		const formData = new FormData();
		formData.append('user_id', selectedUserId);

		$.ajax({
		    url: base_url + '/users/edit/' + selectedUserId,
		    type: 'GET',
		    processData: false,
		    contentType: false,
		    beforeSend: function() {
		    	$('#editSuccessArea').text("");
				$('#editErrorArea').text("Please wait ... loading user details!");
		  	},
		    success: function(data) {
		    	var jason = data.data;
		        if(data.success == true){
		        	var allowedAppsArray = [];
	            	if (jason['allowed_apps']) {
	              		allowedAppsArray = jason['allowed_apps'].split(",");
	            	}
	            	console.log(jason['full_name']);
			      	$('#editFullName').val(jason['full_name']);
		          	$('#editEmail').val(jason['email']);
		          	$('#editUsername').val(jason['username']);
		          	$('#editGender').val(jason['gender']);
		          	$('#editTitle').val(jason['title']);
		          	$('#editUaPostion').val(jason['ua_position']);
		          	$('#editPhone').val(jason['phone']);
		          	$('#editAllowedApps').val(allowedAppsArray).trigger('change');
		          	$('#editRegionID').val(jason['region_id']);
		          	$('#editDistrictId').val(jason['district_id']);
		          	$('#editUaPostion').val(jason['ua_position']);
		          	$('#editGender').val(jason['gender']);  
		          	$("input[name='user_id']").val(jason.ua_id);       
		          	          
	          }
	          //$('#editUserModal').modal('show');
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		        $('#errorArea').text(error);
				$('#errorArea').text(error);
		    }
		});

	});

	$('.viewUserBtn').click(function(evnt){
		evnt.preventDefault();
		var selectedUserId = $(this).siblings('.userIdinput').val();

		const formData = new FormData();
		formData.append('user_id', selectedUserId);

		$.ajax({
		    url: base_url + '/users/' + selectedUserId,
		    type: 'GET',
		    processData: false,
		    contentType: false,
		    beforeSend: function() {
		    	$('#viewSuccessArea').text("");
				$('#viewErrorArea').text("Please wait ... loading user details!");
		  	},
		    success: function(data) {
		    	var jason = data.data;
		        if(data.success == true){
		        	var allowedAppsArray = [];
	            	if (jason['allowed_apps']) {
	              		allowedAppsArray = jason['allowed_apps'].split(",");
	            	}
	            	console.log(jason['full_name']);
			      	$('#viewFullName').val(jason['full_name']);
		          	$('#viewEmail').val(jason['email']);
		          	$('#viewUsername').val(jason['username']);
		          	$('#viewGender').val(jason['gender']);
		          	$('#viewTitle').val(jason['title']);
		          	$('#viewUaPostion').val(jason['ua_position']);
		          	$('#viewPhone').val(jason['phone']);
		          	$('#viewAllowedApps').val(allowedAppsArray).trigger('change');
		          	$('#viewRegionID').val(jason['region_id']);
		          	$('#viewDistrictId').val(jason['district_id']);
		          	$('#viewUaPostion').val(jason['ua_position']);
		          	$('#viewGender').val(jason['gender']);  
		          	$("input[name='user_id']").val(jason.ua_id);       
		          	          
	          }
	          //$('#editUserModal').modal('show');
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		        $('#errorArea').text(error);
				$('#errorArea').text(error);
		    }
		});

	});

	$("#newUserForm").submit(function(evt){
		evt.preventDefault();
		$('#successArea').addClass('d-none');
		$('#errorsArea').removeClass('d-none');
		var formData = new FormData($(this)[0]);

		$.ajax({
		    url: base_url + '/users',
		    type: 'POST',
		    data: formData,
		    processData: false,
		    contentType: false,
		    beforeSend: function() {
		  		$('#successArea').text("");
				$('#successArea').text("Please wait ... user creation in progress!");
		  	},
		    success: function(data) {

		        if (data['success'] == true) {
			        $('#successArea').removeClass('d-none');
		        	$('#errorsArea').addClass('d-none');
		        	
					$('#successArea').text("");
					$('#successArea').text("User successfully created!");
					// location.reload();
					setTimeout(function() {
			            location.reload(); // Reloads the current page
			        }, 15000);
				}
				else{
					$('#successArea').addClass('d-none');
		        	$('#errorArea').removeClass('d-none');
					$('#errorArea').text("");
					$('#errorArea').text("User could not be created!");
				}
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		        $('#successArea').text(error);
				$('#successArea').text(error);
		    }
		});
	});

	$("#editUserForm").submit(function(evt){
		evt.preventDefault();
		$('#successArea').addClass('d-none');
		$('#errorsArea').removeClass('d-none');
		var formData = new FormData($(this)[0]);
		$.ajax({
		    url: base_url + '/users/update/',
		    type: 'POST',
		    data: formData,
		    processData: false,
		    contentType: false,
		    beforeSend: function() {
		  		// $('#updateBtn').addClass('d-none');
					// $('#uodateProgressBtn').removeClass('d-none');
					// $('#updateResultsDiv').removeClass('d-none');
					// $('#updateResultsParagraph').text("Processing Please wait ...");
		  	},
		    success: function(data) {
		        console.log(data);
		        $('#editSuccessArea').removeClass('d-none');
	        	$('#editErrorArea').addClass('d-none');
						$('#editSuccessArea').text("");
						$('#editSuccessArea').text("User successfully details updated!");

		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		        $('#editSuccessArea').text(error);
						$('#editErrorArea').text(error);
						location.reload();
		    }
		});
	});

	$('#regionID').change(function(){
	      var options = $('#districtID');
	      var region_id = $('#regionID').val();	      
	      $.get( base_url + '/admin/districts/' + region_id, function (data) {
	          $('#districtID').empty();
	          $.each(data['districts'], function(id, row) {
	              $('#districtID').append($("<option />").val(row.districtid).text(row.district_name));
	          });
	      });
	});



});
