Загрузка данных


const users = [];
const admins = [];
const trainings = [
    { date: '2024-10-01', time: '10:00', title: 'Йога' },
    { date: '2024-10-01', time: '12:00', title: 'Кардио' },
    { date: '2024-10-02', time: '10:00', title: 'Пилатес' },
    { date: '2024-10-02', time: '14:00', title: 'Силовые упражнения' },
    { date: '2024-10-03', time: '09:00', title: 'Растяжка' },
];

let currentUser = null;
let currentScheduleView = 'weekly';

document.addEventListener('DOMContentLoaded', () => {
    checkAuthentication();
});

function login(event) {
    event.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (users.find(user => user.username === username && user.password === password)) {
        currentUser = { username };
        hideAuthForms();
        alert(`Привет, ${currentUser.username}!`);
    } else if (admins.includes(username)) {
        currentUser = { username };
        hideAuthForms();
        alert(`Привет, администратор ${currentUser.username}!`);
    } else {
        alert('Неправильный логин или пароль.');
    }
}

function register(event) {
    event.preventDefault();
    const name = document.getElementById('reg-name').value;
    const username = document.getElementById('reg-username').value;
    const password = document.getElementById('reg-password').value;
    const accountType = document.getElementById('account-type').value;

    if (!users.some(user => user.username === username)) {
        if (accountType === 'client') {
            users.push({ name, username, password });
            alert('Вы успешно зарегистрировались!');
        } else {
            admins.push(username);
            alert('Вы успешно зарегистрировались как администратор!');
        }
        switchToLogin();
    } else {
        alert('Пользователь с таким логином уже существует.');
    }
}

function logoutUser() {
    currentUser = null;
    showAuthForms();
}

function toggleScheduleView() {
    if (!currentUser) return;
    const authSection = document.getElementById('auth-form');
    const registerSection = document.getElementById('register-form');
    authSection.style.display = 'none';
    registerSection.style.display = 'none';
    const scheduleView = document.getElementById('schedule-view');
    scheduleView.style.display = 'block';
    renderSchedule(currentScheduleView);
}

function changeScheduleView(view) {
    currentScheduleView = view;
    renderSchedule(view);
}

function renderSchedule(view) {
    const scheduleGrid = document.getElementById('schedule-grid');
    scheduleGrid.innerHTML = '';

    if (view === 'daily') {
        const today = new Date().toISOString().split('T')[0];
        const dailyTrainings = trainings.filter(training => training.date === today);

        dailyTrainings.forEach((training) => {
            const item = document.createElement('div');
            item.classList.add('schedule-item');
            item.textContent = `${training.title} (${training.time})`;
            scheduleGrid.appendChild(item);
        });
    } else {
        const weeklyTrainings = [...new Set(trainings.map(t => t.date))];

        weeklyTrainings.forEach(date => {
            const dayTrainings = trainings.filter(t => t.date === date);
            const container = document.createElement('div');
            container.classList.add('schedule-item');
            container.textContent = `\n${new Date(date).toLocaleDateString()}:\n`;
            
            dayTrainings.forEach(training => {
                const subItem = document.createElement('div');
                subItem.textContent = `\t${training.time} - ${training.title}\n`;
                container.appendChild(subItem);
            });
            scheduleGrid.appendChild(container);
        });
    }
}

function openBookingForm() {
    if (!currentUser) return;
    const bookingModal = document.getElementById('booking-modal');
    bookingModal.style.display = 'flex';
}

function bookTraining(event) {
    event.preventDefault();
    const selectedDate = document.getElementById('training-date').value;
    const selectedTime = document.getElementById('training-time').value;

    if (selectedDate && selectedTime) {
        alert(`${currentUser.username}, ваша заявка на занятие ${selectedDate} в ${selectedTime} принята.`);
        closeBookingModal();
    } else {
        alert('Пожалуйста, выберите дату и время занятия.');
    }
}

function closeBookingModal() {
    const bookingModal = document.getElementById('booking-modal');
    bookingModal.style.display = 'none';
}

function switchToRegister() {
    const authSection = document.getElementById('auth-form');
    const registerSection = document.getElementById('register-form');
    authSection.style.display = 'none';
    registerSection.style.display = 'block';
}

function switchToLogin() {
    const authSection = document.getElementById('auth-form');
    const registerSection = document.getElementById('register-form');
    authSection.style.display = 'block';
    registerSection.style.display = 'none';
}

function checkAuthentication() {
    if (localStorage.getItem('currentUser')) {
        currentUser = JSON.parse(localStorage.getItem('currentUser'));
        hideAuthForms();
    } else {
        showAuthForms();
    }
}

function hideAuthForms() {
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    const authSection = document.getElementById('auth-form');
    const registerSection = document.getElementById('register-form');
    authSection.style.display = 'none';
    registerSection.style.display = 'none';
}

function showAuthForms() {
    localStorage.removeItem('currentUser');
    const authSection = document.getElementById('auth-form');
    const registerSection = document.getElementById('register-form');
    authSection.style.display = 'block';
    registerSection.style.display = 'none';
}