<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Zonal Head</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">Name *</label>
            <input
              type="text"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Name" name="name" required value="<?=$zonal_head[0]['name']?>" />
          </div>
          
          <div class="mb-3">
            <label>Mobile *</label>
            <input type="tel" maxlength="10" pattern="[0-9]{10}" oninput="this.value = this.value.replace(/[^0-9]/g, '')" placeholder="Mobile" name="mobile" required class="form-control" value="<?=$zonal_head[0]['mobile']?>" >
        </div>
         
         <div class="mb-3">
            <label for="email" class="form-label"> Email *</label>
            <input
              type="email"
              class="form-control"
              id="email"
              name="email"
              placeholder="Email" required value="<?=$zonal_head[0]['email']?>" />
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">DOB *</label>
            <input
              type="date"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="DOB" name="dob"  required value="<?=$zonal_head[0]['dob']?>" onkeydown="return false;"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Image *</label>
            <input
              type="file"
              class="form-control"
              id="exampleFormControlInput1"
               name="image" placeholder="Image"/>
          </div>
          <p style="color:red">please upload only jpg,jpeg and png format files</p>
          
          <img src="<?php echo $this->config->item('bharosa_base_url').$zonal_head[0]['image'];?>" alt="banner" width="60" height="60">
          
              <div class="mb-3">
                  <label class="form-label">State *</label>
                  <select class="form-select" name="state_id" id="state_id" required placeholder="State">
                    <option value="">Select State</option>
                    <?php if (!empty($states)) {
                      foreach ($states as $row) { ?>
                        <option value="<?= $row['id'] ?>" <?php if($row['id']==$zonal_head[0]['state_id']){echo 'selected="selected"';}?>><?= $row['name'] ?></option>
                    <?php }
                    } ?>
                  </select>
                </div>
                <?php 
                $state_head = $this->registermodel->common_fetch_select('state_heads',['state_id' => $zonal_head[0]['state_id'],'delete_status' => 1],'id,name',[]);
                ?>
                <div class="mb-3">
                  <label class="form-label">State Head *</label>
                  <input type="text" class="form-control" name="state_head_name" id="state_head_name" placeholder="State Head" readonly value="<?=$state_head[0]['name']?>" >
                  <input type="hidden" name="state_head_id" id="state_head_id" value="<?=$state_head[0]['id']?>" placeholder="State Head" required>
                </div>

                
                <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">Gender *</label>
                <select class="form-select" name="gender" required placeholder="Gender">
                    <option value="">Select Gender</option>
                    <option value="male" <?php if($zonal_head[0]['gender']=='male'){echo 'selected="selected"';}?>>Male</option>
                    <option value="female" <?php if($zonal_head[0]['gender']=='female'){echo 'selected="selected"';}?>>Female</option>
                </select>
              </div>
          
          
              <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">Occupation *</label>
                <input
                  type="text"
                  class="form-control"
                  id="exampleFormControlInput1"
                  placeholder="Occupation" name="occupation"  required value="<?=$zonal_head[0]['occupation']?>" />
              </div>
          
        </div>
      </div>
      <input type="hidden" class="form-control-file" placeholder="Image" name="image" value="<?=$zonal_head[0]['image']?>">
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      <a href="<?=base_url('admin/register/zonal_heads')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>



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

        // Validate required fields
        $('#inputform [required]').each(function () {
            let value = $(this).val();
            if (Array.isArray(value)) {
                value = value.join('');
            }
            value = value ? value.toString().trim() : '';
            const fieldName = $(this).attr('name');

            if (value === '') {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', `${$(this).attr('placeholder')} is required`, 'error');
                return;
            }

            // Name validation
            if (fieldName === 'name') {
                const namePattern = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/;
                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. Allowed: letters, numbers, spaces, apostrophes, hyphens, dots.', 'error');
                    return;
                }
            }


            // Mobile validation
            if (fieldName === 'mobile') {
                const mobilePattern = /^[6-9][0-9]{9}$/;
                if (!mobilePattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Please enter a valid 10-digit mobile number starting with 6-9.', 'error');
                    return;
                }
            }
            
            // Emal validation
            if (fieldName === 'email') {
                const namePattern = /^[A-Za-z0-9][^\s@]*@[^\s@]+\.[^\s@]+$/;
                if (!namePattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Please enter a valid email address (first character must be a letter or number)', 'error');
                    return;
                }
            }

            if (fieldName === 'occupation') {
                const namePattern = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/;
                if (!namePattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Occupation must not start with a special character and must be at least 3 characters. Allowed: letters, numbers, spaces, apostrophes, hyphens, dots.', 'error');
                    return;
                }
            }
            
            // DOB validation (should be at least 18 years old)
            if (fieldName === 'dob') {
                const dob = new Date(value);
                const today = new Date();
                const ageDiff = today.getFullYear() - dob.getFullYear();
                const monthDiff = today.getMonth() - dob.getMonth();
                const dayDiff = today.getDate() - dob.getDate();
            
                let age = ageDiff;
                if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
                    age--;
                }
            
                if (isNaN(dob.getTime()) || age < 18) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Age must be at least 18 years based on Date of Birth.', 'error');
                    return;
                }
            }


            $(this).removeClass('is-invalid').addClass('is-valid');
        });

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

            $.ajax({
                url: '<?= base_url("admin/register/edit_zonal_head_data/".$zonal_head[0]['id']); ?>',
                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/zonal_heads") ?>';
                    } 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 feedback
    $('#inputform .form-control').on('input change', function () {
        const value = $(this).val().trim();
        const fieldName = $(this).attr('name');
        let isFieldValid = true;

        if (value === '') {
            isFieldValid = false;
        } else {
            switch (fieldName) {
                case 'name':
                    isFieldValid = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/.test(value);
                    break;
            
                case 'mobile':
                    isFieldValid = /^[6-9][0-9]{9}$/.test(value);
                    break;
            
                case 'email':
                    isFieldValid = /^[A-Za-z0-9][^\s@]*@[^\s@]+\.[^\s@]+$/.test(value);
                    break;
                    
                case 'occupation':
                    isFieldValid = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/.test(value);
                    break;
                
                case 'dob':
                    const enteredDob = new Date(value);
                    const now = new Date();
                    const yearDiff = now.getFullYear() - enteredDob.getFullYear();
                    const monthDiff = now.getMonth() - enteredDob.getMonth();
                    const dayDiff = now.getDate() - enteredDob.getDate(); 
                    let calculatedAge = yearDiff;
                    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
                        calculatedAge--;
                    }
                    isFieldValid = !isNaN(enteredDob.getTime()) && calculatedAge >= 18;
                    break;
                
            }

        }

        if (isFieldValid) {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });
});
</script>

<script>
    $('#state_id').on('change', function () {
      var state_id = $(this).val();
      $('#state_head_name').val('');
      $('#state_head_id').val('');
    
      if (state_id !== '') {
        $.ajax({
          url: '<?= base_url('admin/register/get_state_heads_by_state') ?>',
          type: 'POST',
          data: { state_id: state_id },
          success: function (data) {
            var heads = JSON.parse(data);
            if (heads.length > 0) {
              var head = heads[0]; // Assuming the first head is to be shown
              $('#state_head_name').val(head.name);
              $('#state_head_id').val(head.id);
            } else {
              //$('#state_head_name').val('No State Head Found');
              showToast('Error', 'No State Head Found', 'error');
            }
          }
        });
      }
    });
</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>
            