<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Add Village</h4>
              
  <div class="row"><div class="col-md-6">
      <div class="card mb-4">
          <form method="post" action="#" id="inputform" enctype="multipart/form-data">
        <div class="card-body">
            
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">State *</label>
            <select class="form-select" id="state_id" name="state_id" placeholder="State" required>
                <option value="">Select State</option>
                <?php foreach($states as $row){?>
                <option value="<?=$row['id']?>"><?=$row['name']?></option>
                <?php } ?>
            </select>
          </div>
          
        
            <div class="mb-3">
              <label class="form-label">District *</label>
              <select class="form-select" name="district_id" id="district_id" required placeholder="District">
                <option value="">Select District</option>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label">Mandal *</label>
              <select class="form-select" name="mandal_id" id="mandal_id" required placeholder="Mandal">
                <option value="">Select Mandal</option>
              </select>
            </div>

          
            <div class="mb-3">
              <label class="form-label">Name(s) *</label>
              <div id="nameFieldsContainer">
                <div class="input-group mb-2">
                  <input type="text" name="name[]" class="form-control" placeholder="Name" required />
                  <button type="button" class="btn btn-success add-name-field"><i class="fa fa-plus"></i></button>
                </div>
              </div>
            </div>

          
        </div>
      </div>
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      <a href="<?=base_url('admin/register/villages')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const container = document.getElementById('nameFieldsContainer');

  container.addEventListener('click', function (e) {
    if (e.target.closest('.add-name-field')) {
      const inputGroup = document.createElement('div');
      inputGroup.classList.add('input-group', 'mb-2');
      inputGroup.innerHTML = `
        <input type="text" name="name[]" class="form-control" placeholder="Name" required />
        <button type="button" class="btn btn-danger remove-name-field"><i class="fa fa-minus"></i></button>
      `;
      container.appendChild(inputGroup);
    }

    if (e.target.closest('.remove-name-field')) {
      const inputGroup = e.target.closest('.input-group');
      if (inputGroup) inputGroup.remove();
    }
  });
});
</script>


<script>
$(document).ready(function () {
    $('#saveBtn').on('click', function () {
        let isValid = true;

        // Reset previous validation states
        $('#inputform .form-control').removeClass('is-invalid is-valid');

        // Validate state
        const state = $('#state_id').val();
        if (!state) {
            isValid = false;
            $('#state_id').addClass('is-invalid');
            showToast('Error', 'State is required', 'error');
        }

        // Validate district
        const district = $('#district_id').val();
        if (!district) {
            isValid = false;
            $('#district_id').addClass('is-invalid');
            showToast('Error', 'District is required', 'error');
        }
        
        // Validate mandal
        const mandal = $('#mandal_id').val();
        if (!mandal) {
            isValid = false;
            $('#mandal_id').addClass('is-invalid');
            showToast('Error', 'Mandal is required', 'error');
        }

        // Validate all name[] fields
        $('input[name="name[]"]').each(function () {
            const value = $(this).val().trim();
            // Allow special characters; must be at least 3 chars, not start with space
            const namePattern = /^[A-Za-z][^0-9]{2,}$/;

            if (value === '') {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', 'Name is required', 'error');
            } else if (!namePattern.test(value)) {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', 'Name must not start with a special character and must be at least 3 characters and numbers are not allowed', 'error');
            } else {
                $(this).addClass('is-valid');
            }
        });

        if (isValid) {
            const form = $('#inputform')[0];
            const formData = new FormData(form);

            $.ajax({
                url: '<?= base_url("admin/register/insert_village"); ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    const res = JSON.parse(response);
                    if (res.success) {
                        showToast('Success', res.message, 'success');
                        $('#inputform')[0].reset();
                        $('.form-control').removeClass('is-valid');
                        window.location.href = '<?= base_url("admin/register/villages") ?>';
                    } else {
                        showToast('Error', res.message, 'error');
                    }
                },
                error: function () {
                    showToast('Error', 'An unexpected error occurred.', 'error');
                },
            });
        } else {
            $('html, body').animate({
                scrollTop: $('.is-invalid:first').offset().top - 100,
            }, 500);
        }
    });

    // Real-time validation for dynamic name[] fields
    $(document).on('input change', 'input[name="name[]"]', function () {
        const value = $(this).val().trim();
        const namePattern = /^[A-Za-z][^0-9]{2,}$/;

        if (value === '') {
            $(this).removeClass('is-valid').addClass('is-invalid');
        } else if (!namePattern.test(value)) {
            $(this).removeClass('is-valid').addClass('is-invalid');
        } else {
            $(this).removeClass('is-invalid').addClass('is-valid');
        }
    });
});
</script>

<script>
  $('#state_id').on('change', function () {
    var state_id = $(this).val();
    $('#district_id').html('<option value="">Select District</option>');
    $('#city_id').html('<option value="">Select City</option>');

    if (state_id !== '') {
      $.ajax({
        url: '<?= base_url('admin/register/get_districts_by_state') ?>',
        type: 'POST',
        data: { state_id: state_id },
        success: function (data) {
          var districts = JSON.parse(data);
          $.each(districts, function (index, district) {
            $('#district_id').append('<option value="' + district.id + '">' + district.name + '</option>');
          });
        }
      });
    }
  });

  $('#district_id').on('change', function () {
    var district_id = $(this).val();
    var state_id = $('#state_id').val();
    $('#mandal_id').html('<option value="">Select Mandal</option>');

    if (state_id !== '' && district_id !== '') {
      $.ajax({
        url: '<?= base_url('admin/register/get_mandals_by_state_district') ?>',
        type: 'POST',
        data: { state_id: state_id, district_id: district_id },
        success: function (data) {
          var cities = JSON.parse(data);
          $.each(cities, function (index, city) {
            $('#mandal_id').append('<option value="' + city.id + '">' + city.name + '</option>');
          });
        }
      });
    }
  });
</script>

<!-- Toastr CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


<script>
// Show toast using jQuery
function showToast(title, message, type) {
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000",
    };

    if (type === 'success') {
        toastr.success(message, title);
    } else if (type === 'error') {
        toastr.error(message, title);
    } else if (type === 'info') {
        toastr.info(message, title);
    } else if (type === 'warning') {
        toastr.warning(message, title);
    }
}


</script>
            