<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Add Medical Sales Target</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 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)) { ?>
                    <option value="all">All</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"  placeholder="Mandal" required>
                    <option value="">Select Mandal</option>
                    <!--<option value="add_new">+ Add New City</option>-->
                  </select>
                </div>
                
                <div class="mb-3">
                  <label class="form-label">Village *</label>
                  <select class="form-select" name="village_id" id="village_id"  placeholder="Village" required>
                    <option value="">Select Village</option>
                    <!--<option value="add_new">+ Add New City</option>-->
                  </select>
                </div>
                
                <div class="mb-3">
                  <label class="form-label">Medical Advisors *</label>
                  <select class="form-select" name="regional_manager_id" id="regional_manager_id"  placeholder="Medical Advisor" required>
                    <option value="">Select Medical Advisor</option>
                    <!--<option value="add_new">+ Add New City</option>-->
                  </select>
                </div>
                
                <div class="mb-3">
                  <label class="form-label">Month *</label>
                  <select class="form-select" name="month" id="month"  placeholder="Month" required>
                    <option value="">Select Month</option>
                    <?php foreach($months as $row){?>
                    <option value="<?=$row['id']?>"><?=$row['name']?></option>
                    <?php } ?>
                  </select>
                </div>
                
                <div class="mb-3">
                  <label class="form-label">Year *</label>
                  <select class="form-select" name="year" id="year" placeholder="Year" required>
                    <option value="">Select Year</option>
                    <?php 
                      $current_year = date('Y');
                      for ($i = $current_year; $i >= ($current_year - 10); $i--) {
                          echo "<option value='$i'>$i</option>";
                      }
                    ?>
                  </select>
                </div>

                <div class="mb-3">
                  <label class="form-label">Target *</label>
                  <input type="text" name="target" id="target" class="form-control" required placeholder="Target" autofocus  maxlength="10" pattern="[0-9]{10}" oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                </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/medical_advisor_sales_target')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>


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

    // Validate required fields excluding disabled ones
    $('#inputform [required]').each(function () {
        if ($(this).is(':disabled')) return;

        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 false; // break out of .each()
        }

        if (fieldName === 'target' && parseInt(value) <= 0) {
            isValid = false;
            $(this).addClass('is-invalid');
            showToast('Error', 'Target must be a positive number greater than zero.', 'error');
            return false;
        }

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

    // Stop here if not valid
    if (!isValid) return;

    // Validate date (month/year not in past)
    const selectedMonth = parseInt($('#month').val());
    const selectedYear = parseInt($('#year').val());
    const currentDate = new Date();
    const currentMonth = currentDate.getMonth() + 1;
    const currentYear = currentDate.getFullYear();

    if (selectedYear < currentYear || (selectedYear === currentYear && selectedMonth < currentMonth)) {
        showToast('Error', 'You cannot select a past month and year.', 'error');
        return;
    }

    // ✅ Build form and submit via AJAX
    const formData = new FormData();
    formData.append('state_id', $('#state_id').val());
    formData.append('month', $('#month').val());
    formData.append('year', $('#year').val());
    formData.append('target', $('#target').val());

    if (!$('#district_id').prop('disabled')) {
        formData.append('district_id', $('#district_id').val());
    }
    if (!$('#mandal_id').prop('disabled')) {
        formData.append('mandal_id', $('#mandal_id').val());
    }
    if (!$('#village_id').prop('disabled')) {
        formData.append('village_id', $('#village_id').val());
    }
    if (!$('#regional_manager_id').prop('disabled')) {
        formData.append('regional_manager_id', $('#regional_manager_id').val());
    }

    $.ajax({
        url: '<?= base_url("admin/register/insert_medical_advisor_sales_target"); ?>',
        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');
                $('#district_id, #mandal_id, #regional_manager_id').prop('disabled', false);
                window.location.href = '<?= base_url("admin/register/medical_advisor_sales_target") ?>';
            } else {
                showToast('Error', res.message, 'error');
            }
        },
        error: function () {
            showToast('Error', 'An unexpected error occurred.', 'error');
        }
    });
});

</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 mandals = JSON.parse(data);
          $.each(mandals, function (index, mandal) {
            $('#mandal_id').append('<option value="' + mandal.id + '">' + mandal.name + '</option>');
          });
        }
      });
    }
  });
  
  $('#mandal_id').on('change', function () {
    var mandal_id = $(this).val();
    var state_id = $('#state_id').val();
    var district_id = $('#district_id').val();
    $('#village_id').html('<option value="">Select Village</option>');

    if (state_id !== '' && district_id !== '') {
      $.ajax({
        url: '<?= base_url('admin/register/get_villages_by_state_district_mandal') ?>',
        type: 'POST',
        data: { state_id: state_id, district_id: district_id,mandal_id:mandal_id },
        success: function (data) {
          var villages = JSON.parse(data);
          $.each(villages, function (index, village) {
            $('#village_id').append('<option value="' + village.id + '">' + village.name + '</option>');
          });
        }
      });
    }
  });
  
  $('#village_id').on('change', function () {
    var district_id = $('#district_id').val();
    var state_id = $('#state_id').val();
    var mandal_id = $('#mandal_id').val();
    var village_id = $(this).val();
    $('#regional_manager_id').html('<option value="">Select Medical Advisor</option>');

    if (state_id !== '' && district_id !== '') {
      $.ajax({
        url: '<?= base_url('admin/register/get_medical_advisors_by_state_district_mandal_village') ?>',
        type: 'POST',
        data: { state_id: state_id, district_id: district_id, mandal_id: mandal_id, village_id:village_id },
        success: function (data) {
          var regional_managers = JSON.parse(data);
          $.each(regional_managers, function (index, regional_manager) {
            $('#regional_manager_id').append('<option value="' + regional_manager.id + '">' + regional_manager.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>
            