<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Add 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">
                <option value="">Select Speciality</option>
                <?php if(!empty($specialities)){ 
                foreach($specialities as $row){?>
                <option value="<?=$row['speciality_id']?>"><?=$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/>
          </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">
        </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" required/>
          </div>
          <p style="color:red">please upload only jpg,jpeg and png format files</p>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Qualification *</label>
            <select class="form-select" name="qualification[]" required placeholder="Qualification" multiple>
                <option value="">Select Qualification</option>
                <?php if(!empty($medical_degrees)){ 
                foreach($medical_degrees as $medical_degree_row){?>
                <option value="<?=$medical_degree_row['id']?>"><?=$medical_degree_row['name']?></option>
                <?php } } ?>
            </select>
            <small class="form-text text-muted">Hold down <strong>Ctrl</strong> (or <strong>Cmd</strong> on Mac) to select multiple options.</small>
          </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" min="0" required/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Description *</label>
            <textarea class="form-control"
              id="exampleFormControlInput1"
              placeholder="Description" name="description" required></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 Fee" name="online_fee" min="0" required/>
          </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" min="0" required/>
          </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">Online</option>
                <option value="offline">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" required/>
          </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/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
        $('#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;
                }
            }

            // Experience, Fees: must be 0 or greater
            if (['exp', 'online_fee', 'offline_fee'].includes(fieldName)) {
                if (isNaN(value) || parseInt(value) < 0) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', `${$(this).attr('placeholder')} cannot be negative.`, 'error');
                    return;
                }
            }
            
            if (fieldName === 'exp' && value.length > 2) {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', `${$(this).attr('placeholder')} must be at most 2 digits.`, 'error');
                return;
            }

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

            // Unique ID: 6–20 characters with A-Z, a-z, 0-9, -, /
            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;
                }
            }

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

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

            $.ajax({
                url: '<?= base_url("admin/register/insert_doctor"); ?>',
                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 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 'exp':
                    isFieldValid = !isNaN(value) && parseInt(value) >= 0 && value.length <= 2;
                    break;
            
                case 'online_fee':
                case 'offline_fee':
                    isFieldValid = !isNaN(value) && parseInt(value) >= 0;
                    break;
            
                case 'description':
                    isFieldValid = value.length >= 3;
                    break;
            
                case 'unique_id':
                    isFieldValid = /^[A-Za-z0-9\/-]{6,20}$/.test(value);
                    break;
            }

        }

        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>
            