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

	const getSessionUserId = async () => {
        try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();
            sessionUserId = data.user_id;
            sessionUserLevel = data.user_level;
        } catch (error) {
            console.error('Kļūme ķerot sesijas lietotāju:', error);
        }
	};

    const updateContent = (content) => {
    document.querySelectorAll('.sidebar button').forEach(button => {
        button.classList.remove('active');
    });

    const currentButton = document.querySelector(`.sidebar button[data-content="${content}"]`);
    if (currentButton) {
        currentButton.classList.add('active');
    }

    switch(content) {
        case 'feed':
            contentContainer.innerHTML = `
                <div class="tabs">
                    <button class="tab-button active" data-tab="news">Jaunumi</button>
                    <button class="tab-button" data-tab="other">Plūsma</button>
                </div>
                <div>
                    <button id="add-post-top">+</button>
                </div>
                <div class="tab-content">
                    <div id="news" class="tab active">
                        <div id="news-posts"></div>
                    </div>
                    <div id="other" class="tab">
                        <div id="feed-posts"></div>
                    </div>
                </div>
            `;
            addTabSwitchingFunctionality();
            loadPosts();
            addPostModal();
            break;
    }
};


const loadPosts = () => {
    fetch('../php/fetch_posts.php')
        .then(response => response.json())
        .then(data => {
            const newsPostsContainer = document.getElementById('news-posts');
            const feedPostsContainer = document.getElementById('feed-posts');

            newsPostsContainer.innerHTML = '';
            feedPostsContainer.innerHTML = '';

            data.posts.forEach(post => {
                const postElement = document.createElement('div');
                const images = post.image ? post.image : [];

                let imageContent = '';
                if (images.length > 1) {
                    imageContent = `
                    <div class="carousel">
                        <button class="carousel-button prev">❮</button>
                        <div class="carousel-images">
                            ${images.map(img => `<img src="${img}" alt="${post.title}" class="post-image">`).join('')}
                        </div>
                        <button class="carousel-button next">❯</button>
                    </div>
                    `;
                } else if (images.length === 1) {
                    imageContent = `<img src="${images[0]}" alt="${post.title}" class="post-image">`;
                }

                postElement.innerHTML = `
				<div class="post-container">
					<h2 style="text-align: left;">${post.username}</h2>
					<p>${post.description}</p>
					${imageContent}
					<div class = "post-footer">
					<p>${new Date(post.created_at).toLocaleString()}</p>
					${(sessionUserId === post.user_id || sessionUserLevel === 3) ? '<button type="submit" class="delete-post" data-post-id="' + post.id + '">Dzēst</button>' : ''}
					</div>
				</div>
				<br>
				`;

                
                if (post.tab === 'news') {
                    newsPostsContainer.appendChild(postElement);
                } else {
                    feedPostsContainer.appendChild(postElement);
                }
            });

            setupCarousel();

            document.querySelectorAll('.delete-post').forEach(button => {
                button.addEventListener('click', (event) => {
                    const postId = event.target.getAttribute('data-post-id');
                    deletePost(postId);
                });
            });
        })
        .catch(error => console.error('Error fetching posts:', error));
};


const setupCarousel = () => {
    document.querySelectorAll('.carousel').forEach(carousel => {
        const images = carousel.querySelectorAll('.carousel-images img');
        let currentIndex = 0;

        const showImage = (index) => {
            images.forEach((img, i) => {
                img.style.display = (i === index) ? 'block' : 'none';
            });
        };

        carousel.querySelector('.prev').addEventListener('click', () => {
            currentIndex = (currentIndex > 0) ? currentIndex - 1 : images.length - 1;
            showImage(currentIndex);
        });

        carousel.querySelector('.next').addEventListener('click', () => {
            currentIndex = (currentIndex < images.length - 1) ? currentIndex + 1 : 0;
            showImage(currentIndex);
        });

        showImage(currentIndex);
    });
};





    const deletePost = (postId) => {
        fetch('../php/delete_post.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ id: postId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadPosts();
            } else {
                alert('Kļūme dzēšot ierakstu: ' + data.message);
            }
        })
        .catch(error => console.error('Kļūme dzēšot ierakstu:', error));
    };

const addPostModal = () => {
    const modalHtml = `
    <div id="post-modal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>Pievienot ierakstu</h2>
            <form id="post-form" enctype="multipart/form-data">
                <div class="select-container">
				<br>
                    <label for="tab">Izvēlies ieraksta vietu:</label>
                    <select id="tab" name="tab" required>
                        <option value="news">Jaunumi</option>
                        <option value="other">Plūsma</option>
                    </select>
                </div>
                <br>
                <label for="description">Apraksts:</label>
                <textarea id="description" name="description" required></textarea>
                <br>
				<label for="tab">Attēli:</label>
                <div class="file-upload-container"> <!-- New container for flex layout -->
                    <div class="custom-file-input" id="custom-file-input">
                        <input type="file" id="images" name="images[]" accept="image/*" multiple style="display: none;">
                        <span class="plus-sign">+</span>
                    </div>
                    <div id="image-preview" class="image-preview"></div>
                </div>
                <br>
                <button type="submit">Pievienot</button>
            </form>
        </div>
    </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHtml);

    document.querySelectorAll('#add-post-top').forEach(button => {
        button.addEventListener('click', () => {
            document.getElementById('post-modal').style.display = 'block';
        });
    });

    document.querySelector('.close').addEventListener('click', () => {
        document.getElementById('post-modal').style.display = 'none';
		document.getElementById('post-form').reset();
        document.getElementById('image-preview').innerHTML = '';
    });

    document.getElementById('post-form').addEventListener('submit', (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        fetch('../php/add_post.php', {
            method: 'POST',
            body: formData,
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadPosts();
                document.getElementById('post-modal').style.display = 'none';
                document.getElementById('post-form').reset();
                document.getElementById('image-preview').innerHTML = '';
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => console.error('Error adding post:', error));
    });

    document.getElementById('custom-file-input').addEventListener('click', () => {
        document.getElementById('images').click();
    });

    document.getElementById('images').addEventListener('change', (event) => {
        previewImages(event.target.files);
    });
};

const previewImages = (files) => {
    const previewContainer = document.getElementById('image-preview');
    previewContainer.innerHTML = '';

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        
        reader.onload = (event) => {
            const imgElement = document.createElement('img');
            imgElement.src = event.target.result;
            previewContainer.appendChild(imgElement);
        };

        reader.readAsDataURL(file);
    });
};


    function addTabSwitchingFunctionality() {
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabs = document.querySelectorAll('.tab');

    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            tabButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');

            tabs.forEach(tab => tab.classList.remove('active'));
            const selectedTab = button.getAttribute('data-tab');
            document.getElementById(selectedTab).classList.add('active');
        });
    });
}

    
    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);
            }
        });
    });
    
    document.getElementById('logout').addEventListener('click', () => {
        window.location.href = '../php/logout.php';
    });
});
