jQuery(document).ready(function(){
	jQuery(document).on('change', '#sregion', function(e){
		var elmObj = jQuery(this);
		var regionId = jQuery(this).val();
		
		var route = getCust = getUser = "0";
		
		if(jQuery('#sroute').length){
			route = "1";
		}
		
		if(jQuery('#scustomer').length){	
			getCust = 1;
		}
		
		if(jQuery('#user').length){	
			getUser = 1;
		}
		
		var divisionId = 0;
		if(jQuery('#sdivision').length){
			divisionId = jQuery('#sdivision').val();
		}
		
		var  eoptionsel = jQuery(this).attr('data-val');
		
		jQuery.ajax({
			type: 'POST',
			url: siteUrl+'stocks/getModelOptions.json',
			data: {reModel:'Depot', region:regionId, route:route , division:divisionId, eoption:eoptionsel, getCust:getCust, getUser:getUser},
			dataType: 'json',
			beforeSend: function(){
				elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
			},
			success: function(data){
				jQuery('.loading').remove();
				$('#sdepot').fillSelect(data.options);
				/* if(jQuery('#scustomer').length){	
					$('#scustomer').fillSelect(data.customers);
				} */
				if(eoptionsel=='setsel'){
                    $('#sdepot').prepend('<option value="" selected>Select Depot</option>');
                }
				if(jQuery('#sroute').length && data.routes){
					$('#sroute').fillSelect(data.routes);
					
					if(eoptionsel=='setsel'){
						$('#sroute').prepend('<option value="" selected>Select Route</option>');
					}
				}
				if(jQuery('#user').length && data.users){
					$('#user').fillSelect(data.users);
					
					if(jQuery('#role').length){
						$('#role option:first').prop('selected', true);  // This ensures the first option is selected
					}
				}

			},
			statusCode: {
				404: function() {
					alert( message.noPage );
				}
			}
		});
		
		if (window.location.href.indexOf("verified") > -1) {
			var verifiedVal = 0;
			var url_string = window.location.href;
			var url = new URL(url_string);
			var verified = url.searchParams.get("verified"); 
			if(verified == 1){
				verifiedVal = 1;
			}
			
			if(jQuery('#user').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'region/getUser.json',
				data: {region:regionId, verified:verifiedVal},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					$('#user').fillSelect(data.users); 
					
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
		}
	});
	
	
	jQuery(document).on('change', '#sdepot', function(e){ 
		var elmObj = jQuery(this);
		var depotId = jQuery(this).val();
		var  eoptionsel = jQuery(this).attr('data-val');
		
		if(jQuery('#sroute').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'routes/getRoute.json',
				data: {depot:depotId, eoption:eoptionsel},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					$('#sroute').fillSelect(data.routes);
					if(eoptionsel=='setsel'){
                    	$('#sroute').prepend('<option value="" selected>Select Route</option>');
					}
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	//State and LGA
	
	jQuery('#lg-state').change(function(){
		var elmObj = jQuery(this);
		var stateId = jQuery(this).val();
		jQuery.ajax({
			type: 'POST',
			url: siteUrl+'region/getLgaOptions.json',
			data: {reModel:'LgArea', state:stateId },
			dataType: 'json',
			beforeSend: function(){
				elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
			},
			success: function(data){
				jQuery('.loading').remove();
				$('#lg-area').fillSelect(data.options);
			},
			statusCode: {
				404: function() {
					alert( message.noPage );
				}
			}
		});
	});
	
	jQuery(document).on("click", '.verify-it',  function(){
		
		var elmObj = jQuery(this);
		var mId = jQuery(this).attr('id');
		var mdl = jQuery(this).attr('mdl');
		if(confirm(message.confirmContinue)){
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'reports/do_verify',
				data: {mdl:mdl, mId:mId, 'unverify':0 },
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					jQuery(elmObj).parent('div').html(data);
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	jQuery(document).on("click", '.unverify-it', function(){		
		var elmObj = jQuery(this);
		var mId = jQuery(this).attr('id');
		var mdl = jQuery(this).attr('mdl');
		if(confirm(message.confirmContinue)){
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'reports/do_verify',
				data: {mdl:mdl, mId:mId, 'unverify':1 },
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					jQuery(elmObj).parent('div').html(data);
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	jQuery(document).on("click", '.verifyinline',  function(event){
		event.preventDefault();
		var elmObj = jQuery(this);
		var mId = jQuery(this).attr('id');
		var mdl = jQuery(this).attr('mdl');
		var msg = jQuery(this).attr('msg');		
		if(confirm(msg)){
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'reports/do_verify',
				data: {mdl:mdl, mId:mId, 'unverify':0 },
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					window.location.href = window.location.href;				
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
		return false;
	});
	
	jQuery(document).on("click", ".unverifyinline", function(event){	
		event.preventDefault();
		var elmObj = jQuery(this);
		var mId = jQuery(this).attr('id');
		var mdl = jQuery(this).attr('mdl');
		var msg = jQuery(this).attr('msg');		
		if(confirm(msg)){
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'reports/do_verify',
				data: {mdl:mdl, mId:mId, 'unverify':1 },
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					window.location.href = window.location.href;	
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
		return false;
	});
	
	
	jQuery(document).on('change', '#sdepot', function(e){
		var elmObj = jQuery(this);
		var depotId = jQuery(this).val();
		var verifiedVal = 0;
		if (window.location.href.indexOf("verified") > -1) {
			var url_string = window.location.href;
			var url = new URL(url_string);
			var verified = url.searchParams.get("verified"); 
			if(verified == 1){
				verifiedVal = 1;
			}
		}
		if(jQuery('#user').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'region/getUser.json',
				data: {depot:depotId, verified:verifiedVal},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					$('#user').fillSelect(data.users); 
					
					if(jQuery('#role').length){
						$('#role option:first').prop('selected', true);  // This ensures the first option is selected
					}
					
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	jQuery(document).on('change', '#sdepot', function(e){
		var elmObj = jQuery(this);
		var depotId = jQuery(this).val();
		
		var getCust = getSubdepot = 0;
		if(jQuery('#getSubdepot').length){	
			getSubdepot = 1;
		}
		if(jQuery('#scustomer').length){	
			getCust = 1;
		}
		
		
		if(jQuery('#subdepots').length || jQuery('#scustomer').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'region/getSubdepot.json',
				data: {depot:depotId, getSubdepot:getSubdepot, getCust:getCust},
				dataType: 'json',
				beforeSend: function(){ 
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
					/* if(jQuery('#scustomer').length){
						jQuery('#scustomer').after('<img src="'+siteUrl+'img/loading20.gif" class="cloading" />');
					} */
				},
				success: function(data){
					
					jQuery('.loading').remove();
					if(jQuery('#subdepots').length){	
						$('#subdepots').fillSelect(data.subdepots);
						
					}
					/* if(jQuery('#scustomer').length){	
						$('#scustomer').fillSelect(data.customers);
						jQuery('.cloading').remove();
					} */
					
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	jQuery(document).on('change', '#sdivision', function(e){ //alert('s');
		var elmObj = jQuery(this);
		var divisionId = jQuery(this).val();
		var  eoptionsel = jQuery(this).attr('data-val'); //console.log(eoptionsel);
		
		var getCust = 0;
		if(jQuery('#scustomer').length){	
			getCust = 1;
		}
		
		var getUser = 0;
		if(jQuery('#user').length){	
			getUser = 1;
		}
		
		if(jQuery('#sregion').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'region/getRegion.json',
				data: {division:divisionId,eoption:eoptionsel,getCust:getCust, getUser:getUser},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){ 
					jQuery('.loading').remove();
					$('#sregion').fillSelect(data.regions);
					$('#sdepot').fillSelect(data.depots);
					if($('#user').length){
						$('#user').fillSelect(data.users);
					}
					/* if(jQuery('#scustomer').length){	
						$('#scustomer').fillSelect(data.customers);
					} */
					if(eoptionsel=='setsel'){
                        $('#sregion').prepend('<option value="" selected>Select Region</option>');
                        $('#sdepot').prepend('<option value="" selected>Select Depot</option>');
                    }
					
					if(jQuery('#role').length){
						$('#role option:first').prop('selected', true);  // This ensures the first option is selected
					}
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	jQuery(document).on('change', '#user', function(e){
        var elmObj = jQuery(this);
        var userId = jQuery(this).val();
        var  eoptionsel = jQuery(this).attr('data-val');

        if(jQuery('#sroute').length){

            jQuery.ajax({
                type: 'POST',
                url: siteUrl+'routes/getRouteByUser.json',
                data: {user:userId,eoption:eoptionsel},
                dataType: 'json',
                beforeSend: function(){
                    elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
                },
                success: function(data){//console.log(data);
                    jQuery('.loading').remove();
                    $('#sroute').fillSelect(data.routes);
                    if(eoptionsel=='setsel'){
                        $('#sroute').prepend('<option value="" selected>Select Route</option>');
                    }

                },
                statusCode: {
                    404: function() {
                        alert( message.noPage );
                    }
                }
            });
        }
    });
	
	jQuery(document).on('change', '#asset_type', function(e){
		var elmObj = jQuery(this);
		var type = jQuery(this).val();
		var  eoptionsel = jQuery(this).attr('data-val');
		
		if(jQuery('#asset_id').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'assets/getAssets.json',
				data: {type:type, eoption:eoptionsel},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					$('#asset_id').fillSelect(data.assets);
					
					
					
					if(jQuery('#asset_row').length){		
                    	$('#asset_row').show();
					}
					
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});

	jQuery(document).on('change', '#bgroup', function(e){ //alert('s');
		var elmObj = jQuery(this);
		var brandgroupId = jQuery(this).val();
		var  eoptionsel = jQuery(this).attr('data-val');
			
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'region/getBrand.json',
				data: {brandgroup:brandgroupId,eoption:eoptionsel},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){ 
					jQuery('.loading').remove();
					 $('#sbrand').fillSelect(data.brandList);
					
					if(eoptionsel=='setsel'){
                        $('#sbrand').prepend('<option value="" selected>Select Brand</option>');
                    }
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		
	});

	//select expense type
	jQuery(document).on('change', '#exp_cat', function(e){ //alert('c');
		var elmObj = jQuery(this);
		var expensecategoryId = jQuery(this).val();
		var  eoptionsel = jQuery(this).attr('data-val');

			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'expense/getExpType.json',
				data: {cat_id:expensecategoryId,eoption:eoptionsel},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){ 
					jQuery('.loading').remove();
					 $('#exptype').fillSelect(data.typeList);
					
					if(eoptionsel=='setsel'){
                        $('#exptype').prepend('<option value="" selected>Select Category</option>');
                    }
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
	});
	
	jQuery(document).on('change', '#role', function(e){
		var elmObj = jQuery(this);
		var roleId = jQuery(this).val();
		
		if(jQuery('#sdivision').length){	
			divisionId = jQuery('#sdivision').val();
		}
		if(jQuery('#sregion').length){	
			regionId = jQuery('#sregion').val();
		}
		if(jQuery('#sdepot').length){	
			depotId = jQuery('#sdepot').val();
		}

		if(jQuery('#user').length){		
		
			jQuery.ajax({
				type: 'POST',
				url: siteUrl+'users/getUsersByRole.json',
				data: {roleId:roleId, divisionId:divisionId, regionId:regionId, depotId:depotId},
				dataType: 'json',
				beforeSend: function(){
					elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
				},
				success: function(data){
					jQuery('.loading').remove();
					$('#user').fillSelect(data.users); 
					
				},
				statusCode: {
					404: function() {
						alert( message.noPage );
					}
				}
			});
		}
	});
	
	// Function to populate a select element with options, keeping the first option fixed
	$.fn.fillSelect = function(data) {
		const $select = $(this);
		
		$select.empty(); // Clear existing options
		
		
		// Create an array to hold sorted options and find the first option
		let firstKey = null;
		const sortedEntries = [];

		// Iterate over the object properties
		for (const key in data) {
			if (data.hasOwnProperty(key)) {
				if (firstKey === null) {
					// The first property encountered
					firstKey = key;
				} else {
					// Collect other properties for sorting
					sortedEntries.push([key, data[key]]);
				}
			}
		}

		// Append the first option if it exists
		if (firstKey !== null) {
			$select.append($('<option>').val(firstKey).text(data[firstKey]));
		}

		// Sort the remaining entries alphabetically by value
		sortedEntries.sort((a, b) => a[1].localeCompare(b[1]));

		// Append sorted options
		sortedEntries.forEach(([key, value]) => {
			$select.append($('<option>').val(key).text(value));
		});
								
	};

});