document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    let sessionUserId = null;
    let userLevel = null;

    const getSessionUserId = async () => {
        try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();
            sessionUserId = data.user_id;
            userLevel = data.user_level;
        } catch (error) {
            console.error('Error fetching session user ID:', error);
        }
	};

    const updateContent = (content) => {
        if (content === 'calendar') {
            loadCalendarUI();
            loadCalendar(new Date());
        }
    };

    const loadCalendarUI = () => {
        contentContainer.innerHTML = `
            <div class="calendar-container">
                <div id="calendar-controls">
                    <button class="calendar-button" id="prev-month"><</button>
                    <h3 id="month-header"></h3>
                    <button class="calendar-button" id="next-month">></button>
                </div>
                <div id="calendar"></div>
            </div>
        `;
    };

	function loadEventBadges() {
    const month = currentMonth + 1;
    const year = currentYear;
    
    fetch(`../php/get_badges.php?month=${month}&year=${year}`)
        .then(response => response.json())
        .then(data => {
            document.querySelectorAll('.calendar-cell').forEach(cell => {
                const date = cell.dataset.date;
                if (date && data.includes(date)) {
                    cell.classList.add('has-event');
                }
            });
        })
        .catch(err => console.error('Failed to load event badges:', err));
}


    const loadCalendar = (currentDate) => {
    currentMonth = currentDate.getMonth();
    currentYear = currentDate.getFullYear(); 

    const calendarElement = document.getElementById('calendar');
    calendarElement.innerHTML = '';

    const monthHeader = document.getElementById('month-header');
    monthHeader.textContent = getFormattedMonthHeader(currentDate);

    const grid = createCalendarGrid(currentDate);
    calendarElement.appendChild(grid);

    setupMonthNavigation(currentDate);

    loadEventBadges();
};


    const createCalendarGrid = (currentDate) => {
        const grid = document.createElement('div');
        grid.className = 'calendar-grid';

        addDayNamesToGrid(grid);
        addEmptyCells(grid, currentDate);
        addDayCells(grid, currentDate);

        return grid;
    };

    const addDayNamesToGrid = (grid) => {
        const dayNames = ['Sv.', 'Pr.', 'Ot.', 'Tr.', 'Ce.', 'Pk.', 'Se.'];
        dayNames.forEach(day => {
            const dayCell = document.createElement('div');
            dayCell.className = 'calendar-cell day-name';
            dayCell.textContent = day;
            grid.appendChild(dayCell);
        });
    };

    const addEmptyCells = (grid, currentDate) => {
        const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDay();
        for (let i = 0; i < firstDayOfMonth; i++) {
            const emptyCell = document.createElement('div');
            emptyCell.className = 'calendar-cell empty';
            grid.appendChild(emptyCell);
        }
    };

    const addDayCells = (grid, currentDate) => {
    const daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
    const today = new Date();

    for (let day = 1; day <= daysInMonth; day++) {
        const dayCell = document.createElement('div');
        dayCell.className = 'calendar-cell';
        dayCell.textContent = day;

        dayCell.dataset.date = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

        dayCell.addEventListener('click', () => fetchEventDetails(currentDate.getFullYear(), currentDate.getMonth(), day));

        if (isToday(today, currentDate, day)) {
            dayCell.classList.add('today');
        }

        grid.appendChild(dayCell);
    }
};


    const isToday = (today, currentDate, day) => {
        return day === today.getDate() && currentDate.getMonth() === today.getMonth() && currentDate.getFullYear() === today.getFullYear();
    };

    const setupMonthNavigation = (currentDate) => {
        document.getElementById('prev-month').onclick = () => changeMonth(currentDate, -1);
        document.getElementById('next-month').onclick = () => changeMonth(currentDate, 1);
    };

    const changeMonth = (currentDate, monthOffset) => {
        currentDate.setMonth(currentDate.getMonth() + monthOffset);
        loadCalendar(currentDate);
    };

    const getFormattedMonthHeader = (date) => {
        return date.toLocaleString('default', { month: 'long' }) + ' ' + date.getFullYear();
    };

    const fetchEventDetails = async (year, month, day) => {
        const date = `${year}-${(month + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        try {
            const response = await fetch(`../php/get_events.php?date=${date}`);
            const data = await response.json();
            displayEventDetails(data, date);
        } catch (error) {
            console.error('Error fetching event details:', error);
        }
    };

    const displayEventDetails = (events, date) => {
        const modalContent = document.querySelector('.modal-content');
        modalContent.querySelector('.event-date').textContent = `Notikumi priekš ${date}`;
        modalContent.querySelector('.events-list').innerHTML = createEventList(events);
        document.getElementById('event-date-hidden').value = date;

        toggleAddEventForm();
        openModal();
    };

    const createEventList = (events) => {
        if (events.length === 0) return 'Šajā datumā notikumu nav.';
        return `<ul>${events.map(event => createEventItem(event)).join('')}</ul>`;
    };

    const createEventItem = (event) => {
    let deleteButton = '';
    if (userLevel === 3) {
        deleteButton = `<div class="event-footer">
                            <button class="delete-event-button" data-event-id="${event.id}">Dzēst</button>
                        </div>`;
    }
    return `
        <li>
            <div class="event-details">
                <strong>${event.title}</strong>
                <p>${event.description}</p>
            </div>
            ${deleteButton}
        </li>
    `;
};

    const toggleAddEventForm = () => {
        const addEventForm = document.getElementById('add-event-form');
        addEventForm.style.display = (userLevel === 3) ? 'block' : 'none';
    };

    const createModal = () => {
        const modal = document.createElement('div');
        modal.id = 'modal';
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <span class="close-button">&times;</span>
                <h2>Datuma ieraksti</h2>
                <h3 class="event-date"></h3>
                <div class="events-list"></div>
                <div id="add-event-form">
                    <h3>Pievienot notikumu</h3>
                    <input type="hidden" id="event-date-hidden">
					<label>Notikuma nosaukums</label>
                    <input type="text" id="event-title">
					<label>Notikumu apraksts</label>
                    <textarea id="event-description"></textarea>
                    <button id="add-event-button" class="calendar-button">Pievienot notikumu</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        setupModalListeners(modal);
    };

    const setupModalListeners = (modal) => {
        const closeButton = modal.querySelector('.close-button');
        closeButton.addEventListener('click', closeModal);

        window.addEventListener('click', (event) => {
            if (event.target === modal) {
                closeModal();
            }
        });

        document.getElementById('add-event-button').addEventListener('click', addEvent);

        modal.addEventListener('click', (event) => {
            if (event.target.classList.contains('delete-event-button')) {
                const eventId = event.target.getAttribute('data-event-id');
                deleteEvent(eventId);
            }
        });
    };

    const openModal = () => {
        document.getElementById('modal').style.display = 'block';
    };

    const closeModal = () => {
        const modal = document.getElementById('modal');
        modal.style.display = 'none';
        document.getElementById('event-title').value = '';
        document.getElementById('event-description').value = '';
    };

    const addEvent = async (event) => {
        event.preventDefault();
        const title = document.getElementById('event-title').value;
        const description = document.getElementById('event-description').value;
        const eventDate = document.getElementById('event-date-hidden').value;

        if (!title || !description) return alert('Lūdzu aizpildīt abus laukus!');

        try {
            const response = await fetch('../php/add_event.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ title, description, date: eventDate, sessionUserId })
            });

            const result = await response.json();
            if (result.success) {
                loadCalendar(new Date(eventDate));
				const [year, month, day] = eventDate.split('-').map(Number);
				fetchEventDetails(year, month - 1, day);
				document.getElementById('event-title').value = '';
				document.getElementById('event-description').value = '';
            } else {
                alert('Kļūme pievienojot notikumu');
            }
        } catch (error) {
            console.error('Kļūme pievienojot notikumu:', error);
        }
    };

const deleteEvent = async (eventId) => {

    try {
        const response = await fetch(`../php/delete_event.php?id=${eventId}`, {
            method: 'DELETE'
        });

        const result = await response.json();
        if (result.success) {
            const eventDate = result.eventDate;
            const [year, month, day] = eventDate.split('-').map(Number);
            fetchEventDetails(year, month - 1, day);
			loadCalendar(new Date(eventDate));
        } else {
            alert('Kļūme dzēšot notikumu: ' + result.message);
        }
    } catch (error) {
        console.error('Kļūme dzēšot notikumu:', error);
    }
};


    const savedContent = localStorage.getItem('selectedContent') || 'feed';

    getSessionUserId().then(() => {
        updateContent(savedContent);
    });
    
    document.querySelectorAll('.sidebar button').forEach(button => {
        button.addEventListener('click', (event) => {
            const content = event.target.getAttribute('data-content');
            if (content) {
                updateContent(content);
                localStorage.setItem('selectedContent', content);
            }
        });
    });

    createModal();
    getSessionUserId();
});
