<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Regional Manager</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="<?=$regional_manager[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="<?=$regional_manager[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="<?=$regional_manager[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="<?=$regional_manager[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').$regional_manager[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']==$regional_manager[0]['state_id']){echo 'selected="selected"';}?>><?= $row['name'] ?></option>
                    <?php }
                    } ?>
                  </select>
                </div>
                
                <?php 
                    $state_head = $this->registermodel->common_fetch_select('state_heads',['state_id' => $regional_manager[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']?>" required>
                </div>
                
                <?php 
                $zonal_heads = $this->registermodel->common_fetch_select('zonal_heads',['state_id' => $regional_manager[0]['state_id'],'state_head_id' => $regional_manager[0]['state_head_id'],'delete_status' => 1],'id,name',[]);
                ?>
                
                <div class="mb-3">
                  <label class="form-label">Zonal Head *</label>
                  <select class="form-select" name="zonal_head_id" id="zonal_head_id"  placeholder="Zonal Head" required>
                    <option value="">Select Zonal Head</option>
                    <?php if (!empty($zonal_heads)) {
                      foreach ($zonal_heads as $zonal_rows) { ?>
                        <option value="<?= $zonal_rows['id'] ?>" <?php if($zonal_rows['id']==$regional_manager[0]['zonal_head_id']){echo 'selected="selected"';}?>><?= $zonal_rows['name'] ?></option>
                    <?php }
                    } ?>
                  </select>
                </div>
                
                <?php 
                $territory_heads = $this->registermodel->common_fetch_select('territory_heads',['state_id' => $regional_manager[0]['state_id'],'state_head_id' => $regional_manager[0]['state_head_id'],'zonal_head_id' => $regional_manager[0]['zonal_head_id'],'delete_status' => 1],'id,name,district_id',[]);
                if (!empty($territory_heads)) {
                    $district_ids = explode(',', $territory_heads[0]['district_id']);
                    $this->db->where_in('id', $district_ids);
                    $this->db->order_by('name', 'ASC');
                    $districts = $this->db->get('districts')->result_array();
                } else {
                    $districts = [];
                }
                ?>
                
                <div class="mb-3">
                  <label class="form-label">Territory Head *</label>
                  <select class="form-select" name="territory_head_id" id="territory_head_id" required placeholder="Territory Head">
                    <option value="">Select Territory Head</option>
                    <?php if (!empty($territory_heads)) {
                      foreach ($territory_heads as $territory_rows) { ?>
                        <option value="<?= $territory_rows['id'] ?>" <?php if($territory_rows['id']==$regional_manager[0]['territory_head_id']){echo 'selected="selected"';}?>><?= $territory_rows['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>
                    <?php if (!empty($districts)) {
                      foreach ($districts as $district_rows) { ?>
                        <option value="<?= $district_rows['id'] ?>" <?php if($district_rows['id']==$regional_manager[0]['district_id']){echo 'selected="selected"';}?>><?= $district_rows['name'] ?></option>
                    <?php }
                    } ?>
                  </select>
                </div>
                
                <?php 
                $mandals = $this->registermodel->common_fetch_select('mandals',['district_id' => $regional_manager[0]['district_id'],'delete_status' => 1],'id,name',[]);
                $selected_mandal_ids = [];
                if (!empty($regional_manager[0]['mandal_id'])) {
                    $selected_mandal_ids = explode(',', $regional_manager[0]['mandal_id']); // e.g., ["3", "5", "8"]
                }

                ?>
                
                <div class="mb-3">
                  <label class="form-label">Mandal *</label>
                  <select class="form-select" name="mandal_id[]" id="mandal_id" required placeholder="Mandal" multiple>
                    <option value="">Select Mandal</option>
                    <?php if (!empty($mandals)) {
                        foreach ($mandals as $mandal_rows) { 
                          $selected = in_array($mandal_rows['id'], $selected_mandal_ids) ? 'selected="selected"' : '';
                      ?>
                          <option value="<?= $mandal_rows['id'] ?>" <?= $selected ?>><?= $mandal_rows['name'] ?></option>
                      <?php }
                      } ?>
                  </select>
                </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($regional_manager[0]['gender']=='male'){echo 'selected="selected"';}?>>Male</option>
                    <option value="female" <?php if($regional_manager[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="<?=$regional_manager[0]['occupation']?>"/>
              </div>
          
        </div>
      </div>
      <input type="hidden" class="form-control-file" placeholder="Image" name="image" value="<?=$regional_manager[0]['image']?>">
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      <a href="<?=base_url('admin/register/regional_managers')?>"><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_regional_manager_data/".$regional_manager[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/regional_managers") ?>';
                    } 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>
$(document).ready(function () {
  // On state change
  $('#state_id').on('change', function () {
    const state_id = $(this).val();
    $('#district_id').html('<option value="">Select District</option>');
    $('#zonal_head_id').html('<option value="">Select Zonal Head</option>');
    $('#territory_head_id').html('<option value="">Select Territory Head</option>');
    $('#mandal_id').html('<option value="">Select Mandal</option>');
    $('#state_head_name').val('');
    $('#state_head_id').val('');

    if (state_id !== '') {
      // 1. Fetch state head
      $.post('<?= base_url('admin/register/get_state_heads_by_state') ?>', { state_id }, function (data) {
        const heads = JSON.parse(data);
        if (heads.length > 0) {
          const head = heads[0];
          $('#state_head_name').val(head.name);
          $('#state_head_id').val(head.id);

          // 2. Fetch zonal heads
          $.post('<?= base_url('admin/register/get_zonal_heads_by_state') ?>', { state_id, state_head_id: head.id }, function (data) {
            const zonal_heads = JSON.parse(data);
            $('#zonal_head_id').html('<option value="">Select Zonal Head</option>');
            $.each(zonal_heads, function (index, zonal) {
              $('#zonal_head_id').append(`<option value="${zonal.id}">${zonal.name}</option>`);
            });
          });
        } else {
          //$('#state_head_name').val('No State Head Found');
          showToast('Error', 'No State Head Found', 'error');
        }
      });
    }
  });

  // On zonal head change
  $('#zonal_head_id').on('change', function () {
    const state_id = $('#state_id').val();
    const state_head_id = $('#state_head_id').val();
    const zonal_head_id = $(this).val();
    $('#territory_head_id').html('<option value="">Select Territory Head</option>');
    $('#district_id').html('<option value="">Select District</option>');
    $('#mandal_id').html('<option value="">Select Mandal</option>');

    if (zonal_head_id !== '') {
      $.post('<?= base_url('admin/register/get_territory_heads_by_zonal') ?>', {
        state_id,
        state_head_id,
        zonal_head_id
      }, function (data) {
        const heads = JSON.parse(data);
        $.each(heads, function (index, head) {
          $('#territory_head_id').append(`<option value="${head.id}">${head.name}</option>`);
        });
      });
    }
  });

  // On territory head change
  $('#territory_head_id').on('change', function () {
    const state_id = $('#state_id').val();
    const state_head_id = $('#state_head_id').val();
    const zonal_head_id = $('#zonal_head_id').val();
    const territory_head_id = $(this).val();

    $('#district_id').html('<option value="">Select District</option>');
    //$('#mandal_id').html('<option value="">Select Mandal</option>');

    if (territory_head_id !== '') {
      $.post('<?= base_url('admin/register/get_districts_by_territory') ?>', {
        state_id,
        state_head_id,
        zonal_head_id,
        territory_head_id
      }, function (data) {
        const districts = JSON.parse(data);
        const district_ids = [];

        $.each(districts, function (index, district) {
          $('#district_id').append(`<option value="${district.id}">${district.name}</option>`);
          district_ids.push(district.id);
        });

        // Optionally auto-load mandals too here
        // loadMandalsByDistricts(district_ids);
      });
    }
  });

  // On district change (load mandals)
  $('#district_id').on('change', function () {
    const district_ids = $(this).val(); // multiple select supported
    $('#mandal_id').html('<option value="">Select Mandal</option>');

    if (district_ids.length > 0) {
      $.ajax({
        url: '<?= base_url('admin/register/get_mandals_by_districts') ?>',
        type: 'POST',
        data: { district_id: district_ids },
        traditional: true,
        success: function (data) {
          const mandals = JSON.parse(data);
          $.each(mandals, function (index, mandal) {
            $('#mandal_id').append(`<option value="${mandal.id}">${mandal.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>
            