// API Base URL
const API_URL = 'http://127.0.0.1:8000';

// Глобальные переменные
let currentLanguage = 'ru';
let currentCalendarView = 'month';
let currentScheduleView = 'day';
let currentDate = new Date();
let machines = [];
let employees = [];
let serviceRequests = [];
let calendarEvents = [];

// Переводы
const translations = {
    ru: {
        page_title: 'Модуль франчайзера',
        header_title: 'Модуль франчайзера',
        menu_ta: 'ТА',
        menu_calendar: 'Календарь обслуживания',
        menu_schedule: 'График работ',
        ta_title: 'Загрузка торговых автоматов',
        upload_text: 'Перетащите файл сюда или нажмите для выбора',
        upload_formats: 'Поддерживаемые форматы: .xlsx, .csv',
        upload_button1: 'Загрузить файл',
        calendar_title: 'Календарь обслуживания',
        prev: 'Назад',
        next: 'Вперед',
        view_week: 'Неделя',
        view_month: 'Месяц',
        view_year: 'Год',
        view_day: 'День',
        filter_label: 'Фильтр:',
        filter_all: 'Все ТА',
        filter_all_employees: 'Все сотрудники',
        legend_planned: 'Плановое ТО',
        legend_soon: 'Приближается (< 5 дней)',
        legend_overdue: 'Просрочено',
        schedule_title: 'График работ',
        employee_filter: 'Сотрудник:',
        confirm_schedule: 'Сформировать',
        monday: 'Понедельник',
        tuesday: 'Вторник',
        wednesday: 'Среда',
        thursday: 'Четверг',
        friday: 'Пятница',
        saturday: 'Суббота',
        sunday: 'Воскресенье',
        module_franchiser: 'Модуль франчайзера'
    },
    en: {
        page_title: 'Franchisee Module',
        header_title: 'Franchisee Module',
        menu_ta: 'Vending Machines',
        menu_calendar: 'Service Calendar',
        menu_schedule: 'Work Schedule',
        ta_title: 'Upload Vending Machines',
        upload_text: 'Drag and drop file here or click to select',
        upload_formats: 'Supported formats: .xlsx, .csv',
        upload_button1: 'Upload File',
        calendar_title: 'Service Calendar',
        prev: 'Previous',
        next: 'Next',
        view_week: 'Week',
        view_month: 'Month',
        view_year: 'Year',
        view_day: 'Day',
        filter_label: 'Filter:',
        filter_all: 'All Machines',
        filter_all_employees: 'All Employees',
        legend_planned: 'Planned Service',
        legend_soon: 'Coming Soon (< 5 days)',
        legend_overdue: 'Overdue',
        schedule_title: 'Work Schedule',
        employee_filter: 'Employee:',
        confirm_schedule: 'Confirm',
        monday: 'Monday',
        tuesday: 'Tuesday',
        wednesday: 'Wednesday',
        thursday: 'Thursday',
        friday: 'Friday',
        saturday: 'Saturday',
        sunday: 'Sunday',
        module_franchiser: 'Franchiser module'

    }
};

// Переключение языка
function setLanguage(lang) {
    currentLanguage = lang;
    
    // Обновляем кнопки языка
    document.querySelectorAll('.lang-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // Обновляем все элементы с data-lang-key
    document.querySelectorAll('[data-lang-key]').forEach(element => {
        const key = element.getAttribute('data-lang-key');
        if (translations[lang][key]) {
            if (element.tagName === 'INPUT') {
                element.value = translations[lang][key];
            } else {
                element.textContent = translations[lang][key];
            }
        }
    });
    
    // Обновляем title страницы
    document.title = translations[lang].page_title;
    
    // Перерисовываем календарь и график
    renderCalendar();
    renderSchedule();
}

// Навигация по секциям
document.querySelectorAll('.nav-link').forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
        
        // Убираем активный класс у всех ссылок
        document.querySelectorAll('.nav-link').forEach(l => l.classList.remove('active'));
        link.classList.add('active');
        
        // Скрываем все секции
        document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
        
        // Показываем нужную секцию
        const sectionId = link.getAttribute('data-section') + '-section';
        document.getElementById(sectionId).classList.add('active');
        
        // Загружаем данные для секции
        if (sectionId === 'calendar-section') {
            loadCalendarData();
        } else if (sectionId === 'schedule-section') {
            loadScheduleData();
        }
    });
});

// ============== СЕКЦИЯ ТА (Загрузка файлов) ==============

const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
const fileInfo = document.getElementById('fileInfo');
const errorList = document.getElementById('errorList');
const successMessage = document.getElementById('successMessage');

// Клик по области загрузки
uploadArea.addEventListener('click', () => {
    fileInput.click();
});

// Выбор файла
fileInput.addEventListener('change', (e) => {
    handleFileSelect(e.target.files[0]);
});

// Drag & Drop
uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    
    const file = e.dataTransfer.files[0];
    handleFileSelect(file);
});

function handleFileSelect(file) {
    if (!file) return;
    
    // Проверка формата
    const validExtensions = ['.xlsx', '.csv'];
    const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
    
    if (!validExtensions.includes(fileExtension)) {
        showNotification('Неверный формат файла. Поддерживаются только .xlsx и .csv', 'error');
        return;
    }
    
    // Показываем информацию о файле
    fileInfo.style.display = 'block';
    fileInfo.innerHTML = `
        <strong>Выбран файл:</strong> ${file.name}<br>
        <strong>Размер:</strong> ${(file.size / 1024).toFixed(2)} KB<br>
        <strong>Тип:</strong> ${fileExtension}
    `;
    
    uploadBtn.disabled = false;
    uploadBtn.onclick = () => uploadFile(file);
    
    errorList.style.display = 'none';
    successMessage.style.display = 'none';
}

async function uploadFile(file) {
    uploadBtn.disabled = true;
    uploadBtn.textContent = 'Загрузка...';
    
    try {
        // Читаем файл как base64
        const fileContent = await readFileAsBase64(file);
        
        const response = await fetch(`${API_URL}/upload-machines`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                file_content: fileContent,
                filename: file.name
            })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            successMessage.style.display = 'block';
            successMessage.innerHTML = `
                <strong>✓ Успешно загружено!</strong><br>
                Добавлено машин: ${result.added_count}<br>
                Обновлено машин: ${result.updated_count}
            `;
            
            errorList.style.display = 'none';
            showNotification('Файл успешно загружен!', 'success');
            
            fileInput.value = '';
            fileInfo.style.display = 'none';
            uploadBtn.disabled = true;
            
        } else {
            if (result.errors && result.errors.length > 0) {
                errorList.style.display = 'block';
                errorList.innerHTML = '<strong>⚠ Обнаружены ошибки:</strong><ul>' +
                    result.errors.map(err => `<li>Строка ${err.row}: ${err.message}</li>`).join('') +
                    '</ul>';
            } else {
                errorList.style.display = 'block';
                errorList.innerHTML = `<strong>⚠ Ошибка:</strong> ${result.detail || 'Неизвестная ошибка'}`;
            }
            
            showNotification('Ошибка при загрузке файла', 'error');
        }
    } catch (error) {
        errorList.style.display = 'block';
        errorList.innerHTML = `<strong>⚠ Ошибка:</strong> ${error.message}`;
        showNotification('Ошибка соединения с сервером', 'error');
    } finally {
        uploadBtn.disabled = false;
    }
}

// Добавьте эту вспомогательную функцию
function readFileAsBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        
        reader.onload = () => {
            // Убираем префикс "data:...;base64,"
            const base64 = reader.result.split(',')[1];
            resolve(base64);
        };
        
        reader.onerror = () => {
            reject(new Error('Ошибка чтения файла'));
        };
        
        reader.readAsDataURL(file);
    });
}

// ============== СЕКЦИЯ КАЛЕНДАРЬ ==============

async function loadCalendarData() {
    try {
        // Загружаем машины
        const machinesResponse = await fetch(`${API_URL}/machines`);
        machines = await machinesResponse.json();
        
        // Загружаем события календаря
        const eventsResponse = await fetch(`${API_URL}/calendar-events`);
        calendarEvents = await eventsResponse.json();
        
        // Заполняем фильтр
        const machineFilter = document.getElementById('machineFilter');
        machineFilter.innerHTML = '<option value="all">' + translations[currentLanguage].filter_all + '</option>';
        
        machines.forEach(machine => {
            const option = document.createElement('option');
            option.value = machine.id;
            option.textContent = `${machine.model} - ${machine.location}`;
            machineFilter.appendChild(option);
        });
        
        renderCalendar();
        
        // Добавляем кнопку создания события
        addCreateEventButton();
        
    } catch (error) {
        console.error('Ошибка загрузки календаря:', error);
        showNotification('Ошибка загрузки данных календаря', 'error');
    }
}

function setCalendarView(view) {
    currentCalendarView = view;
    
    // Обновляем кнопки
    document.querySelectorAll('.view-mode .view-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    renderCalendar();
}

function previousPeriod() {
    if (currentCalendarView === 'week') {
        currentDate.setDate(currentDate.getDate() - 7);
    } else if (currentCalendarView === 'month') {
        currentDate.setMonth(currentDate.getMonth() - 1);
    } else if (currentCalendarView === 'year') {
        currentDate.setFullYear(currentDate.getFullYear() - 1);
    }
    renderCalendar();
}

function nextPeriod() {
    if (currentCalendarView === 'week') {
        currentDate.setDate(currentDate.getDate() + 7);
    } else if (currentCalendarView === 'month') {
        currentDate.setMonth(currentDate.getMonth() + 1);
    } else if (currentCalendarView === 'year') {
        currentDate.setFullYear(currentDate.getFullYear() + 1);
    }
    renderCalendar();
}

function filterCalendar() {
    renderCalendar();
}

function renderCalendar() {
    const calendarView = document.getElementById('calendarView');
    const currentPeriod = document.getElementById('currentPeriod');
    const selectedMachine = document.getElementById('machineFilter').value;
    
    // Фильтруем события
    let filteredEvents = calendarEvents;
    if (selectedMachine !== 'all') {
        filteredEvents = calendarEvents.filter(e => e.vending_machine_id == selectedMachine);
    }
    
    if (currentCalendarView === 'week') {
        renderWeekView(calendarView, currentPeriod, filteredEvents);
    } else if (currentCalendarView === 'month') {
        renderMonthView(calendarView, currentPeriod, filteredEvents);
    } else if (currentCalendarView === 'year') {
        renderYearView(calendarView, currentPeriod, filteredEvents);
    }
}

function renderWeekView(container, periodLabel, events) {
    const weekStart = getWeekStart(currentDate);
    const weekEnd = new Date(weekStart);
    weekEnd.setDate(weekEnd.getDate() + 6);
    
    periodLabel.textContent = formatDateRange(weekStart, weekEnd);
    
    let html = '<div class="calendar-week">';
    
    const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    
    for (let i = 0; i < 7; i++) {
        const date = new Date(weekStart);
        date.setDate(date.getDate() + i);
        
        const dayEvents = events.filter(e => isSameDay(new Date(e.service_date), date));
        
        html += `
            <div class="calendar-day">
                <div class="calendar-day-header">
                    ${translations[currentLanguage][days[date.getDay()]]}<br>
                    ${date.getDate()}
                </div>
                ${dayEvents.map(e => renderEvent(e)).join('')}
            </div>
        `;
    }
    
    html += '</div>';
    container.innerHTML = html;
    
    attachEventListeners();
}

function renderMonthView(container, periodLabel, events) {
    const months = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 
                    'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
    const monthsEn = ['January', 'February', 'March', 'April', 'May', 'June',
                      'July', 'August', 'September', 'October', 'November', 'December'];
    
    const monthNames = currentLanguage === 'ru' ? months : monthsEn;
    periodLabel.textContent = `${monthNames[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
    
    const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
    
    let html = '<div class="calendar-month">';
    
    // Заголовки дней недели
    const dayNames = currentLanguage === 'ru' 
        ? ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
        : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    
    dayNames.forEach(day => {
        html += `<div style="text-align: center; font-weight: bold; padding: 10px;">${day}</div>`;
    });
    
    // Пустые ячейки до начала месяца
    let startDay = firstDay.getDay();
    if (startDay === 0) startDay = 7; // Воскресенье в конец
    
    for (let i = 1; i < startDay; i++) {
        html += '<div class="calendar-day" style="background: #f5f5f5;"></div>';
    }
    
    // Дни месяца
    for (let day = 1; day <= lastDay.getDate(); day++) {
        const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), day);
        const dayEvents = events.filter(e => isSameDay(new Date(e.service_date), date));
        
        html += `
            <div class="calendar-day">
                <div class="calendar-day-header">${day}</div>
                ${dayEvents.map(e => renderEvent(e)).join('')}
            </div>
        `;
    }
    
    html += '</div>';
    container.innerHTML = html;
    
    attachEventListeners();
}

function renderYearView(container, periodLabel, events) {
    periodLabel.textContent = currentDate.getFullYear();
    
    const months = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
                    'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
    const monthsEn = ['January', 'February', 'March', 'April', 'May', 'June',
                      'July', 'August', 'September', 'October', 'November', 'December'];
    
    const monthNames = currentLanguage === 'ru' ? months : monthsEn;
    
    let html = '<div class="calendar-year">';
    
    for (let month = 0; month < 12; month++) {
        const firstDay = new Date(currentDate.getFullYear(), month, 1);
        const lastDay = new Date(currentDate.getFullYear(), month + 1, 0);
        
        html += `
            <div class="month-mini">
                <div class="month-mini-header">${monthNames[month]}</div>
                <div class="month-mini-grid">
        `;
        
        // Заголовки дней
        const dayNames = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
        dayNames.forEach(day => {
            html += `<div style="font-weight: bold; font-size: 10px; text-align: center;">${day}</div>`;
        });
        
        // Пустые ячейки
        let startDay = firstDay.getDay();
        if (startDay === 0) startDay = 7;
        
        for (let i = 1; i < startDay; i++) {
            html += '<div class="month-mini-day"></div>';
        }
        
        // Дни месяца
        for (let day = 1; day <= lastDay.getDate(); day++) {
            const date = new Date(currentDate.getFullYear(), month, day);
            const dayEvents = events.filter(e => isSameDay(new Date(e.service_date), date));
            
            let bgColor = 'white';
            if (dayEvents.length > 0) {
                const eventType = getEventType(dayEvents[0]);
                if (eventType === 'overdue') bgColor = '#F44336';
                else if (eventType === 'soon') bgColor = '#FFC107';
                else bgColor = '#4CAF50';
            }
            
            html += `<div class="month-mini-day ${dayEvents.length > 0 ? 'has-event' : ''}" 
                          style="background: ${bgColor}; color: ${dayEvents.length > 0 ? 'white' : 'black'};">
                          ${day}
                     </div>`;
        }
        
        html += '</div></div>';
    }
    
    html += '</div>';
    container.innerHTML = html;
}

function renderEvent(event) {
    const eventType = getEventType(event);
    const eventClass = eventType === 'overdue' ? 'event-overdue' : 
                       eventType === 'soon' ? 'event-soon' : 'event-planned';
    
    return `
        <div class="calendar-event ${eventClass}" 
             data-event-id="${event.id}"
             onmouseenter="showTooltip(event, ${event.id})"
             onmouseleave="hideTooltip()">
            ${event.machine_model || 'ТА'}
        </div>
    `;
}

function getEventType(event) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const eventDate = new Date(event.service_date);
    eventDate.setHours(0, 0, 0, 0);
    
    const diffDays = Math.ceil((eventDate - today) / (1000 * 60 * 60 * 24));
    
    if (diffDays < 0) return 'overdue';
    if (diffDays <= 5) return 'soon';
    return 'planned';
}

function showTooltip(event, eventId) {
    const calendarEvent = calendarEvents.find(e => e.id === eventId);
    if (!calendarEvent) return;
    
    const tooltip = document.getElementById('tooltip');
    tooltip.innerHTML = `
        <strong>Модель:</strong> ${calendarEvent.machine_model}<br>
        <strong>Место:</strong> ${calendarEvent.machine_location}<br>
        <strong>Франчайзи:</strong> ${calendarEvent.franchisee || 'Не указан'}<br>
        <strong>Дата ТО:</strong> ${formatDate(new Date(calendarEvent.service_date))}
    `;
    
    tooltip.style.display = 'block';
    tooltip.style.left = event.pageX + 10 + 'px';
    tooltip.style.top = event.pageY + 10 + 'px';
}

function hideTooltip() {
    document.getElementById('tooltip').style.display = 'none';
}

function attachEventListeners() {
    // Обработчики уже назначены через onclick в HTML
}

// ============== СЕКЦИЯ ГРАФИК РАБОТ ==============

async function loadScheduleData() {
    try {
        // Загружаем сотрудников
        const employeesResponse = await fetch(`${API_URL}/employees`);
        employees = await employeesResponse.json();
        
        // Загружаем заявки
        const requestsResponse = await fetch(`${API_URL}/service-requests`);
        serviceRequests = await requestsResponse.json();
        
        // Заполняем фильтр сотрудников
        const employeeFilter = document.getElementById('employeeFilter');
        employeeFilter.innerHTML = '<option value="all">' + translations[currentLanguage].filter_all_employees + '</option>';
        
        employees.forEach(emp => {
            const option = document.createElement('option');
            option.value = emp.id;
            option.textContent = emp.name;
            employeeFilter.appendChild(option);
        });
        
        renderSchedule();
        
    } catch (error) {
        console.error('Ошибка загрузки графика:', error);
        showNotification('Ошибка загрузки данных графика', 'error');
    }
}

function setScheduleView(view) {
    currentScheduleView = view;
    
    document.querySelectorAll('#schedule-section .view-mode .view-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    renderSchedule();
}

function filterSchedule() {
    renderSchedule();
}

function renderSchedule() {
    const scheduleView = document.getElementById('scheduleView');
    const selectedEmployee = document.getElementById('employeeFilter').value;
    
    let filteredEmployees = employees;
    if (selectedEmployee !== 'all') {
        filteredEmployees = employees.filter(e => e.id == selectedEmployee);
    }
    
    if (currentScheduleView === 'day') {
        renderDaySchedule(scheduleView, filteredEmployees);
    } else {
        renderWeekSchedule(scheduleView, filteredEmployees);
    }
}

function renderDaySchedule(container, employeesList) {
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    
    let html = `
        <table>
            <thead>
                <tr>
                    <th>Сотрудник<br><small>Загрузка за день</small></th>
    `;
    
    for (let hour = 8; hour <= 18; hour++) {
        html += `<th>${hour}:00</th>`;
    }
    
    html += `</tr></thead><tbody>`;
    
    employeesList.forEach(emp => {
        const empRequests = serviceRequests.filter(r => 
            r.employee_id === emp.id && r.scheduled_date === todayStr
        );
        
        // Подсчет загрузки
        const totalHours = empRequests.reduce((sum, r) => 
            sum + (r.service_duration_hours || 1) + (r.travel_time_hours || 2), 0
        );
        
        const overloaded = totalHours > 10;
        const rowColor = overloaded ? '#ffebee' : 'white';
        
        html += `
            <tr style="background: ${rowColor};">
                <td>
                    <strong>${emp.name}</strong><br>
                    <small style="color: ${overloaded ? '#f44336' : '#666'};">
                        ${emp.models_can_service || 'Нет специализации'}<br>
                        Загрузка: ${totalHours}ч ${overloaded ? '⚠ >10ч' : ''}
                    </small>
                </td>
        `;
        
        for (let hour = 8; hour <= 18; hour++) {
            const hourRequests = empRequests.filter(r => {
                if (!r.scheduled_time) return false;
                const reqHour = parseInt(r.scheduled_time.split(':')[0]);
                return reqHour === hour;
            });
            
            html += `
                <td class="drop-zone" 
                    data-employee-id="${emp.id}" 
                    data-hour="${hour}"
                    ondrop="drop(event)" 
                    ondragover="allowDrop(event)"
                    ondragleave="dragLeave(event)">
                    ${hourRequests.map(r => renderTaskCard(r)).join('')}
                </td>
            `;
        }
        
        html += '</tr>';
    });
    
    // Неназначенные задачи
    const unassignedRequests = serviceRequests.filter(r => 
        !r.employee_id && r.scheduled_date === todayStr
    );
    
    if (unassignedRequests.length > 0) {
        html += `
            <tr>
                <td colspan="${11 + 1}" style="background: #fff3e0;">
                    <strong>⚠ Неназначенные задачи (${unassignedRequests.length}):</strong><br>
                    <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;">
                        ${unassignedRequests.map(r => renderTaskCard(r)).join('')}
                    </div>
                </td>
            </tr>
        `;
    }
    
    html += '</tbody></table>';
    container.innerHTML = html;
}

function renderWeekSchedule(container, employeesList) {
    const weekStart = getWeekStart(new Date());
    
    let html = `
        <table>
            <thead>
                <tr>
                    <th>Сотрудник</th>
    `;
    
    const days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
    for (let i = 0; i < 7; i++) {
        const date = new Date(weekStart);
        date.setDate(date.getDate() + i);
        html += `<th>${days[i]}<br>${date.getDate()}.${date.getMonth() + 1}</th>`;
    }
    
    html += `
                    <th>Всего часов</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    employeesList.forEach(emp => {
        html += `
            <tr>
                <td><strong>${emp.name}</strong></td>
        `;
        
        let totalHours = 0;
        
        for (let i = 0; i < 7; i++) {
            const date = new Date(weekStart);
            date.setDate(date.getDate() + i);
            const dateStr = date.toISOString().split('T')[0];
            
            const dayRequests = serviceRequests.filter(r => 
                r.employee_id === emp.id && r.scheduled_date === dateStr
            );
            
            const dayHours = dayRequests.reduce((sum, r) => 
                sum + (r.service_duration_hours || 1) + (r.travel_time_hours || 2), 0
            );
            
            totalHours += dayHours;
            
            const cellColor = dayHours > 10 ? '#ffebee' : dayHours > 8 ? '#fff3e0' : 'white';
            
            html += `
                <td class="drop-zone" 
                    data-employee-id="${emp.id}" 
                    data-date="${dateStr}"
                    style="background: ${cellColor};"
                    ondrop="drop(event)" 
                    ondragover="allowDrop(event)"
                    ondragleave="dragLeave(event)">
                    ${dayRequests.map(r => renderTaskCard(r)).join('')}
                    <div style="margin-top: 5px; font-size: 12px; color: #666;">
                        ${dayHours}ч
                    </div>
                </td>
            `;
        }
        
        const totalColor = totalHours > 40 ? '#f44336' : totalHours > 35 ? '#ff9800' : '#4CAF50';
        
        html += `
                <td style="background: ${totalColor}; color: white; font-weight: bold; text-align: center;">
                    ${totalHours}ч
                </td>
            </tr>
        `;
    });
    
    html += '</tbody></table>';
    container.innerHTML = html;
}

function renderTaskCard(request) {
    const isEmergency = request.priority === 'Авария';
    
    return `
        <div class="task-card ${isEmergency ? 'emergency' : ''}" 
             draggable="true"
             data-request-id="${request.id}"
             ondragstart="drag(event)">
            ${isEmergency ? '🚨 ' : ''}ТА #${request.vending_machine_id}<br>
            <small>${request.description || ''}</small><br>
            <small>${request.service_duration_hours || 1}ч + ${request.travel_time_hours || 2}ч дорога</small>
        </div>
    `;
}

// Drag & Drop
function allowDrop(ev) {
    ev.preventDefault();
    ev.currentTarget.classList.add('drag-over');
}

function dragLeave(ev) {
    ev.currentTarget.classList.remove('drag-over');
}

function drag(ev) {
    ev.dataTransfer.setData("requestId", ev.target.getAttribute('data-request-id'));
    ev.target.classList.add('dragging');
}

async function drop(ev) {
    ev.preventDefault();
    ev.currentTarget.classList.remove('drag-over');
    
    const requestId = ev.dataTransfer.getData("requestId");
    const employeeId = ev.currentTarget.getAttribute('data-employee-id');
    const hour = ev.currentTarget.getAttribute('data-hour');
    const date = ev.currentTarget.getAttribute('data-date');
    
    // Обновляем заявку
    try {
        const response = await fetch(`${API_URL}/service-requests/${requestId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                employee_id: parseInt(employeeId),
                scheduled_time: hour ? `${hour}:00:00` : null,
                scheduled_date: date || null
            })
        });
        
        if (response.ok) {
            // Обновляем локальные данные
            const request = serviceRequests.find(r => r.id == requestId);
            if (request) {
                request.employee_id = parseInt(employeeId);
                if (hour) request.scheduled_time = `${hour}:00:00`;
                if (date) request.scheduled_date = date;
            }
            
            renderSchedule();
            showNotification('Задача перемещена', 'success');
        }
    } catch (error) {
        console.error('Ошибка перемещения задачи:', error);
        showNotification('Ошибка перемещения задачи', 'error');
    }
}

async function confirmSchedule() {
    if (!confirm('Подтвердить график работ? Статусы будут обновлены.')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_URL}/confirm-schedule`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showNotification(`График подтвержден! Обновлено заявок: ${result.updated_count}`, 'success');
            loadScheduleData();
        } else {
            showNotification('Ошибка подтверждения графика', 'error');
        }
    } catch (error) {
        console.error('Ошибка подтверждения:', error);
        showNotification('Ошибка подтверждения графика', 'error');
    }
}

// ============== ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ==============

function showNotification(message, type = 'info') {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.className = 'notification ' + type;
    notification.style.display = 'block';
    
    setTimeout(() => {
        notification.style.display = 'none';
    }, 5000);
}

function getWeekStart(date) {
    const d = new Date(date);
    const day = d.getDay();
    const diff = d.getDate() - day + (day === 0 ? -6 : 1); // Понедельник
    return new Date(d.setDate(diff));
}

function isSameDay(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
}

function formatDate(date) {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}.${month}.${year}`;
}

function formatDateRange(start, end) {
    return `${formatDate(start)} - ${formatDate(end)}`;
}

// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', () => {
    loadCalendarData();
});

// Генерация заявок при смене дня (можно вызвать вручную для теста)
async function generateDailyRequests() {
    try {
        const response = await fetch(`${API_URL}/generate-daily-requests`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showNotification(`Создано заявок: ${result.created_count}`, 'success');
            loadScheduleData();
        }
    } catch (error) {
        showNotification('Ошибка создания заявок', 'error');
    }
}

// Создание аварийной заявки
async function createEmergencyRequest(machineId) {
    try {
        const response = await fetch(`${API_URL}/create-emergency-request`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                vending_machine_id: machineId,
                description: 'Аварийная поломка - требуется срочный ремонт'
            })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            if (result.status === 'warning') {
                showNotification(result.message, 'warning');
            } else {
                showNotification(result.message, 'success');
            }
            loadScheduleData();
        }
    } catch (error) {
        showNotification('Ошибка создания аварийной заявки', 'error');
    }
}

// Получить загруженность сотрудников
async function checkEmployeeWorkload(date = null) {
    try {
        const url = date 
            ? `${API_URL}/employee-workload?date=${date}`
            : `${API_URL}/employee-workload`;
        
        const response = await fetch(url);
        const workload = await response.json();
        
        // Проверяем перегрузки
        const overloaded = workload.filter(emp => emp.daily_overloaded || emp.weekly_overloaded);
        
        if (overloaded.length > 0) {
            const messages = overloaded.map(emp => {
                if (emp.daily_overloaded) {
                    return `${emp.name}: перегрузка ${emp.daily_hours}ч за день (>10ч)`;
                } else {
                    return `${emp.name}: перегрузка ${emp.weekly_hours}ч за неделю (>40ч)`;
                }
            });
            
            showNotification('Внимание! Перегрузка сотрудников:\n' + messages.join('\n'), 'warning');
        }
        
        return workload;
    } catch (error) {
        console.error('Ошибка проверки загруженности:', error);
        return [];
    }
}

// Проверить доступность сотрудников для модели
async function checkEmployeeForModel(model) {
    try {
        const response = await fetch(`${API_URL}/check-employee-availability/${encodeURIComponent(model)}`);
        const result = await response.json();
        
        if (!result.has_employees) {
            showNotification(
                `Нет доступных сотрудников для обслуживания ${model}`, 
                'warning'
            );
            return false;
        }
        
        return true;
    } catch (error) {
        console.error('Ошибка проверки сотрудников:', error);
        return false;
    }
}

// Обновляем функцию confirmSchedule для сохранения истории
async function confirmSchedule() {
    if (!confirm('Подтвердить график работ? Статусы заявок и оборудования будут обновлены, изменения сохранятся в историю.')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_URL}/confirm-schedule`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showNotification(
                `График подтвержден!\n` +
                `Обновлено заявок: ${result.updated_count}\n` +
                `Статусы сохранены в историю`, 
                'success'
            );
            loadScheduleData();
        } else {
            showNotification('Ошибка подтверждения графика', 'error');
        }
    } catch (error) {
        console.error('Ошибка подтверждения:', error);
        showNotification('Ошибка подтверждения графика', 'error');
    }
}

// ========== ФУНКЦИИ ДЛЯ СОЗДАНИЯ СОБЫТИЯ В КАЛЕНДАРЕ ==========

// Открыть диалог создания события
function openCreateEventDialog() {
    const dialog = document.getElementById('createEventDialog');
    if (dialog) {
        dialog.style.display = 'block';
    } else {
        // Создаем диалог если его нет
        createEventDialog();
    }
}

// Закрыть диалог создания события
function closeCreateEventDialog() {
    const dialog = document.getElementById('createEventDialog');
    if (dialog) {
        dialog.style.display = 'none';
    }
}

// Создать диалог если его еще нет в HTML
function createEventDialog() {
    if (document.getElementById('createEventDialog')) return;
    
    const dialog = document.createElement('div');
    dialog.id = 'createEventDialog';
    dialog.className = 'modal-dialog';
    dialog.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h2>Создать событие в календаре</h2>
                <button type="button" class="close-btn" onclick="closeCreateEventDialog()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="eventMachineId">Торговый автомат:</label>
                    <select id="eventMachineId" class="form-control">
                        <option value="">-- Выберите автомат --</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="eventType">Тип обслуживания:</label>
                    <select id="eventType" class="form-control">
                        <option value="Плановое ТО">Плановое ТО</option>
                        <option value="ТО по ресурсу">ТО по ресурсу</option>
                        <option value="Ремонт">Ремонт</option>
                        <option value="Проверка">Проверка</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="eventDays">На сколько дней вперед:</label>
                    <input type="number" id="eventDays" class="form-control" value="5" min="1" max="30">
                </div>
                
                <div class="form-group">
                    <label for="eventReason">Причина (опционально):</label>
                    <textarea id="eventReason" class="form-control" rows="3" placeholder="Введите причину события"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeCreateEventDialog()">Отмена</button>
                <button type="button" class="btn btn-primary" onclick="submitCreateEvent()">Создать</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(dialog);
    
    // Загружаем список машин
    if (machines.length === 0) {
        fetch(`${API_URL}/machines`)
            .then(r => r.json())
            .then(data => {
                machines = data;
                fillEventMachineSelect();
            });
    } else {
        fillEventMachineSelect();
    }
}

// Заполнить список машин в диалоге
function fillEventMachineSelect() {
    const select = document.getElementById('eventMachineId');
    if (!select) return;
    
    machines.forEach(machine => {
        const option = document.createElement('option');
        option.value = machine.id;
        option.textContent = `${machine.model} - ${machine.location}`;
        select.appendChild(option);
    });
}

// Отправить запрос на создание события
async function submitCreateEvent() {
    const machineId = document.getElementById('eventMachineId').value;
    const serviceType = document.getElementById('eventType').value;
    const daysAhead = parseInt(document.getElementById('eventDays').value) || 5;
    const reason = document.getElementById('eventReason').value;
    
    if (!machineId) {
        showNotification('Пожалуйста, выберите торговый автомат', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_URL}/calendar-events`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                vending_machine_id: parseInt(machineId),
                service_type: serviceType,
                reason: reason || null,
                days_ahead: daysAhead
            })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showNotification(
                `✓ Событие создано на ${result.service_date}`,
                'success'
            );
            
            // Закрываем диалог
            closeCreateEventDialog();
            
            // Перезагружаем календарь
            loadCalendarData();
        } else {
            showNotification(`Ошибка: ${result.detail || 'Не удалось создать событие'}`, 'error');
        }
    } catch (error) {
        console.error('Ошибка создания события:', error);
        showNotification('Ошибка при создании события', 'error');
    }
}

// Добавить кнопку создания события в календарь (вызвать при загрузке страницы)
function addCreateEventButton() {
    const calendarSection = document.getElementById('calendar-section');
    if (!calendarSection) return;
    
    const buttonContainer = calendarSection.querySelector('.calendar-controls');
    if (!buttonContainer || buttonContainer.querySelector('.create-event-btn')) return;
    
    const button = document.createElement('button');
    button.className = 'btn btn-success create-event-btn';
    button.textContent = '+ Новое событие';
    button.onclick = openCreateEventDialog;
    button.style.margin = '10px';
    
    buttonContainer.appendChild(button);
}
