این کد رو برام بهینه کن

async function timeToMinutes(time) {
    const [hours, minutes] = time.split(':').map(Number);
    return hours * 60 + minutes;
}

async function gregorianToJalali(gy, gm, gd) {
    const g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    const j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];

    gy -= 1600;
    gm -= 1;
    gd -= 1;

    let g_day_no = 365 * gy + Math.floor((gy + 3) / 4) - Math.floor((gy + 99) / 100) + Math.floor((gy + 399) / 400);

    for (let i = 0; i < gm; ++i) {
        g_day_no += g_days_in_month[i];
    }

    if (gm > 1 && ((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0))) {
        g_day_no++;
    }
    g_day_no += gd;

    let j_day_no = g_day_no - 79;
    const j_np = Math.floor(j_day_no / 12053);
    j_day_no %= 12053;

    let jy = 979 + 33 * j_np + 4 * Math.floor(j_day_no / 1461);
    j_day_no %= 1461;

    if (j_day_no >= 366) {
        jy += Math.floor((j_day_no - 1) / 365);
        j_day_no = (j_day_no - 1) % 365;
    }

    let jm;
    for (jm = 0; jm < 11 && j_day_no >= j_days_in_month[jm]; ++jm) {
        j_day_no -= j_days_in_month[jm];
    }

    const jd = j_day_no + 1;
    return [jy, jm + 1, jd];
}

async function calculateFirstAvailableSlot(data) {
    const startMinutes = await timeToMinutes(data.starttime);
    const endMinutes = await timeToMinutes(data.endtime);
    const totalSlots = (endMinutes - startMinutes) / data.time_each_visit;

    const totalReserved = data.reserved_internet_turn + data.reserved_manualt_turn + data.reserved_organization_turn;

    if (totalReserved < totalSlots) {
        const firstAvailableSlotMinutes = startMinutes + totalReserved * data.time_each_visit;
        const hours = Math.floor(firstAvailableSlotMinutes / 60);
        const minutes = firstAvailableSlotMinutes % 60;
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;

        const [gy, gm, gd] = data.visit_date.split('-').map(Number);
        const [jy, jm, jd] = await gregorianToJalali(gy, gm, gd);

        return `${timeString} ${jy}/${jm.toString().padStart(2, '0')}/${jd.toString().padStart(2, '0')}`;
    } else {
        return "زمانی برای ویزیت خالی نیست.";
    }
}

async function get_data() {
    const url = 'http://localhost/TakingTurns/visits/';

    try {
        const response = await send_requests(url, {}, 'GET');

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        return await response.json();
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

async function addRow(data) {
    const bodyTable = document.getElementById("data_table");

    for (const [index, item] of data.entries()) {
        const firstAvailableSlot = await calculateFirstAvailableSlot(item);

        bodyTable.insertAdjacentHTML('beforeend', `
            <tr>
                <td>${item.doctor}</td>
                <td>${"اطفال"}</td>
                <td>${item.medical_center}</td>
                <td>${firstAvailableSlot}</td>
                <td><button class="btn btn-primary waves-effect waves-light" data-bs-target="#editUser" data-bs-toggle="modal" type="button" id="data-${index}">نمایش</button></td>
            </tr>
        `);
    }
}

document.addEventListener('DOMContentLoaded', async function() {
    var data_visit = await get_data();
    if (data_visit.length) {
        await addRow(data_visit);
    }
});

document.getElementById('filterInput').addEventListener('input', async function() {
    const filterValue = this.value.toLowerCase();
    const rows = document.querySelectorAll('#data_table tr');

    for (let row of rows) {
        await filterRow(row, filterValue);
    }
});

async function filterRow(row, filterValue) {
    const cells = row.querySelectorAll('td');
    const match = Array.from(cells).some(cell => cell.textContent.toLowerCase().includes(filterValue));
    row.style.display = match ? '' : 'none';
}

document.addEventListener('click', (event) => {
    // مطمئن می‌شویم که عنصر کلیک‌شده دکمه‌ای با کلاس‌های مشخص شده باشد
    if (event.target.matches('.btn.btn-primary.waves-effect.waves-light')) {
        const buttonId = event.target.id;
        const index = parseInt(buttonId.split('-')[1], 10);
        add_button(data_visit[index]);
    }
});

async function add_button(data) {
    
// تبدیل زمان به دقیقه
const timeToMinutes = time => {
    const [hours, minutes] = time.split(':').map(Number);
    return hours * 60 + minutes;
};

// محاسبه زمان‌های قابل رزرو به صورت لیست
const generateTimeSlots = (startTime, endTime, timeEachVisit, reservations) => {
    let slots = [];
    const startMinutes = timeToMinutes(startTime);
    const endMinutes = timeToMinutes(endTime);
    const totalSlots = (endMinutes - startMinutes) / timeEachVisit;

    for (let i = 0; i < totalSlots; i++) {
        const slotStart = startMinutes + i * timeEachVisit;
        const hours = Math.floor(slotStart / 60);
        const minutes = slotStart % 60;
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
        const reserved = i < reservations;
        slots.push({ time: timeString, reserved });
    }

    return slots;
};

// اضافه کردن اطلاعات به DOM
const slots = generateTimeSlots(data.starttime, data.endtime, data.time_each_visit, data.reserved_internet_turn + data.reserved_manualt_turn + data.reserved_organization_turn);

document.getElementById('visitInfo').insertAdjacentHTML('beforeend', `
    <div class="col-12 col-md-6">
        <strong>نام دکتر:</strong> ${data.doctor}
    </div>
    <div class="col-12 col-md-6">
        <strong>تخصص:</strong> ${data.specialty}
    </div>
    <div class="col-12 col-md-6">
        <strong>تاریخ ویزیت:</strong> ${data.visit_date}
    </div>
    <div class="col-12 col-md-6">
        <strong>مرکز درمانی:</strong> ${data.medical_center}
    </div>
    <div class="col-12">
        <strong>زمان‌های قابل رزرو:</strong>
        <ul class="list-group">
            ${slots.map(slot => `
                <li class="list-group-item ${slot.reserved ? 'disabled' : 'list-group-item-action'}">
                    ${slot.time} ${slot.reserved ? '(رزرو شده)' : '<button class="btn btn-sm btn-primary">رزرو</button>'}
                </li>
            `).join('')}
        </ul>
    </div>
`);
}