/**
* قائمة جانبية المواعيد المتاحة
* Appointments Sidebar JavaScript
*/
class AppointmentsSidebar {
constructor() {
this.sidebar = null;
this.toggle = null;
this.overlay = null;
this.isOpen = false;
this.currentDate = new Date().toISOString().split('T')[0];
this.autoRefreshInterval = null;
this.refreshInterval = 30000; // 30 ثانية
this.init();
}
init() {
this.createSidebar();
this.createToggle();
this.createOverlay();
this.bindEvents();
this.loadAppointments();
this.startAutoRefresh();
}
createSidebar() {
this.sidebar = document.createElement('div');
this.sidebar.className = 'appointments-sidebar';
this.sidebar.innerHTML = `
`;
document.body.appendChild(this.sidebar);
}
createToggle() {
this.toggle = document.createElement('button');
this.toggle.className = 'sidebar-toggle';
this.toggle.innerHTML = 'المواعيد المتاحة';
this.toggle.title = 'فتح قائمة المواعيد المتاحة';
document.body.appendChild(this.toggle);
}
createOverlay() {
this.overlay = document.createElement('div');
this.overlay.className = 'sidebar-overlay';
document.body.appendChild(this.overlay);
}
bindEvents() {
// زر التبديل
this.toggle.addEventListener('click', () => {
this.toggleSidebar();
});
// النقر على الخلفية لإغلاق القائمة
this.overlay.addEventListener('click', () => {
this.closeSidebar();
});
// تغيير التاريخ
const dateInput = this.sidebar.querySelector('#sidebarDate');
dateInput.addEventListener('change', (e) => {
this.currentDate = e.target.value;
this.loadAppointments();
});
// زر التحديث
const refreshBtn = this.sidebar.querySelector('#refreshBtn');
refreshBtn.addEventListener('click', () => {
this.loadAppointments();
this.animateRefresh();
});
// إغلاق بـ ESC
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.isOpen) {
this.closeSidebar();
}
});
// إغلاق عند تغيير حجم النافذة
window.addEventListener('resize', () => {
if (window.innerWidth < 768 && this.isOpen) {
this.closeSidebar();
}
});
}
toggleSidebar() {
if (this.isOpen) {
this.closeSidebar();
} else {
this.openSidebar();
}
}
openSidebar() {
this.isOpen = true;
this.sidebar.classList.add('open');
this.toggle.classList.add('open');
this.overlay.classList.add('open');
document.body.style.overflow = 'hidden';
// تحميل البيانات إذا لم تكن محملة
if (this.sidebar.querySelector('.loading')) {
this.loadAppointments();
}
}
closeSidebar() {
this.isOpen = false;
this.sidebar.classList.remove('open');
this.toggle.classList.remove('open');
this.overlay.classList.remove('open');
document.body.style.overflow = 'auto';
}
async loadAppointments() {
const appointmentsList = this.sidebar.querySelector('#appointmentsList');
// عرض حالة التحميل
appointmentsList.innerHTML = `
`;
try {
const response = await fetch(`api/get-available-appointments.php?date=${this.currentDate}`);
const data = await response.json();
if (data.success) {
this.updateStats(data.stats);
this.renderAppointments(data);
} else {
this.showError(data.message);
}
} catch (error) {
console.error('خطأ في تحميل المواعيد:', error);
this.showError('خطأ في الاتصال بالخادم');
}
}
updateStats(stats) {
this.sidebar.querySelector('#availableCount').textContent = stats.available;
this.sidebar.querySelector('#confirmedCount').textContent = stats.confirmed;
this.sidebar.querySelector('#waitingCount').textContent = stats.waiting;
this.sidebar.querySelector('#totalCount').textContent = stats.total;
}
renderAppointments(data) {
const appointmentsList = this.sidebar.querySelector('#appointmentsList');
if (data.available_slots.length === 0 &&
data.confirmed_appointments.length === 0 &&
data.waiting_appointments.length === 0) {
appointmentsList.innerHTML = `
لا توجد مواعيد
لا توجد مواعيد متاحة أو محجوزة في هذا التاريخ
`;
return;
}
let html = '';
// المواعيد المتاحة
data.available_slots.forEach(slot => {
html += `
${slot.formatted_time}
${slot.doctor_name}
متاح للحجز
متاح
`;
});
// المواعيد المؤكدة
data.confirmed_appointments.forEach(appointment => {
html += `
${this.formatTime(appointment.appointment_time)}
${appointment.doctor_name}
${appointment.patient_name}
مؤكد
`;
});
// قائمة الانتظار
data.waiting_appointments.forEach(appointment => {
html += `
${this.formatTime(appointment.appointment_time)}
${appointment.doctor_name}
${appointment.patient_name}
في الانتظار
`;
});
appointmentsList.innerHTML = html;
}
formatTime(time) {
const date = new Date(`2000-01-01T${time}`);
return date.toLocaleTimeString('ar-SA', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
}
showError(message) {
const appointmentsList = this.sidebar.querySelector('#appointmentsList');
appointmentsList.innerHTML = `
خطأ في التحميل
${message}
`;
}
showAlert(message, type = 'info') {
// إزالة التنبيهات السابقة
const existingAlerts = this.sidebar.querySelectorAll('.sidebar-alert');
existingAlerts.forEach(alert => alert.remove());
const alert = document.createElement('div');
alert.className = `sidebar-alert ${type}`;
alert.innerHTML = `
${message}
`;
const header = this.sidebar.querySelector('.sidebar-header');
header.insertAdjacentElement('afterend', alert);
// إزالة التنبيه بعد 5 ثوان
setTimeout(() => {
alert.remove();
}, 5000);
}
animateRefresh() {
const refreshBtn = this.sidebar.querySelector('#refreshBtn i');
refreshBtn.style.transform = 'rotate(360deg)';
refreshBtn.style.transition = 'transform 0.5s ease-in-out';
setTimeout(() => {
refreshBtn.style.transform = 'rotate(0deg)';
}, 500);
}
startAutoRefresh() {
this.autoRefreshInterval = setInterval(() => {
if (this.isOpen) {
this.loadAppointments();
}
}, this.refreshInterval);
}
stopAutoRefresh() {
if (this.autoRefreshInterval) {
clearInterval(this.autoRefreshInterval);
this.autoRefreshInterval = null;
}
}
// دوال الإجراءات
bookAppointment(doctorId, time, date) {
// فتح النافذة المنبثقة للحجز
if (typeof openBookingModal === 'function') {
openBookingModal();
// تعيين البيانات المحددة مسبقاً
setTimeout(() => {
document.getElementById('doctor_id').value = doctorId;
document.getElementById('appointment_date').value = date;
if (typeof loadAvailableTimes === 'function') {
loadAvailableTimes().then(() => {
document.getElementById('appointment_time').value = time;
});
}
}, 100);
} else {
// إذا لم تكن النافذة المنبثقة متاحة، انتقل للصفحة الرئيسية
window.location.href = `available-appointments.php?doctor=${doctorId}&date=${date}&time=${time}`;
}
}
viewAppointment(id) {
window.location.href = `appointments.php?view=${id}`;
}
async cancelAppointment(id) {
if (confirm('هل أنت متأكد من إلغاء هذا الموعد؟')) {
try {
const response = await fetch('api/appointment-actions.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `action=cancel&id=${id}`
});
const data = await response.json();
if (data.success) {
this.showAlert(data.message, 'success');
this.loadAppointments(); // إعادة تحميل القائمة
} else {
this.showAlert(data.message, 'error');
}
} catch (error) {
this.showAlert('حدث خطأ في الاتصال', 'error');
}
}
}
// دوال مساعدة
setDate(date) {
this.currentDate = date;
const dateInput = this.sidebar.querySelector('#sidebarDate');
if (dateInput) {
dateInput.value = date;
}
this.loadAppointments();
}
getCurrentDate() {
return this.currentDate;
}
isSidebarOpen() {
return this.isOpen;
}
destroy() {
this.stopAutoRefresh();
if (this.sidebar) this.sidebar.remove();
if (this.toggle) this.toggle.remove();
if (this.overlay) this.overlay.remove();
}
}
// تهيئة القائمة الجانبية عند تحميل الصفحة
let appointmentsSidebar;
document.addEventListener('DOMContentLoaded', function() {
appointmentsSidebar = new AppointmentsSidebar();
});
// دوال عامة للاستخدام من الخارج
window.openAppointmentsSidebar = function() {
if (appointmentsSidebar) {
appointmentsSidebar.openSidebar();
}
};
window.closeAppointmentsSidebar = function() {
if (appointmentsSidebar) {
appointmentsSidebar.closeSidebar();
}
};
window.toggleAppointmentsSidebar = function() {
if (appointmentsSidebar) {
appointmentsSidebar.toggleSidebar();
}
};