<html lang=en><meta charset=viewport content="width=device-width, initial-scale=1.0"><title>Files</title><script src=https://cdn.tailwindcss.com></script><link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css rel=stylesheet><style>.hidden{display:none}.no-select{user-select:none}.no-scroll{overflow:hidden}.alert{position:fixed;bottom:20px;left:20px;background-color:#323232;color:#fff;padding:10px 20px;border-radius:5px;display:flex;align-items:center;opacity:0;transition:opacity .5s,transform .5s;transform:translateY(20px)}.alert.show{opacity:1;transform:translateY(0)}.alert.success{background-color:#4caf50}.alert.error{background-color:#f44336}.alert i{margin-right:10px}.modal{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);display:flex;justify-content:center;align-items:center;z-index:50}.modal-content{background:#1a202c;padding:20px;border-radius:8px;text-align:center;width:90%;max-width:400px}</style><body class="bg-gray-900 h-screen no-scroll no-select text-white"><div class="flex h-full"><div class="p-4 bg-gray-800 w-1/5"id=sidebar><div class=mb-6><ul class=space-y-4><li class="flex items-center space-x-2"><i class="fas fa-tachometer-alt"></i> <a class=hover:text-gray-400 href=panel.html>Dashboard</a><li class="flex items-center space-x-2"><i class="fas fa-folder"></i> <a class=hover:text-gray-400 href=files.html>Files</a><li class="flex items-center space-x-2"><i class="fas fa-cog"></i> <a class=hover:text-gray-400 href=settings.html>Settings</a></ul></div></div><div class="p-4 flex-1 overflow-hidden"><div class="flex items-center justify-between mb-6"><div class="flex items-center space-x-2"><span class="text-xl font-bold">TownZone Hosting</span> <i class="fas fa-server text-xl"></i></div><div class="flex items-center bg-gray-800 px-4 py-2 rounded text-white"id=serverStatus><div class="bg-green-500 h-3 mr-2 rounded-full w-3"></div><span>RUNNING</span></div></div><div id=filesContent><div class="rounded bg-gray-800 h-full overflow-y-auto p-4"><h3 class="mb-4 font-semibold text-lg">Files</h3><div class="flex space-x-4 mb-4"><input class=hidden id=fileInput multiple type=file> <button class="rounded text-white px-4 py-2 bg-blue-600 hover:bg-blue-700"id=uploadFileBtn>Upload Files</button> <button class="rounded text-white px-4 py-2 bg-yellow-600 hover:bg-yellow-700"id=createFileBtn>Create File</button> <button class="rounded text-white px-4 py-2 bg-purple-600 hover:bg-purple-700"id=createFolderBtn>Create Folder</button></div><div class="mb-4 text-gray-400 text-sm"id=pathDisplay></div><ul class=space-y-2 id=fileList></ul></div></div></div></div><div class=alert id=alert><i class=fas></i> <span id=alertMessage></span></div><div class="hidden modal"id=modal><div class=modal-content><i class="fas fa-question-circle mb-4 text-4xl"></i><h3 class="mb-4 font-semibold text-lg">Enter Name</h3><input class="rounded text-white bg-gray-700 mb-4 p-2 w-full"id=modalInput placeholder="Enter name"><div class="flex space-x-4 justify-end"><button class="rounded text-white px-4 py-2 bg-red-600 hover:bg-red-700"id=modalCancelBtn>Cancel</button> <button class="rounded text-white px-4 py-2 bg-blue-600 hover:bg-blue-700"id=modalConfirmBtn>Confirm</button></div></div></div><script>let currentPath = '';
        let modalCallback = null;

        function showAlert(message, type) {
            const alertBox = document.getElementById('alert');
            const alertMessage = document.getElementById('alertMessage');
            const alertIcon = alertBox.querySelector('i');

            alertMessage.textContent = message;
            alertBox.className = `alert show ${type}`;
            alertIcon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-times-circle';

            setTimeout(() => {
                alertBox.classList.remove('show');
            }, 3000);
        }

        function showModal(callback, defaultValue = '') {
            modalCallback = callback;
            document.getElementById('modalInput').value = defaultValue;
            document.getElementById('modal').classList.remove('hidden');
        }

        function hideModal() {
            document.getElementById('modal').classList.add('hidden');
            document.getElementById('modalInput').value = '';
        }

        document.getElementById('modalCancelBtn').addEventListener('click', hideModal);

        document.getElementById('modalConfirmBtn').addEventListener('click', function() {
            const inputValue = document.getElementById('modalInput').value;
            if (modalCallback) {
                modalCallback(inputValue);
            }
            hideModal();
        });

        document.getElementById('uploadFileBtn').addEventListener('click', function() {
            document.getElementById('fileInput').click();
        });

        document.getElementById('createFileBtn').addEventListener('click', function() {
            showModal(async function(fileName) {
                if (fileName) {
                    try {
                        const response = await fetch('http://10.147.19.217:3000/create-file', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ path: `${currentPath}/${fileName}`, content: '' })
                        });
                        if (response.ok) {
                            showAlert('File created successfully!', 'success');
                            addFileToList(fileName, `${currentPath}/${fileName}`);
                        } else {
                            showAlert('Failed to create file.', 'error');
                        }
                    } catch (error) {
                        console.error('Error creating file:', error);
                        showAlert('Error creating file.', 'error');
                    }
                }
            });
        });

        document.getElementById('createFolderBtn').addEventListener('click', function() {
            showModal(async function(folderName) {
                if (folderName) {
                    try {
                        const response = await fetch('http://10.147.19.217:3000/create-directory', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ path: `${currentPath}/${folderName}` })
                        });
                        if (response.ok) {
                            showAlert('Folder created successfully!', 'success');
                            addFolderToList(folderName, `${currentPath}/${folderName}`);
                        } else {
                            showAlert('Failed to create folder.', 'error');
                        }
                    } catch (error) {
                        console.error('Error creating folder:', error);
                        showAlert('Error creating folder.', 'error');
                    }
                }
            });
        });

        document.getElementById('fileInput').addEventListener('change', async function(event) {
            const files = event.target.files;
            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('files', files[i]);
            }
            try {
                const response = await fetch(`http://10.147.19.217:3000/upload?path=${currentPath}`, {
                    method: 'POST',
                    body: formData
                });
                if (response.ok) {
                    showAlert('Files uploaded successfully!', 'success');
                    for (let i = 0; i < files.length; i++) {
                        addFileToList(files[i].name, `${currentPath}/${files[i].name}`);
                    }
                } else {
                    showAlert('Failed to upload files.', 'error');
                }
            } catch (error) {
                console.error('Error uploading files:', error);
                showAlert('Error uploading files.', 'error');
            }
        });

        async function loadFiles(path = '') {
            currentPath = path;
            try {
                const response = await fetch(`http://10.147.19.217:3000/directory?path=${path}`);
                const data = await response.json();
                const fileList = document.getElementById('fileList');
                fileList.innerHTML = '';
                const pathDisplay = document.getElementById('pathDisplay');
                pathDisplay.innerHTML = '';

                const pathParts = path.split('/').filter(Boolean);
                pathParts.forEach((part, index) => {
                    const span = document.createElement('span');
                    span.textContent = part;
                    span.className = 'cursor-pointer hover:underline';
                    span.addEventListener('click', () => {
                        const newPath = pathParts.slice(0, index + 1).join('/');
                        loadFiles(newPath);
                    });
                    pathDisplay.appendChild(span);
                    if (index < pathParts.length - 1) {
                        const separator = document.createElement('span');
                        separator.textContent = ' / ';
                        pathDisplay.appendChild(separator);
                    }
                });

                if (pathParts.length > 0) {
                    const rootSpan = document.createElement('span');
                    rootSpan.textContent = 'Root';
                    rootSpan.className = 'cursor-pointer hover:underline';
                    rootSpan.addEventListener('click', () => {
                        loadFiles('');
                    });
                    pathDisplay.insertBefore(rootSpan, pathDisplay.firstChild);
                    const separator = document.createElement('span');
                    separator.textContent = ' / ';
                    pathDisplay.insertBefore(separator, pathDisplay.childNodes[1]);
                }

                data.forEach(item => {
                    if (item.type === 'file') {
                        addFileToList(item.name, item.path);
                    } else if (item.type === 'directory') {
                        addFolderToList(item.name, item.path);
                    }
                });
            } catch (error) {
                console.error('Error loading files:', error);
            }
        }

        function addFileToList(fileName, filePath) {
            const fileList = document.getElementById('fileList');
            const listItem = document.createElement('li');
            listItem.className = 'bg-gray-700 p-2 rounded flex justify-between items-center';

            const fileSpan = document.createElement('span');
            fileSpan.className = 'flex items-center space-x-2 cursor-pointer';
            fileSpan.innerHTML = `<i class="fas fa-file-alt"></i><span>${fileName}</span>`;
            fileSpan.addEventListener('click', function() {
                window.location.href = `file-editor.html?path=${encodeURIComponent(filePath)}`;
            });

            const buttonContainer = document.createElement('div');
            buttonContainer.className = 'flex space-x-2';

            const renameButton = document.createElement('button');
            renameButton.textContent = 'Rename';
            renameButton.className = 'bg-yellow-600 hover:bg-yellow-700 text-white px-2 py-1 rounded';
            renameButton.addEventListener('click', function() {
                showModal(async function(newName) {
                    if (newName) {
                        try {
                            const response = await fetch('http://10.147.19.217:3000/rename', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ path: filePath, newName: `${currentPath}/${newName}` })
                            });
                            if (response.ok) {
                                showAlert('File renamed successfully!', 'success');
                                fileSpan.querySelector('span').textContent = newName;
                            } else {
                                showAlert('Failed to rename file.', 'error');
                            }
                        } catch (error) {
                            console.error('Error renaming file:', error);
                            showAlert('Error renaming file.', 'error');
                        }
                    }
                }, fileName);
            });

            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.className = 'bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded';
            deleteButton.addEventListener('click', async function() {
                try {
                    const response = await fetch('http://10.147.19.217:3000/delete', {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ path: filePath })
                    });
                    if (response.ok) {
                        showAlert('File deleted successfully!', 'success');
                        fileList.removeChild(listItem);
                    } else {
                        showAlert('Failed to delete file.', 'error');
                    }
                } catch (error) {
                    console.error('Error deleting file:', error);
                    showAlert('Error deleting file.', 'error');
                }
            });

            buttonContainer.appendChild(renameButton);
            buttonContainer.appendChild(deleteButton);
            listItem.appendChild(fileSpan);
            listItem.appendChild(buttonContainer);
            fileList.appendChild(listItem);
        }

        function addFolderToList(folderName, folderPath) {
            const fileList = document.getElementById('fileList');
            const listItem = document.createElement('li');
            listItem.className = 'bg-gray-700 p-2 rounded flex justify-between items-center';

            const folderSpan = document.createElement('span');
            folderSpan.className = 'flex items-center space-x-2 cursor-pointer';
            folderSpan.innerHTML = `<i class="fas fa-folder"></i><span>${folderName}</span>`;
            folderSpan.addEventListener('click', function() {
                loadFiles(folderPath);
            });

            const buttonContainer = document.createElement('div');
            buttonContainer.className = 'flex space-x-2';

            const renameButton = document.createElement('button');
            renameButton.textContent = 'Rename';
            renameButton.className = 'bg-yellow-600 hover:bg-yellow-700 text-white px-2 py-1 rounded';
            renameButton.addEventListener('click', function() {
                showModal(async function(newName) {
                    if (newName) {
                        try {
                            const response = await fetch('http://10.147.19.217:3000/rename', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ path: folderPath, newName: `${currentPath}/${newName}` })
                            });
                            if (response.ok) {
                                showAlert('Folder renamed successfully!', 'success');
                                folderSpan.querySelector('span').textContent = newName;
                            } else {
                                showAlert('Failed to rename folder.', 'error');
                            }
                        } catch (error) {
                            console.error('Error renaming folder:', error);
                            showAlert('Error renaming folder.', 'error');
                        }
                    }
                }, folderName);
            });

            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.className = 'bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded';
            deleteButton.addEventListener('click', async function() {
                try {
                    const response = await fetch('http://10.147.19.217:3000/delete', {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ path: folderPath })
                    });
                    if (response.ok) {
                        showAlert('Folder deleted successfully!', 'success');
                        fileList.removeChild(listItem);
                    } else {
                        showAlert('Failed to delete folder.', 'error');
                    }
                } catch (error) {
                    console.error('Error deleting folder:', error);
                    showAlert('Error deleting folder.', 'error');
                }
            });

            buttonContainer.appendChild(renameButton);
            buttonContainer.appendChild(deleteButton);
            listItem.appendChild(folderSpan);
            listItem.appendChild(buttonContainer);
            fileList.appendChild(listItem);
        }

        async function loadBackgroundImage() {
            try {
                const response = await fetch('http://10.147.19.217:3000/background');
                const data = await response.json();
                if (data.url) {
                    document.body.style.backgroundImage = `url(${data.url})`;
                    document.body.style.backgroundSize = 'cover';
                    document.body.style.backgroundRepeat = 'no-repeat';
                    document.getElementById('sidebar').style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
                }
            } catch (error) {
                console.error('Error loading background image:', error);
            }
        }

        async function fetchServerStatus() {
            try {
                const response = await fetch('http://10.147.19.217:3000/status/townzone');
                const data = await response.json();
                const statusElement = document.getElementById('serverStatus');
                if (data.status === 'online') {
                    statusElement.innerHTML = '<div class="bg-green-500 h-3 w-3 rounded-full mr-2"></div><span>RUNNING</span>';
                } else {
                    statusElement.innerHTML = '<div class="bg-red-500 h-3 w-3 rounded-full mr-2"></div><span>OFFLINE</span>';
                }
            } catch (error) {
                console.error('Error fetching server status:', error);
            }
        }

        loadBackgroundImage();
              fetchServerStatus();
        setInterval(fetchServerStatus, 1000);
        loadFiles();
          document.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
            }
        });</script>