$(document).ready(function () {

    let iti;
  	
    $('#editUserModal').on('shown.bs.modal', function () {
        const phoneInput = document.querySelector("#editPhone");
        if (!iti) {
            iti = window.intlTelInput(phoneInput, {
                initialCountry: "gh",
                onlyCountries: ["gh"],
                nationalMode: false,       
                autoPlaceholder: "polite",
                utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/utils.js"
            });

            phoneInput.addEventListener("blur", function () {
			    let rawNumber = phoneInput.value.trim();
			    console.log(rawNumber);
			    if (rawNumber.startsWith("0")) {
			        rawNumber = rawNumber.substring(1);
			        phoneInput.value = "+233" + rawNumber;
			    }
			    if (iti.isValidNumber()) {
			        phoneInput.value = iti.getNumber(); // clean +233XXXXXXXXX
			    }
			});
        }
    });

    $('#addUserModal').on('shown.bs.modal', function () {
        const phoneInput = document.querySelector("#addUserphone");
        if (!iti) {
            iti = window.intlTelInput(phoneInput, {
                initialCountry: "gh",
                onlyCountries: ["gh"],
                nationalMode: false,       
                autoPlaceholder: "polite",
                utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/utils.js"
            });

            phoneInput.addEventListener("blur", function () {
			    let rawNumber = phoneInput.value.trim();

			    if (rawNumber.startsWith("0")) {
			        rawNumber = rawNumber.substring(1);
			        phoneInput.value = "+233" + rawNumber;
			    }
			    if (iti.isValidNumber()) {
			        phoneInput.value = iti.getNumber();
			    }
			});
        }
    });
    
    let lastTrigger = null;
    // $(document).on('click', '.editBtnXX', function(){
    //   lastTrigger = this;
    //   const row = $(this).closest('.user-row');
    //   $('#editId').val(row.data('id'));
    //   $('#editName').val(row.data('name'));
    //   $('#editEmail').val(row.data('email'));
    //   $('#editCategory').val(row.data('category'));
    // });
    // When edit modal closes, return focus to trigger
    $('#editUserModal').on('hidden.bs.modal', function(){
      if (lastTrigger && document.contains(lastTrigger)) lastTrigger.focus();
      lastTrigger = null;
    });

    // Submit edit (updates row inline)
    $('#editFormXX').on('submit', function(e){
      e.preventDefault();
      const id = $('#editId').val();
      const name = $('#editName').val();
      const email = $('#editEmail').val();
      const category = $('#editCategory').val();

      const row = $(`.user-row[data-id="${id}"]`);
      row.data('name', name).data('email', email).data('category', category);
      row.find('.fw-semibold').text(name);
      row.find('td').eq(2).text(email);
      row.find('.category-badge').removeClass('badge-district badge-regional badge-national');
      if (category === 'District') row.find('.category-badge').addClass('badge-district').text('District');
      if (category === 'Regional') row.find('.category-badge').addClass('badge-regional').text('Regional');
      if (category === 'National') row.find('.category-badge').addClass('badge-national').text('National');
      const targetBody = category === 'District' ? '#districtBody' : (category === 'Regional' ? '#regionalBody' : '#nationalBody');
      if (!row.parent().is(targetBody)) {
        row.appendTo($(targetBody));
      }

      updateCounts();
      $('#editModal').modal('hide');
    });


    var selectedValue = $("input[name='user_type']:checked").val();
	const $dropdown = $("#uaPostionAdd");
	    
	    const optionsMap = {
	        district_user: [
	        	"PPD Head", "Works Head",  "MIS",
	        	"PPD Staff", "Works Staff", 
	        	"Devt Planning Officer",
	        	"MCE", "DCE",
	        	"Urban Roads Department Head",
	        	"District Fire Officer",
	        	"District Disaster Prevention Department",
	        	"Head of District Health Department",
	        	"Representative of the Lands Commission",
	        	"Representative of the Environmental Protection Agency",
	        	"Rep from Traditional Council",
	        	"Chairman of the Works Sub Committee",
	        	"Chairman of Development Sub Planning Committee",
	        	"Nominated Elected Assembly Memebers"
	        ],
	        national_luspa: ["Director", "IT Head", "Staff"],
	        regional_luspa: ["Director", "Staff"]
			
	    };
	    $dropdown.empty();
        $dropdown.append('<option value="">-- Select an option --</option>');

        if (optionsMap['district_user']) {
            $.each(optionsMap['district_user'], function(index, value) {
                $dropdown.append($("<option></option>").attr("value", value.toLowerCase()).text(value));
            });
        }

	$("input[name='user_type']").change(function() {
	    var userValue = $(this).val();   
   		if (userValue == 'district_user') {
   			$('#regionID').prop('disabled', false);
   			$('#districtID').prop('disabled', false);

   			$('#editRegionID').prop('disabled', false);
   			$('#editdistrictID').prop('disabled', false);

   		}
   		if (userValue == 'national_luspa') {
   			$('#regionID').prop('disabled', true);
   			$('#districtID').prop('disabled', true);

   			$('#editRegionID').prop('disabled', true);
   			$('#editdistrictID').prop('disabled', true);

   		}
   		if (userValue == 'regional_luspa') {
   			$('#districtID').prop('disabled', true);
   			$('#regionID').prop('disabled', false);

   			$('#editdistrictID').prop('disabled', true);
   			$('#editRegionID').prop('disabled', false);

   		}

        $dropdown.empty();
        $dropdown.append('<option value="">-- Select an option --</option>');

        if (optionsMap[userValue]) {
            $.each(optionsMap[userValue], function(index, value) {
                $dropdown.append($("<option></option>")
                    .attr("value", value.toLowerCase())
                    .text(value));
            });
        }

	});

	

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

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

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

	$('.editUserBtn').click(function(evnt){
		evnt.preventDefault();
		// var selectedUserId = $(this).siblings('.userIdinput').val();
		const row = $(this).closest('.user-row');
		var selectedUserId = row.data('id');
		console.log('selectedUserId');
		lastTrigger = this;
      	
      	// $('#editId').val(row.data('id'));
		
		const formData = new FormData();
		formData.append('user_id', selectedUserId);

		$.ajax({
		    url: base_url + '/users/edit/' + selectedUserId,
		    type: 'GET',
		    processData: false,
		    contentType: false,
		    headers: {
		        'X-Requested-With': 'XMLHttpRequest',
		        'crossDomain': false
		    },
		    beforeSend: function() {
		    	$('#editSuccessArea').text("");
				$('#editErrorArea').text("Please wait ... loading user details!!");
		  	},
		    success: function(data) {
		    	$('#editErrorArea').text('');
		    	var jason = data.data;
		        if(data.success == true){
		        	var allowedAppsArray = [];
	            	if (jason['allowed_apps']) {
	              		allowedAppsArray = jason['allowed_apps'].split(",");
	            	}
			      	$('#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.user_id);       
		          	          
	          }
	          //$('#editUserModal').modal('show');
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		        $('#errorArea').text(error);
				$('#errorArea').text(error);
		    }
		});

	});
	$("#editUserForm").submit(function(evt){
		evt.preventDefault();
		const $successArea = $("#editSuccessArea");
        const $errorArea = $("#editErrorArea");
		$('#editSuccessArea').addClass('d-none');
		$('#editErrorArea').removeClass('d-none');

		const formData = new FormData($(this)[0]);
		 // formData = new FormData(this);
		let errors = [];
        if (iti) {
		    let formattedPhone = iti.getNumber();
		    if (formattedPhone.startsWith("+2330")) {
		        formattedPhone = "+233" + formattedPhone.substring(5);
		    }
		    formattedPhone = formattedPhone.trim();
		    if (!iti.isValidNumber()) {
		        errors.push("001 | Please enter a valid Ghana phone number.");
		    } else {
		        formData.set("phone", formattedPhone);
		    }
		}
        const username = $("#editUsername").val().trim();
        const email = $("#editEmail").val().trim();
        const fullName = $("#editFullName").val().trim();

        if (!fullName) errors.push("Full name is required.");
        if (!username) errors.push("Username is required.");
        if (!email) {
            errors.push("Email is required.");
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            errors.push("Invalid email format.");
        }

        if (errors.length > 0) {
            $('#editSuccessArea').addClass("d-none").text("");
            $errorArea.removeClass("d-none").html(errors.join("<br>"));
            return;
        }

		
		$.ajax({
		    url: base_url + '/userupdate',
		    type: 'POST',
		    data: formData,
		    dataType: 'json', 
		    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);
		        console.log(data['success']);
		        if (data['success'] == true) {
		        	$('#editSuccessArea').removeClass('d-none');
		        	$('#editErrorArea').addClass('d-none');
					$('#editSuccessArea').text("");
					$('#editSuccessArea').text("User successfully details updated!");	
					$.alert({
	                    title: 'Alert!',
	                    content: 'User successfully details updated!!',
	                });
	                setTimeout(() => location.reload(), 2000);
		        }
		        else{
		        	$('#editErrorArea').removeClass('d-none');
					$('#editErrorArea').text(data['msg']);
					$.alert({
	                    title: 'Alert!',
	                    content: data['msg'],
	                });
		        }
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		       	$('#editErrorArea').removeClass('d-none');
				$('#editErrorArea').text(error);
				
		        if (xhr.status === 422) {
		            // Laravel validation error
		            let errors = xhr.responseJSON.errors;
		            let messages = [];

		            $.each(errors, function (field, msgs) {
		                messages.push(msgs.join("<br>"));
		            });

		            $('#editErrorArea').removeClass("d-none").html(messages.join("<br>"));

		            $.alert({
		                title: "Validation Error",
		                content: messages.join("<br>"),
		            });
		        } else {
		            $('#editErrorArea').removeClass('d-none').text("Request failed : " + error);

		            $.alert({
		                title: "Error",
		                content: "Request failed: " + error,
		            });
		        }
		    }
		});
	});
	$('#regionID').change(function(){
		console.log('change is coming');
      	var options = $('#districtID');
      	var region_id = $('#regionID').val();	      
      	$.ajax({
		    url: base_url + '/admin/districts/' + region_id,
		    type: 'GET',
		    headers: {
		        'X-Requested-With': 'XMLHttpRequest',
		        'crossDomain': false
		    },
		    success: function(data) {
		        $.each(data['districts'], function(id, row) {
		            $('#districtID').append($("<option />").val(row.districtid).text(row.district_name));
		        });
		    },
		    error: function(xhr, status, error) {
		        console.error('Error:', error);
		    }
		});
	});





    $("#newUserForm").on("submit", function (evt) {
	    evt.preventDefault();

	    const $successArea = $("#newUserSuccessArea");
        const $errorArea = $("#newUserErrorArea");
        const formData = new FormData(this);

        let errors = [];
        if (iti) {
		    let formattedPhone = iti.getNumber(); // +233XXXXXXXXX
		    if (formattedPhone.startsWith("+2330")) {
		        formattedPhone = "233" + formattedPhone.substring(5);
		    }

		    if (!iti.isValidNumber()) {
		        errors.push("Please enter a valid Ghana phone number.");
		    } else {
		        formData.set("phone", formattedPhone);
		    }
		}
        const username = $("#addUserUsername").val().trim();
        const email = $("#addUserEmail").val().trim();
        const fullName = $("#addUserFullname").val().trim();

        if (!fullName) errors.push("Full name is required.");
        if (!username) errors.push("Username is required.");
        if (!email) {
            errors.push("Email is required.");
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            errors.push("Invalid email format.");
        }

        if (errors.length > 0) {
            $successArea.addClass("d-none").text("");
            $errorArea.removeClass("d-none").html(errors.join("<br>"));
            return;
        }

	    $successArea.addClass("d-none").text("");
	    $errorArea.addClass("d-none").text("");

	    $.ajax({
		    url: base_url + "/users",
		    type: "POST",
		    data: formData,
		    processData: false,
		    contentType: false,
		    headers: {
		        "Accept": "application/json", 
		        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content')
		    },
		    beforeSend: function () {
		        $successArea.removeClass("d-none").text("Please wait ... user creation in progress!");
		    },
		    success: function (data) {
		        if (data.success) {
		            $successArea.removeClass("d-none").text("User successfully created!");
		            $errorArea.addClass("d-none");

		            $.alert({
		                title: "Success",
		                content: "User successfully created!",
		            });

		            setTimeout(() => location.reload(), 2000);
		        } else {
		            $successArea.addClass("d-none");
		            $errorArea.removeClass("d-none").text(data.msg || "An error occurred.");

		            $.alert({
		                title: "Error",
		                content: data.msg || "An error occurred.",
		            });
		        }
		    },
		    error: function (xhr, status, error) {
		        $successArea.addClass("d-none");

		        if (xhr.status === 422) {
		            // Laravel validation error
		            let errors = xhr.responseJSON.errors;
		            let messages = [];

		            $.each(errors, function (field, msgs) {
		                messages.push(msgs.join("<br>"));
		            });

		            $errorArea.removeClass("d-none").html(messages.join("<br>"));

		            $.alert({
		                title: "Validation Error",
		                content: messages.join("<br>"),
		            });
		        } else {
		            // Other errors
		            $errorArea.removeClass("d-none").text("Request failed: " + error);

		            $.alert({
		                title: "Error",
		                content: "Request failed: " + error,
		            });
		        }
		    },
		});

	});
});