<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Diagnostic Prescription Booking</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="userSearch">Users *</label>
                <input type="text" id="userSearch" class="form-control" placeholder="Type name or mobile or unique id" onkeyup="filterUsers()">
                
                <select id="userSelect" name="user_id" class="form-select mt-2" size="5" style="display:none;" required placeholder="User">
                    <?php if(!empty($users)){ 
                        foreach($users as $row){ ?>
                            <option value="<?= $row['id'] ?>"><?= $row['name'] ?> (<?= $row['mobile'] ?>) (<?= $row['unique_id'] ?>)</option>
                    <?php } } ?>
                </select>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Family Members *</label>
            <select class="form-select" name="family_member_id" required placeholder="Family Member">
            
            </select>
          </div>
          
            <div class="mb-3">
                <label for="hospitalSearch" class="form-label">Diagnostics *</label>
                
                <!-- Search box -->
                <input type="text" id="hospitalSearch" class="form-control" placeholder="Type hospital name or mobile" onkeyup="filterHospitals()">
                
                <!-- Dropdown -->
                <select id="hospitalSelect" name="main_data_id" class="form-select mt-2" size="5" style="display:none;" required placeholder="Hospital">
                    <?php if(!empty($hospitals)){ 
                        foreach($hospitals as $roww){ ?>
                            <option value="<?= $roww['id'] ?>"><?= $roww['name'] ?> (<?= $roww['mobile'] ?>)</option>
                    <?php } } ?>
                </select>
            </div>
            
          <div class="mb-3">
            <label for="userSearch">Prescription *</label>
                <input type="file" id="prescription" class="form-control" placeholder="Image" name="image" required>
                <p style="color:red">upload only jpg,jpeg,png or pdf files</p>
          </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/hospital_notifications')?>"><button type="button" class="btn btn-danger">Cancel</button></a>-->
    </div></div>
</div>



<script>
$(document).ready(function () {

    // --- helpers ---
    function resetForm() {
        $('#inputform')[0].reset();
        $('.form-control').removeClass('is-valid is-invalid');

        // Reset custom dropdowns
        $('#userSearch').val('');
        $('#userSelect').val('').hide();

        $('#hospitalSearch').val('');
        $('#hospitalSelect').val('').hide();

        // Clear hidden fields
        $('#address_display').val('');
        $('#address_hidden').val('');
        $('#address_lat').val('');
        $('#address_lon').val('');
    }

    function validateForm() {
        let isValid = true;
        $('#inputform [required]').each(function () {
            let value = $(this).val();
            if (Array.isArray(value)) value = value.join('');
            value = value ? value.toString().trim() : '';

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

    // --- subscription check ---
    function checkUserSubscription(user_id, callback) {
        $.ajax({
            url: '<?= base_url("admin/register/check_user_subscription/"); ?>' + user_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
    
                    // ✅ Enable all fields except user search/select
                    $("#inputform :input").not('#userSearch, #userSelect').prop("disabled", false);
    
                    // --- populate family members dropdown ---
                    let familySelect = $("select[name='family_member_id']");
                    familySelect.empty();
                    familySelect.append('<option value="">Select Family Member</option>');
    
                    if (res.family_members && res.family_members.length > 0) {
                        res.family_members.forEach(function (member) {
                            familySelect.append(
                                `<option value="${member.id}">
                                    ${member.name} (${member.mobile || ''})
                                 </option>`
                            );
                        });
                    } else {
                        familySelect.append('<option value="">No Family Members Found</option>');
                    }
    
                } else {
                    showToast('Error', res.message, 'error');
    
                    // ❌ Disable all fields except user search/select
                    $("#inputform :input").not('#userSearch, #userSelect').prop("disabled", true);
    
                    $('#address_display, #address_hidden, #address_lat, #address_lon').val('');
    
                    // Reset family members dropdown
                    let familySelect = $("select[name='family_member_id']");
                    familySelect.empty().append('<option value="">Select Family Member</option>');
                }
    
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
    
                // ❌ Disable all fields except user search/select
                $("#inputform :input").not('#userSearch, #userSelect').prop("disabled", true);
    
                if (callback) callback(false);
            }
        });
    }


    // --- distance check ---
    function checkUserDistance(user_id, hospital_id, lat, lon, callback) {
        $.ajax({
            url: '<?= base_url("admin/register/check_user_distance/"); ?>',
            type: 'POST',
            data: { user_id, hospital_id, lat, lon },
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
                } else {
                    showToast('Error', res.message, 'error');
                }
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
                if (callback) callback(false);
            }
        });
    }
    
    //--- order type ---
    function getOrderType(hospital_id, callback) {
        $.ajax({
            url: '<?= base_url("admin/register/get_diagnostic_details/"); ?>' + hospital_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
                    $("#inputform :input").prop("disabled", false);
    
                    let ordertypeSelect = $("select[name='order_type']");
                    ordertypeSelect.empty();
                    ordertypeSelect.append('<option value="">Select Order Type</option>');
    
                    if (res.order_type && Object.keys(res.order_type).length > 0) {
                        $.each(res.order_type, function (key, value) {
                            ordertypeSelect.append(`<option value="${key}">${value}</option>`);
                        });
                    } else {
                        ordertypeSelect.append('<option value="">No Order Type Found</option>');
                    }
                } else {
                    showToast('Error', res.message, 'error');
                    let ordertypeSelect = $("select[name='order_type']");
                    ordertypeSelect.empty().append('<option value="">Select Order Type</option>');
                }
    
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
                if (callback) callback(false);
            }
        });
    }
    
    //--- address ---
    function getAddress(hospital_id,order_type,user_id,callback){
        $.ajax({
            url: '<?= base_url("admin/register/get_diagnostic_address/"); ?>' + hospital_id +'/'+ order_type +'/'+ user_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
                    $('#address_display').val(res.address);
                    $('#address_hidden').val(res.address_id);
                    $('#address_lat').val(res.lat);
                    $('#address_lon').val(res.lon);
                    $("#inputform :input").prop("disabled", false);
                } else {
                    showToast('Error', res.message, 'error');
                    $('#address_display, #address_hidden, #address_lat, #address_lon').val('');
                }
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
                if (callback) callback(false);
            }
        });
    }


    // --- events ---
    $('#userSelect').on('change', function () {
        let user_id = $(this).val();
        if (user_id) checkUserSubscription(user_id);
    });

    $('#saveBtn').on('click', function () {
        if (!validateForm()) {
            $('html, body').animate({
                scrollTop: $('.is-invalid:first').offset().top - 100
            }, 500);
            return;
        }


        // First check distance, then submit booking if OK

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

        $.ajax({
            url: '<?= base_url("admin/register/insert_diagnostic_prescription_booking"); ?>',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                const res = JSON.parse(response);
                if (res.success) {
                    showToast('Success', res.message, 'success');
                    resetForm();
                } else {
                    showToast('Error', res.message, 'error');
                }
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
            }
        });
    });

    // real-time input validation
    $('#inputform .form-control').on('input change', function () {
        if ($(this).val().trim()) {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });

});
</script>

<script>
    function filterUsers() {
      var input = document.getElementById("userSearch").value.toLowerCase();
      var select = document.getElementById("userSelect");
      var options = select.options;
      var found = false;
    
      for (var i = 0; i < options.length; i++) {
        var txt = options[i].text.toLowerCase();
        if (txt.includes(input)) {
          options[i].style.display = "";
          found = true;
        } else {
          options[i].style.display = "none";
        }
      }
    
      // Show dropdown only if search text is not empty
      select.style.display = input.length > 0 && found ? "block" : "none";
    }
</script>

<script>
    function filterHospitals() {
      var input = document.getElementById("hospitalSearch").value.toLowerCase();
      var select = document.getElementById("hospitalSelect");
      var options = select.options;
      var found = false;
    
      for (var i = 0; i < options.length; i++) {
        var txt = options[i].text.toLowerCase();
        if (txt.includes(input)) {
          options[i].style.display = "";
          found = true;
        } else {
          options[i].style.display = "none";
        }
      }
    
      // Show dropdown only if search text is not empty and a match is found
      select.style.display = input.length > 0 && found ? "block" : "none";
    }
</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>
            