/**
 * Auto selection of County, Subcounty, Parish and Village from  respective District
 */
$(document).ready(function(){
  
    // County load
    $('#district_id').change(function(){
      var district_id = $(this).val();
      $.ajax({
          url: base_url + 'county/' + district_id,
          method: 'POST',
          data: { [csrfTokenName]: csrfToken, district_id: district_id },
          dataType: 'json',
          success: function(response) {
              // refresh token for NEXT request
              csrfToken = response.csrfToken;

              $('#county_id').empty().append('<option value="">Select County</option>');
              $.each(response.data, function(i, item){
                  $('#county_id').append('<option value="'+item.county_id+'">'+item.county_name+'</option>');
              });
          }
      });
  });

  // SubCounty load
  $('#county_id').change(function(){
      var county_id = $(this).val();
      $.ajax({
          url: base_url + 'subcounty/' + county_id,
          method: 'POST',
          data: { [csrfTokenName]: csrfToken, county_id: county_id },
          dataType: 'json',
          success: function(response) {
              // refresh token again
              csrfToken = response.csrfToken;

              $('#subcounty_id').empty().append('<option value="">Select Subcounty</option>');
              $.each(response.data, function(i, item){
                  $('#subcounty_id').append('<option value="'+item.subcounty_id+'">'+item.subcounty_name+'</option>');
              });
          }
      });
  });


  // Parish load
  $('#subcounty_id').change(function(){
    var subcounty_id = $(this).val();
    $.ajax({
      url: base_url+'parish/'+subcounty_id,
      method: 'POST',
      data: { [csrfTokenName]: csrfToken, subcounty_id: subcounty_id },
      dataType: 'json',
      success: function(response){
        csrfToken = response.csrfToken;

        $('#parish_id').find('option').not(':first').remove();
        $('#village_id').find('option').not(':first').remove();

        $.each(response.data, function(index, data){
          $('#parish_id').append('<option value="'+data.parish_id+'">'+data.parish_name+'</option>');
        });
      }
    });
  });


  // Village load
  $('#parish_id').change(function(){
    var parish_id = $(this).val();
    $.ajax({
      url: base_url+'village/'+parish_id,
      method: 'POST',
      data: { [csrfTokenName]: csrfToken, parish_id: parish_id },
      dataType: 'json',
      success: function(response){
        // NB: your villages() method does NOT return csrfToken yet → fix below
        if (response.csrfToken) {
          csrfToken = response.csrfToken;
        }

        $('#village_id').find('option').not(':first').remove();

        $.each(response.data, function(index, data){
          $('#village_id').append('<option value="'+data.village_id+'">'+data.village_name+'</option>');
        });
      }
    });
  });

 });