<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Hospital Diagnostic 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>
            
            <select class="form-select family-multi-select" 
                    name="family_member_id[]" 
                    required 
                    multiple 
                    id="family_memeber_id" 
                    placeholder="Family Member">
                <!-- options will be injected dynamically -->
            </select>
        </div>

          
            <div class="mb-3">
            <label for="stateSearch" class="form-label">States *</label>
        
            <!-- Search box -->
            <input type="text" id="stateSearch" class="form-control state-search" placeholder="Type state name" onkeyup="filterStates()">
        
            <!-- Dropdown -->
            <select id="stateSelect" name="state_id" class="form-select mt-2 state-select" size="5">
                <option value="" disabled selected>Select State</option>
                <?php if(!empty($states)){ 
                    foreach($states as $row){ ?>
                        <option value="<?= $row['id'] ?>"><?= $row['name'] ?></option>
                <?php } } ?>
            </select>
        </div>

          
          <div class="mb-3">
            <label for="district_id" class="form-label">Districts *</label>
            
            <!-- Search box -->
            <input type="text" id="districtSearch" class="form-control district-search" placeholder="Type district name" onkeyup="filterDistricts()">
        
            <!-- Dropdown (will be populated via JS) -->
            <select id="district_id" name="district_id" class="form-select mt-2 district-select" size="5" style="display:none;" >
                <option value="">Select District</option>
            </select>
        </div>

          
          <div class="mb-3">
            <label for="city_id" class="form-label">Cities *</label>
            
            <!-- Search box -->
            <input type="text" id="citySearch" class="form-control city-search" placeholder="Type city name" onkeyup="filterCities()">
        
            <!-- Dropdown (populated dynamically) -->
            <select class="form-select mt-2 city-select" name="city_id" id="city_id" placeholder="City" size="5" style="display:none;" >
                <option value="">Select City</option>
            </select>
        </div>

            
            <div class="mb-3">
                <label for="hospitalSearch" class="form-label">Hospitals *</label>
            
                <!-- Search box -->
                <input type="text" id="hospitalSearch" class="form-control" placeholder="Type hospital name, mobile, or location" onkeyup="filterHospitals()">
            
                <!-- Dropdown -->
                <select id="hospitalSelect" name="main_data_id" class="form-select mt-2 hospital-select" size="5" style="display:none;" required placeholder="Hospital">
                </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">Diagnostic 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 diagnostic 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 class="form-label">Apply Coupon</label>
                <div id="couponContainer" class="border rounded p-2" style="max-height: 200px; overflow-y:auto;">
                    <!-- Coupons will be loaded here dynamically -->
                    <p class="text-muted">Loading coupons...</p>
                </div>
            </div>
            
            <!-- add these hidden fields inside your <form> -->
            <input type="hidden" name="applied_coupon_idd" id="applied_coupon_idd" value="">
            <input type="hidden" name="applied_coupon_codee" id="applied_coupon_codee" value="">
            <input type="hidden" name="applied_coupon_discountt" id="applied_coupon_discountt" value="">
            <input type="hidden" name="applied_coupon_amountt" id="applied_coupon_amountt" 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;
}

/* State Search Input */
.state-search {
    border: 2px solid #007bff;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 15px;
    transition: all 0.3s ease;
}

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

/* State Dropdown */
.state-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 */
.state-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 */
.state-select option:hover,
.state-select option:focus {
    background: #e6f2ff;
    color: #007bff;
}

/* Disabled placeholder option */
.state-select option[value=""] {
    color: #888;
    font-style: italic;
}


/* District Search Input */
.district-search {
    border: 2px solid #fd7e14;   /* orange */
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 15px;
    transition: all 0.3s ease;
}

.district-search:focus {
    border-color: #e8590c;
    box-shadow: 0 0 6px rgba(253, 126, 20, 0.4);
    outline: none;
}

/* District Dropdown */
.district-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;
    overflow-y: auto;
}

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

/* Hover / Focus */
.district-select option:hover,
.district-select option:focus {
    background: #fff4e6;
    color: #fd7e14;
}

/* Placeholder option */
.district-select option[value=""] {
    color: #888;
    font-style: italic;
}

/* City Search Input */
.city-search {
    border: 2px solid #20c997;   /* teal */
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 15px;
    transition: all 0.3s ease;
}

.city-search:focus {
    border-color: #0ca678;
    box-shadow: 0 0 6px rgba(32, 201, 151, 0.4);
    outline: none;
}

/* City Dropdown */
.city-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;
    overflow-y: auto;
}

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

/* Hover / Focus */
.city-select option:hover,
.city-select option:focus {
    background: #e6fcf5;
    color: #0ca678;
}

/* Placeholder option */
.city-select option[value=""] {
    color: #888;
    font-style: italic;
}

/* Multi-select Family Members */
.family-multi-select {
    border: 2px solid #51cf66;   /* green border */
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 14px;
    color: #333;
    background: #fff;
    min-height: 120px; /* taller box for multiple selection */
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    transition: all 0.2s ease;
}

/* Focus effect */
.family-multi-select:focus {
    border-color: #2b8a3e;
    box-shadow: 0 0 0 3px rgba(81, 207, 102, 0.25);
    outline: none;
}

/* Option styling */
.family-multi-select option {
    padding: 8px 10px;
    margin: 2px 0;
    border-radius: 4px;
    transition: background 0.2s;
}

/* Hover effect */
.family-multi-select option:hover {
    background: #d3f9d8; /* light green */
}

/* Selected option effect */
.family-multi-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_hospital_diagnostic_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>');
                    }
    
                } 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);
            }
        });
    }
    
    // --- hospitals check ---
    function getHospitals(state_id, district_id = '', city_id = '', callback) {
        $.ajax({
            url: '<?= base_url("admin/register/get_hospitals_data"); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                state_id: state_id,
                district_id: district_id,
                city_id: city_id
            },
            success: function (res) {
                let hospitalSelect = $("#hospitalSelect");
                hospitalSelect.empty();
    
                if (res.success && res.hospitals.length > 0) {
                    res.hospitals.forEach(function (hos) {
                        $("#hospitalSelect").append(
                            `<option value="${hos.id}">
                                ${hos.name} (${hos.mobile}) - ${hos.address}
                            </option>`
                        );
                    });

                    hospitalSelect.show();
                } else {
                    hospitalSelect.append('<option value="">No Hospitals Found</option>').show();
                }
    
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'Failed to load hospitals', 'error');
                if (callback) callback(false);
            }
        });
    }

    
    // --- districts check ---
    function getDistricts(state_id, callback) {
        $.ajax({
            url: '<?= base_url("admin/register/get_districts_data/"); ?>' + state_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
                    let districtSelectt = $("#district_id");
                    districtSelectt.empty();
    
                    // --- populate family members dropdown ---
                    let districtSelect = $("select[name='district_id']");
                    districtSelect.empty(); // clear old options
                    districtSelect.append('<option value="">Select District</option>');
    
                    if (res.districts && res.districts.length > 0) {
                        res.districts.forEach(function (dis) {
                            districtSelect.append(
                                `<option value="${dis.id}">
                                    ${dis.name}
                                 </option>`
                            );
                        });
                        districtSelectt.show();
                    } else {
                        districtSelect.append('<option value="">No District Found</option>');
                    }
    
                } else {
                    showToast('Error', res.message, 'error');
                
                    // Reset family members dropdown
                    let districtSelect = $("select[name='district_id']");
                    districtSelect.empty().append('<option value="">Select District</option>');
                }
    
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
    
                if (callback) callback(false);
            }
        });
    }
    
    // --- cities check ---
    function getCities(state_id,district_id, callback) {
        $.ajax({
            url: '<?= base_url("admin/register/get_cities_data/"); ?>' + state_id + '/'+ district_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    showToast('Success', res.message, 'success');
                    
                    let cityySelectt = $("#city_id");
                    cityySelectt.empty();
    
                    // --- populate family members dropdown ---
                    let citySelect = $("select[name='city_id']");
                    citySelect.empty(); // clear old options
                    citySelect.append('<option value="">Select City</option>');
    
                    if (res.cities && res.cities.length > 0) {
                        res.cities.forEach(function (city) {
                            citySelect.append(
                                `<option value="${city.id}">
                                    ${city.name}
                                 </option>`
                            );
                        });
                        cityySelectt.show();
                    } else {
                        districtSelect.append('<option value="">No City Found</option>');
                    }
    
                } else {
                    showToast('Error', res.message, 'error');
                
                    // Reset family members dropdown
                    let citySelect = $("select[name='city_id']");
                    //districtSelect.empty().append('<option value="">Select District</option>');
                }
    
                if (callback) callback(res.success);
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
    
                if (callback) callback(false);
            }
        });
    }

    let currentPage = 1;
    let hasMore = true;
    let isLoading = false;
    let currentSearch = "";
    
    function renderSearchBox() {
        if ($("#diagnosticContainer #diagnosticSearch").length === 0) {
            $("#diagnosticContainer").prepend(`
                <div class="mb-2">
                    <input type="text" id="diagnosticSearch" class="form-control" 
                           placeholder="Search diagnostic tests...">
                </div>
            `);
    
            // Bind search handler
            $("#diagnosticSearch").on("keyup", function () {
                currentSearch = $(this).val().trim();
                const hospital_id = $('#hospitalSelect').val();
                if (hospital_id) loadDiagnosticPackages(hospital_id, true);
            });
        }
    }
    
    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
            let container = $("#packagePricesContainer");
            container.empty();
            $('#consultation_fee').val('');
    
            // ✅ Reset applied selections when hospital changes
            $('#applied_coupon_id').val('');
            $(".applyCouponBtn").text("BOOK").removeClass("btn-success").addClass("btn-outline-primary");
        }
    
        $.ajax({
            url: '<?= base_url("admin/register/get_hospital_diagnostic_tests/"); ?>' + hospital_id,
            type: 'POST',
            data: {
                page: currentPage,
                search: currentSearch
            },
            dataType: 'json',
            success: function (res) {
                renderSearchBox(); // ensure search is always shown
                $("#diagnosticContainer").find("p.text-muted:contains('Loading diagnostic 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}">
                                        BOOK
                                      </button>
                                    </div>
                                </div>
                              </div>
                            </div>
                        `);
                    });
    
                    currentPage++;
                    hasMore = res.has_more;
                } else if (reset) {
                    if (reset) {
                        $("#diagnosticContainer").append('<p class="text-danger package-card">No packages found</p>');
                    }
                    showToast('Info', 'No packages available.', 'info');
                }
            },
            complete: function () {
                isLoading = false;
            },
            error: function () {
                $("#diagnosticContainer").append('<p class="text-danger package-card">Failed to load packages</p>');
                isLoading = false;
            }
        });
    }
    
    // ================= EVENT BINDINGS =================
    
    // ✅ Test details modal
    $(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_hospital_diagnostic_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', 'An unexpected error occurred.', 'error');
            }
        });
    });
    
    // ✅ Apply coupon button
    $(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('');
    
        // AJAX fetch prices
        $.ajax({
            url: '<?= base_url("admin/register/get_hospital_diagnostic_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>
                        `);
                    });
    
                    // ✅ Remove old handlers and bind fresh (prevents duplicate toasts)
                    $(document).off('change', 'input[name="fee"]').on('change', 'input[name="fee"]', function () {
                        const selectedPersons = parseInt($(this).data('persons'), 10) || 0;
                        const members = $('#family_memeber_id').val();
                        const selectedMembers = Array.isArray(members) ? members.filter(v => v).length : (members ? 1 : 0);
    
                        if (selectedPersons > 0 && selectedMembers !== selectedPersons) {
                            showToast('Error', `Please select exactly ${selectedPersons} family member(s).`, 'error');
                            $(this).prop('checked', false);
                            $('#consultation_fee').val('');
                            $('.applyCouponBtnn').text('APPLY').removeClass('btn-success').addClass('btn-outline-primary');
                            return;
                        }
    
                        //const discount = parseFloat($('#flat_discount').val()) || 0;
                        const original = parseFloat($(this).val()) || 0;
                        let newTotal = original;
    
                        //if (discount === 0) {
                            $('#consultation_fee').val(original);
                        /*} else {
                            const discountAmount = Math.round(original * discount / 100);
                            newTotal = original - discountAmount;
                            $('#consultation_fee').val(newTotal);
                            showToast('Success', `Flat discount of ${discount}% applied! Final price: ₹${newTotal}`, 'success');
                        }*/
                    });
    
                    // ✅ Revalidate on family member change
                    $(document).off('change', '#family_memeber_id').on('change', '#family_memeber_id', function () {
                        const $checked = $('input[name="fee"]:checked');
                        if ($checked.length) $checked.trigger('change');
                    });
    
                } 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');
    });

    
    // 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_hospital_diagnostic_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);
                loadCoupons();
                
            } else {
                showToast('Error', 'No available dates found', 'error');
                document.getElementById("date").value = "";
            }
        },
        error: function () {
            showToast('Error', 'Failed to load diagnostic dates', 'error');
        }
    });
}

    function loadCoupons() {
        let fee_val =  $('#fee').val();
        if (fee_val != 0) {
            $.ajax({
                url: '<?= base_url("admin/register/get_hospital_diagnostic_couponss"); ?>',
                type: 'POST',
                dataType: 'json',
                success: function (res) {
                    let container = $("#couponContainer");
                    container.empty();
        
                    if (res.success && res.coupons && res.coupons.length > 0) {
                        // Save original fee for reference
                        window.originalConsultationFee = Math.round(parseFloat($("#fee").val()) || 0);
        
                        // Clear hidden coupon fields
                        $('#applied_coupon_idd,#applied_coupon_codee,#applied_coupon_discountt,#applied_coupon_amountt').val('');
        
                        // Render coupon cards
                        res.coupons.forEach(coupon => {
                            const id = coupon.id || '';
                            const code = coupon.code || coupon.name || '';
                            const percentage = coupon.percentage || coupon.discount || 0;
                            const description = coupon.description || '';
        
                            container.append(`
                                <div class="card mb-2 border">
                                  <div class="card-body p-2">
                                    <h6 class="mb-1">${coupon.name}</h6>
                                    <p class="small mb-1">${description}</p>
                                    <div class="d-flex justify-content-between align-items-center">
                                      <span class="badge bg-danger">${code}</span>
                                      <button type="button" class="btn btn-sm btn-outline-primary applyCouponBtnn"
                                              data-id="${id}"
                                              data-code="${code}"
                                              data-discount="${percentage}">
                                        APPLY
                                      </button>
                                    </div>
                                  </div>
                                </div>
                            `);
                        });
        
                        // Bind coupon apply/unapply
                        $(document).off('click', '.applyCouponBtnn').on('click', '.applyCouponBtnn', function () {
                            const btn = $(this);
                            const couponId = btn.data('id').toString();
                            const code = btn.data('code').toString();
                            const discount = parseFloat(btn.data('discount')) || 0;
                        
                            // Always parse as float for calculations
                            const original = parseFloat($('input[name="fee"]:checked').val() || 0);
                        
                            if (!original || isNaN(original)) {
                                showToast('Error', `Please select a package before applying coupon!`, 'error');
                                return; // stop execution if no fee selected
                            }
                        
                            // If same coupon clicked again → unapply
                            if ($('#applied_coupon_idd').val() === couponId) {
                                $('#consultation_fee').val(original);
                        
                                $('#applied_coupon_idd').val('');
                                $('#applied_coupon_codee').val('');
                                $('#applied_coupon_discountt').val('');
                                $('#applied_coupon_amountt').val('');
                        
                                btn.text('APPLY').removeClass('btn-success').addClass('btn-outline-primary');
                                showToast('Info', `Coupon ${code} removed.`, 'info');
                                return;
                            }
                        
                            // Reset all buttons to default
                            $('.applyCouponBtnn').text('APPLY').removeClass('btn-success').addClass('btn-outline-primary');
                        
                            // Apply new coupon
                            const discountAmount = Math.round(original * discount / 100);
                            const newTotal = original - discountAmount;
                        
                            $('#consultation_fee').val(newTotal);
                        
                            $('#applied_coupon_idd').val(couponId);
                            $('#applied_coupon_codee').val(code);
                            $('#applied_coupon_discountt').val(discount);
                            $('#applied_coupon_amountt').val(discountAmount);
                        
                            btn.text('APPLIED').removeClass('btn-outline-primary').addClass('btn-success');
                            showToast('Success', `Coupon ${code} applied. You saved ₹${discountAmount}!`, 'success');
                        });

        
                    } else {
                        container.html('<p class="text-danger">No coupons available</p>');
                    }
                },
                error: function () {
                    $("#couponContainer").html('<p class="text-danger">Failed to load coupons</p>');
                }
            });
        }
    }

    // --- 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);
        }
    });
    
    $('#stateSelect').on('change', function () {
        let state_id = $(this).val();
        if (state_id) {
            getDistricts(state_id);
            getHospitals(state_id); // load hospitals by state
        }
    });

    $('#district_id').on('change', function () {
        let state_id = $('#stateSelect').val();
        let district_id = $(this).val();
        if (state_id && district_id) {
            getCities(state_id, district_id);
            getHospitals(state_id, district_id); // load hospitals by state + district
        }
    });

    $('#city_id').on('change', function () {
        let state_id = $('#stateSelect').val();
        let district_id = $('#district_id').val();
        let city_id = $(this).val();
        if (state_id && district_id && city_id) {
            getHospitals(state_id, district_id, city_id); // load hospitals by state + district + city
        }
    });

    $('#saveBtn').on('click', function () {
        if (!validateForm()) return;
    
        const form = $('#inputform')[0];
        const formData = new FormData(form);
    
        $.ajax({
            url: '<?= base_url("admin/register/create_hospital_diagnostic_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 filterStates() {
      var input = document.getElementById("stateSearch").value.toLowerCase();
      var select = document.getElementById("stateSelect");
      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 filterDistricts() {
      var input = document.getElementById("districtSearch").value.toLowerCase();
      var select = document.getElementById("district_id");
      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 filterCities() {
      var input = document.getElementById("citySearch").value.toLowerCase();
      var select = document.getElementById("city_id");
      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; ?>