<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Doctor</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">Speciality *</label>
            <select class="form-select" name="speciality_id" required placeholder="Speciality" disabled>
                <option value="">Select Speciality</option>
                <?php if(!empty($specialities)){ 
                foreach($specialities as $row){?>
                <option value="<?=$row['id']?>" <?php if($doctor[0]['speciality_id']==$row['speciality_id']){echo 'selected="selected"';}?>><?=$row['name']?></option>
                <?php } } ?>
            </select>
          </div>
            
          <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="<?=$doctor[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="<?=$doctor[0]['mobile']?>" disabled>
        </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').$doctor[0]['image'];?>" alt="banner" width="60" height="60">
          
          <div class="mb-3">
            <label for="qualification" class="form-label">Qualification *</label>
            <select class="form-select" name="qualification[]" required multiple disabled>
                <?php if (!empty($medical_degrees)) { 
                    foreach ($medical_degrees as $medical_degree_row) { 
                        $selected = in_array($medical_degree_row['id'], $selected_qualifications ?? []) ? 'selected' : '';
                ?>
                    <option value="<?= $medical_degree_row['id'] ?>" <?= $selected ?>><?= $medical_degree_row['name'] ?></option>
                <?php 
                    } 
                } else { 
                ?>
                    <option value="">No qualifications found</option>
                <?php } ?>
            </select>
        </div>

          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Exp(in years) *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Exp" name="exp" required min="0" value="<?=$doctor[0]['exp']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Description *</label>
            <textarea class="form-control"
              id="exampleFormControlInput1"
              placeholder="Description" name="description" required><?=$doctor[0]['description']?></textarea>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Online Fee *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Online " name="online_fee" required min="0" value="<?=$doctor[0]['online_fee']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Offline Fee *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Offline Fee" name="offline_fee" required min="0" value="<?=$doctor[0]['offline_fee']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Consult Type *</label>
            <select class="form-select" name="consult_type" required placeholder="Consult Type">
                <option value="">Select Consult Type</option>
                <option value="online" <?php if($doctor[0]['consult_type']=='online'){echo 'selected="selected"';}?>>Online</option>
                <option value="offline" <?php if($doctor[0]['consult_type']=='offline'){echo 'selected="selected"';}?>>Offline</option>
            </select>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Unique Id *</label>
            <input
              type="text"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Unique Id" name="unique_id" maxlength="20" value="<?=$doctor[0]['unique_id']?>" disabled required/>
          </div>
          
        </div>
      </div>
      <input type="hidden" class="form-control-file" placeholder="Image" name="image" value="<?=$doctor[0]['image']?>">
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      <a href="<?=base_url('admin/register/doctors')?>"><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 with field-specific checks
        $('#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 start with a letter, be at least 3 characters, and may include letters, spaces, apostrophes, hyphens, or 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 from 6–9.', 'error');
                    return;
                }
            }

            // Experience validation
            if (fieldName === 'exp') {
                if (isNaN(value) || parseInt(value) < 0) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Experience cannot be negative.', 'error');
                    return;
                }
            
                if (value.length > 2) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Experience must be at most 2 digits.', 'error');
                    return;
                }
            }


            // Online fee validation
            if (fieldName === 'online_fee') {
                if (isNaN(value) || parseInt(value) < 0) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Online Fee cannot be negative.', 'error');
                    return;
                }
            }

            // Offline fee validation
            if (fieldName === 'offline_fee') {
                if (isNaN(value) || parseInt(value) < 0) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Offline Fee cannot be negative.', 'error');
                    return;
                }
            }

            // Description validation
            if (fieldName === 'description') {
                if (value.length < 3) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Description must be at least 3 characters long.', 'error');
                    return;
                }
            }

            // Unique ID validation
            if (fieldName === 'unique_id') {
                const uniqueIdPattern = /^[A-Za-z0-9\/-]{6,20}$/;
                if (!uniqueIdPattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Unique Id must be 6–20 characters and only include letters, numbers, hyphen (-), or slash (/).', 'error');
                    return;
                }
            }

            // Vehicle registration number
            if (fieldName === 'reg_number') {
                const regPattern = /^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{1,4}$/i;
                if (!regPattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Enter a valid vehicle number (e.g., MH12AB1234).', '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_doctor_data/".$doctor[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/doctors") ?>';
                    } 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
    $('#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 {
            if (fieldName === 'name') {
                isFieldValid = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/.test(value);
            
            } else if (fieldName === 'mobile') {
                isFieldValid = /^[6-9][0-9]{9}$/.test(value);
            
            } else if (fieldName === 'exp') {
                isFieldValid = !isNaN(value) && parseInt(value) >= 0 && value.length <= 2;
            
            } else if (['online_fee', 'offline_fee'].includes(fieldName)) {
                isFieldValid = !isNaN(value) && parseInt(value) >= 0;
            
            } else if (fieldName === 'description') {
                isFieldValid = value.length >= 3;
            
            } else if (fieldName === 'unique_id') {
                isFieldValid = /^[A-Za-z0-9\/-]{6,20}$/.test(value);
            
            } else if (fieldName === 'reg_number') {
                isFieldValid = /^[A-Z]{2}[0-9]{2}[A-Z]{1,2}[0-9]{1,4}$/i.test(value);
            }

        }

        if (isFieldValid) {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });
});
</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>