<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Lab Test 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" class="form-label">Users *</label>
        
            <!-- Search box -->
            <input type="text" id="userSearch" class="form-control user-search" placeholder="Type name, mobile, or unique ID" onkeyup="filterUsers()">
        
            <!-- Dropdown -->
            <select id="userSelect" name="user_id" class="form-select mt-2 user-select" size="5" 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="family_memeber_id" class="form-label">Family Members *</label>
            
            <!-- Multi Select -->
            <select class="form-select family-select" 
                    name="family_member_id[]" 
                    required 
                    placeholder="Family Member" 
                    multiple 
                    id="family_memeber_id" size="6">
                <option value="">Select Family Member</option>
            </select>
        </div>

          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Address *</label>
            <!-- Visible input -->
            <textarea
                class="form-control"
                id="address_display"
                placeholder="Address"
                name="address_display"
                readonly required>
            </textarea>
            
            <!-- Hidden input to submit actual address -->
            <input type="hidden" name="address" id="address_hidden" />
            
            <!-- Hidden input to lat -->
            <input type="hidden" name="lat" id="address_lat" />
            
            <!-- Hidden input to lon -->
            <input type="hidden" name="lon" id="address_lon" />

          </div>
          
            <div class="mb-3">
                <label for="hospitalSearch" class="form-label">Labs *</label>
            
                <!-- Search box -->
                <input type="text" id="hospitalSearch" class="form-control" placeholder="Type lab name, mobile, or location" onkeyup="filterHospitals()">
            
                <!-- Dropdown -->
                <select id="hospitalSelect" name="main_data_id" class="form-select mt-2 hospital-select" size="5"  required placeholder="Lab">
                    <?php if(!empty($hospitals)){ 
                        foreach($hospitals as $roww){ ?>
                            <option value="<?= $roww['id'] ?>"><?= $roww['name'] ?> (<?= $roww['mobile'] ?>) - <?=$roww['location']?></option>
                    <?php } } ?>
                </select>
            </div>
            
            <input type="hidden" name="flat_discount" class="form-control" placeholder="Flat Discount" id="flat_discount" readonly>
            
            <div class="mb-3">
                <label class="form-label">Lab Tests</label>
                <div id="diagnosticContainer" class="border rounded p-2" style="max-height: 200px; overflow-y:auto;">
                    <!-- Search + packages will be injected dynamically -->
                    <p class="text-muted">Loading lab test packages...</p>
                </div>
            </div>
            
            <div id="packagePricesContainer" class="mt-3"></div>
         
            <div class="mb-3">
                <label for="consultation_fee" class="form-label">Total Fee *</label>
                <input type="text" name="consultation_fee" class="form-control" placeholder="Consultation Fee" id="consultation_fee" required readonly>
            </div>
            
            <!-- add these hidden fields inside your <form> -->
            <input type="hidden" name="applied_coupon_id" id="applied_coupon_id" value="">
            
            <div class="mb-3">
                <label for="datePicker" class="form-label">Dates *</label>
                <input type="text" name="date" class="form-control" placeholder="Date" id="date" required>
            </div>
            
            
            <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">Time Slots *</label>
                <div id="slotContainer">
                    <p class="text-muted">Please select a date to view available slots.</p>
                </div>
            </div>
            
            <div class="mb-3">
            <label for="userSearch">Prescription </label>
                <input type="file" id="prescription" class="form-control" placeholder="Image" name="image">
                <p style="color:red">upload only jpg,jpeg,png or pdf files</p>
        </div>
        
        </div>
      </div>
      
        
      
        <input type="hidden" id="cashfree_order_id" name="cashfree_order_id">
        <input type="hidden" id="cashfree_order_token" name="cashfree_order_token">
        <input type="hidden" id="payment_status" name="payment_status" value="pending">

       <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>

<style>
    /* Hospital Search Input */
#hospitalSearch {
    border: 2px solid #007bff;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 15px;
    transition: all 0.3s ease;
}

#hospitalSearch:focus {
    border-color: #0056b3;
    box-shadow: 0 0 6px rgba(0, 123, 255, 0.5);
    outline: none;
}

/* Hospital Dropdown */
.hospital-select {
    border: 1.5px solid #ddd;
    border-radius: 8px;
    padding: 6px;
    font-size: 14px;
    color: #333;
    background: #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    max-height: 220px; /* prevents very long list */
    overflow-y: auto;
}

/* Dropdown options */
.hospital-select option {
    padding: 10px;
    font-size: 14px;
    line-height: 1.4;
    white-space: normal;   /* allow wrapping */
    word-wrap: break-word;
    border-bottom: 1px solid #f0f0f0;
}

/* Highlight on hover */
.hospital-select option:hover,
.hospital-select option:focus {
    background: #f1f9ff;
    color: #007bff;
}

/* First option when no results */
.hospital-select option[value=""] {
    color: #888;
    font-style: italic;
}

/* User Search Input */
.user-search {
    border: 2px solid #28a745;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 15px;
    transition: all 0.3s ease;
}

.user-search:focus {
    border-color: #1e7e34;
    box-shadow: 0 0 6px rgba(40, 167, 69, 0.4);
    outline: none;
}

/* User Dropdown */
.user-select {
    border: 1.5px solid #ddd;
    border-radius: 8px;
    padding: 6px;
    font-size: 14px;
    color: #333;
    background: #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    max-height: 220px; /* limit list height */
    overflow-y: auto;
}

/* Dropdown options */
.user-select option {
    padding: 10px;
    font-size: 14px;
    line-height: 1.4;
    white-space: normal;   /* allow wrapping */
    word-wrap: break-word;
    border-bottom: 1px solid #f5f5f5;
}

/* Hover / Focus effect */
.user-select option:hover,
.user-select option:focus {
    background: #e6f9ee;
    color: #28a745;
}

/* First option if no users */
.user-select option[value=""] {
    color: #888;
    font-style: italic;
}

/* Family Member Multi Select */
.family-select {
    border: 2px solid #51cf66;   /* green */
    border-radius: 8px;
    padding: 8px;
    font-size: 14px;
    color: #333;
    background: #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    max-height: 240px;
    overflow-y: auto;
}

/* Options inside multi-select */
.family-select option {
    padding: 10px;
    margin: 2px 0;
    border-radius: 6px;
    font-size: 14px;
    line-height: 1.4;
}

/* Hover */
.family-select option:hover {
    background: #ebfbee;
    color: #2b8a3e;
}

/* Selected option */
.family-select option:checked {
    background: #51cf66;
    color: #fff;
}

</style>

<!-- Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<!-- Flatpickr JS -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const dateInput = document.getElementById('date');
    const slotContainer = document.getElementById('slotContainer');

    // Set today's date as minimum
    const today = new Date().toISOString().split('T')[0];
    dateInput.setAttribute('min', today);

    // Load slots on date change
    dateInput.addEventListener('change', function () {
        const selectedDate = this.value;
        const hospital_id = document.getElementById('hospitalSelect').value; 

        if (!selectedDate || !hospital_id) {
            slotContainer.innerHTML = '<p class="text-danger">Please select hospital & date first.</p>';
            return;
        }

        fetch("<?= base_url('admin/register/get_lab_test_slots_by_date') ?>", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "date=" + encodeURIComponent(selectedDate) 
                + "&hospital_id=" + encodeURIComponent(hospital_id)
        })
        .then(response => response.json())
        .then(slots => {
            let html = '';
            const sections = ['morning', 'afternoon', 'evening'];
            let hasSlots = false;

            sections.forEach(section => {
                if (slots[section] && slots[section].length > 0) {
                    hasSlots = true;
                    html += `<div class="mb-2"><strong>${section.charAt(0).toUpperCase() + section.slice(1)}</strong><br>`;
                    slots[section].forEach((slot, i) => {
                        const id = `${section}_${i}`;
                        const isBooked = slot.booking_status === 'booked';
            
                        html += `
                            <label for="${id}" class="me-2 ${isBooked ? 'text-muted' : ''}">
                                <input type="checkbox" class="slot-checkbox" 
                                       name="time" id="${id}" 
                                       value="${slot.id}" 
                                       ${isBooked ? 'disabled' : ''}> 
                                ${slot.time} ${isBooked ? '(Booked)' : ''}
                            </label>`;
                    });
                    html += `</div>`;
                }
            });


            if (!hasSlots) {
                html = '<p class="text-danger">No available slots for the selected date.</p>';
            }

            slotContainer.innerHTML = html;

            // enforce only one checkbox at a time
            slotContainer.querySelectorAll('.slot-checkbox').forEach(cb => {
                cb.addEventListener('change', function () {
                    if (this.checked) {
                        slotContainer.querySelectorAll('.slot-checkbox').forEach(other => {
                            if (other !== this) other.checked = false;
                        });
                    }
                });
            });
        })
        .catch(err => {
            slotContainer.innerHTML = '<p class="text-danger">Failed to load slots. Please try again.</p>';
            console.error(err);
        });
    });
});
</script>

<!-- Sandbox -->
<script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>

<!-- For production later -->
 <!--<script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>-->

<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();

    }

    function validateForm() {
        let isValid = true;
        $('#inputform [required]').each(function () {
            let value = $(this).val();
    
            // Special handling for flatpickr
            if ($(this).attr('id') === 'date' && $(this)[0]._flatpickr) {
                value = $(this)[0]._flatpickr.input.value; 
            }
    
            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;
            }
            $(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 inputs
                    $("#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="" disabled>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>');
                    }
                    
                    // Populate address if subscription is valid
                    $('#address_display').val(res.address);
                    $('#address_hidden').val(res.address_id);
                    $('#address_lat').val(res.lat);
                    $('#address_lon').val(res.lon);
    
                } else {
                    showToast('Error', res.message, 'error');
    
                    // ❌ Disable all fields except user inputs
                    $("#inputform :input").not('#userSearch, #userSelect').prop("disabled", true);
    
                    $('#address_display, #address_hidden, #address_lat, #address_lon').val('');
    
                    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 inputs
                $("#inputform :input").not('#userSearch, #userSelect').prop("disabled", true);
    
                if (callback) callback(false);
            }
        });
    }

    let currentPage = 1;
    let hasMore = true;
    let isLoading = false;
    let currentSearch = "";
    
    // Render search box once
    function renderSearchBox() {
        if ($("#diagnosticContainer #diagnosticSearch").length === 0) {
            $("#diagnosticContainer").prepend(`
                <div class="mb-2">
                    <input type="text" id="diagnosticSearch" class="form-control" 
                           placeholder="Search lab tests...">
                </div>
            `);
    
            // Bind search handler once
            $("#diagnosticSearch").on("keyup", function () {
                currentSearch = $(this).val().trim();
                const hospital_id = $('#hospitalSelect').val();
                if (hospital_id) loadDiagnosticPackages(hospital_id, true);
            });
        }
    }
    
    // Load lab test packages
    function loadDiagnosticPackages(hospital_id, reset = false) {
        if (isLoading || (!hasMore && !reset)) return;
        isLoading = true;
        const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";
    
        if (reset) {
            currentPage = 1;
            hasMore = true;
            $("#diagnosticContainer").find(".package-card").remove(); // clear old cards but keep search
            $("#packagePricesContainer").empty();
            $('#consultation_fee').val('');
            $('#applied_coupon_id').val(''); // ✅ clear selected package
        }
    
        $.ajax({
            url: '<?= base_url("admin/register/get_labb_tests/"); ?>' + hospital_id,
            type: 'POST',
            data: {
                page: currentPage,
                search: currentSearch
            },
            dataType: 'json',
            success: function (res) {
                renderSearchBox();
                $("#diagnosticContainer").find("p.text-muted:contains('Loading lab test packages')").remove();
    
                if (res.success && res.packages.length > 0) {
                    res.packages.forEach(pkg => {
                        const id        = pkg.id || '';
                        const name      = pkg.name || '';
                        const image     = pkg.image || '';
                        const onePerson = pkg.one_person || 0;
                        const discount  = pkg.one_person_discount || 0;
                        const reportIn  = pkg.report_in || '';
                        const fasting   = pkg.fasting || '';
                        const count     = pkg.total_test_count || 0;
    
                        const imgSrc = `${bharosa_base_url}${image}`;
    
                        $("#diagnosticContainer").append(`
                            <div class="card mb-2 border package-card">
                              <div class="card-body p-2 d-flex">
                            <div class="me-3">
                                <img src="${imgSrc}" 
                                   alt="${name}" 
                                   class="rounded-circle" 
                                   width="48" height="48"
                                   onerror="this.onerror=null; this.src='<?= base_url("assets/admin/admin_logo.png"); ?>';">
                            </div>
                            <div class="flex-grow-1">
                                <h6 class="mb-1">${name}</h6>
                                <p class="small mb-1">Fee: ₹${onePerson} | Discount: ₹${discount}</p>
                                <p class="small mb-1">Fasting: ${fasting || 'No'}</p>
                                <p class="small mb-1">Report in: ${reportIn}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                  <span class="badge bg-danger view-test-details" data-count="${count}" data-id="${id}">
                                    Tests: ${count} <i class="fa fa-eye"></i>
                                  </span>
                                  <button type="button" class="btn btn-sm btn-outline-primary applyCouponBtn"
                                          data-id="${id}"
                                          data-code="${name}"
                                          data-discount="${discount}">
                                    APPLY
                                  </button>
                                </div>
                            </div>
                          </div>
                        </div>
                    `);
                });

                currentPage++;
                hasMore = res.has_more;
            } else if (reset) {
                $("#diagnosticContainer").append('<p class="text-danger package-card">No packages found</p>');
            }
        },
        complete: function () {
            isLoading = false;
        },
        error: function () {
            $("#diagnosticContainer").append('<p class="text-danger package-card">Failed to load packages</p>');
            isLoading = false;
        }
    });
}

/* ------------------ GLOBAL EVENT HANDLERS ------------------ */

// ✅ Prevent duplicate bindings
$(document).off('click', '.view-test-details').on('click', '.view-test-details', function (e) {
    e.preventDefault();
    const packageId = $(this).data('id');
    const count = $(this).data('count');

    $('#modalBookingIdd').text(packageId);
    $('#totalTestCount').text(count);

    $.ajax({
        url: '<?= base_url("admin/register/get_lab_tests_subtests/"); ?>' + packageId,
        type: 'POST',
        dataType: 'json',
        success: function (res) {
            if (res.success && res.tests.length > 0) {
                let html = '';
                res.tests.forEach(pkg => {
                    html += `<h5 class="fw-bold mt-3">${pkg.name}</h5><ul>`;
                    pkg.tests.forEach(test => {
                        html += `<li><strong>${test.name}</strong>`;
                        if (test.sub_tests && test.sub_tests.length > 0) {
                            html += '<ul>';
                            test.sub_tests.forEach(st => {
                                html += `<li>${st.name}</li>`;
                            });
                            html += '</ul>';
                        }
                        html += '</li>';
                    });
                    html += '</ul>';
                });

                $('#testDetailsContent').html(html);
                $('#testDetailsModal').modal('show');
            } else {
                $('#testDetailsContent').html('<p class="text-danger">No test details found.</p>');
                $('#testDetailsModal').modal('show');
            }
        },
        error: function () {
            showToast('Error', 'Failed to fetch test details', 'error');
        }
    });
});

// ✅ Handle package selection globally
$(document).off('click', '.applyCouponBtn').on('click', '.applyCouponBtn', function () {
    const btn = $(this);
    const packageId = btn.data('id').toString();
    const packageName = btn.data('code').toString();

    // If already selected → unselect
    if ($('#applied_coupon_id').val() === packageId) {
        $('#applied_coupon_id').val('');
        $('#packagePricesContainer').empty();
        $('#consultation_fee').val('');
        btn.text('BOOK').removeClass('btn-success').addClass('btn-outline-primary');
        showToast('Info', `${packageName} removed.`, 'info');
        return;
    }

    // Reset all buttons
    $('.applyCouponBtn').text('BOOK').removeClass('btn-success').addClass('btn-outline-primary');
    $('#applied_coupon_id').val(packageId);
    $('#consultation_fee').val('');

    // Fetch package prices
    $.ajax({
        url: '<?= base_url("admin/register/get_lab_test_package_prices/"); ?>' + packageId,
        type: 'POST',
        dataType: 'json',
        success: function (res) {
            let container = $("#packagePricesContainer");
            container.empty();

            if (res.success && res.prices.length > 0) {
                container.append(`<h6 class="mb-2">Book For</h6>`);

                res.prices.forEach(pric => {
                    if (!pric.original_price || !pric.discounted_price) return;

                    container.append(`
                        <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                            <label class="d-flex align-items-center mb-0 w-100">
                                <input type="radio" name="fee" value="${pric.discounted_price}"
                                       data-persons="${pric.persons_count}"
                                       class="me-2">
                                <span>${pric.persons_count} Patient${pric.persons_count > 1 ? 's' : ''}</span>
                            </label>
                            <div>
                                <span class="text-muted text-decoration-line-through me-2">₹${pric.original_price}</span>
                                <span class="fw-bold">₹${pric.discounted_price}</span>
                            </div>
                        </div>
                    `);
                });
            } else {
                container.html('<p class="text-danger">No Prices Found</p>');
            }
        },
        error: function () {
            showToast('Error', 'Failed to fetch package prices', 'error');
        }
    });

    btn.text('SELECTED').removeClass('btn-outline-primary').addClass('btn-success');
});

// ✅ Validate package selection (single binding)
$(document).off('change', 'input[name="fee"]').on('change', 'input[name="fee"]', function () {
    const selectedPersons = $(this).data('persons') || 0;
    const selectedMembers = $('#family_memeber_id option:selected').length;

    if (selectedPersons > 0 && selectedMembers !== selectedPersons) {
        showToast('Error', `Please select exactly ${selectedPersons} family member(s).`, 'error');
        $(this).prop('checked', false);
        $('#consultation_fee').val('');
        return;
    }

    let discount = parseFloat($('#flat_discount').val()) || 0;
    let original = parseFloat($(this).val()) || 0;
    let newTotal = original;

    if (discount === 0) {
        $("#consultation_fee").val(original);
        showToast('Info', `No flat discount applied. Price is ₹${original}`, 'info');
    } else {
        const discountAmount = Math.round(original * discount / 100);
        newTotal = original - discountAmount;
        $('#consultation_fee').val(newTotal);
        showToast('Success', `Flat discount of ${discount}% applied! You saved ₹${discountAmount}. Final price: ₹${newTotal}`, 'success');
    }
});

// ✅ Validate again when family members change
$(document).off('change', '#family_memeber_id').on('change', '#family_memeber_id', function () {
    const selectedPersons = $('input[name="fee"]:checked').data('persons') || 0;
    const selectedMembers = $('#family_memeber_id option:selected').length;

    if (selectedPersons > 0 && selectedMembers !== selectedPersons) {
        showToast('Error', `Please select exactly ${selectedPersons} family member(s).`, 'error');
        $('input[name="fee"]:checked').prop('checked', false);
        $('#consultation_fee').val('');
    }
});

    
    // Infinite scroll listener inside container
    $("#diagnosticContainer").on("scroll", function () {
        if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight - 50) {
            const hospital_id = $('#hospitalSelect').val();
            if (hospital_id) loadDiagnosticPackages(hospital_id);
        }
    });


    function getDiagnosticdates(hospital_id) {
    $.ajax({
        url: '<?= base_url("admin/register/get_lab_test_dates/"); ?>' + hospital_id,
        type: 'POST',
        dataType: 'json',
        success: function (res) {
            if (res.success && res.dates.length > 0) {
                // Extract Y-m-d format dates from backend response
                let enabledDates = res.dates.map(d => d.date);

                // Initialize Flatpickr
                flatpickr("#date", {
                    dateFormat: "Y-m-d",     // value stored in DB (hidden format)
                    altInput: true,
                    altFormat: "D d M Y",   // pretty UI format e.g. Thu 11 Sep 2025
                    minDate: "today",
                    enable: enabledDates    // âœ… only allow doctorâ€™s available dates
                });
                
                $('#flat_discount').val(res.dates[0].flat_discount);
                
            } else {
                showToast('Error', 'No available dates found', 'error');
                document.getElementById("date").value = "";
            }
        },
        error: function () {
            showToast('Error', 'Failed to load diagnostic dates', 'error');
        }
    });
}

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


    $('#saveBtn').on('click', function () {
        if (!validateForm()) return;
    
        const form = $('#inputform')[0];
        const formData = new FormData(form);
    
        $.ajax({
            url: '<?= base_url("admin/register/create_lab_test_cashfree_order"); ?>',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                let res = {};
                try {
                    res = JSON.parse(response);
                } catch (e) {
                    showToast('Error', 'Invalid response from server', 'error');
                    return;
                }
    
                // ✅ Handle slot not selected
                if (res.success === false) {
                    showToast('Error', res.message, 'error');
                    return;
                }
    
                // ✅ Normal Cashfree checkout
                if (res.payment_session_id) {
                    const cashfree = Cashfree({
                        mode: "sandbox" // or "production" or "sandbox"
                    });
    
                    cashfree.checkout({
                        paymentSessionId: res.payment_session_id,
                        redirectTarget: "_self"
                    });
                } else {
                    showToast('Error', 'Failed to create order', '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>

<!-- Tests Details Modal -->
<div class="modal fade" id="testDetailsModal" tabindex="-1" aria-labelledby="testDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          Contains <span id="totalTestCount"></span> tests
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="testDetailsContent"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- Tests Details Modal -->

<!-- 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>

<?php if($this->session->flashdata('success')): ?>
    <script>
        showToast('Success', "<?= $this->session->flashdata('success') ?>", 'success');
        
    </script>
<?php endif; ?>

<?php if($this->session->flashdata('error')): ?>
    <script>
        showToast('Error', '<?= $this->session->flashdata('error') ?>', 'error');
    </script>
<?php endif; ?>