<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - File Manager</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
    <style>
        /* Global Styles */
        body {
            font-family: 'Arial', sans-serif;
            background-color: #2c2f38;
            margin: 0;
            padding: 0;
            color: #e0e0e0;
        }

        #content {
            padding: 20px;
            overflow-y: auto;
        }

        /* File Manager Header */
        .file-manager-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
        }

        .file-manager-header h2 {
            font-size: 28px;
            font-weight: bold;
            color: #4CAF50;
        }

        /* File and Folder Item Styling */
        .file-item, .folder-item {
            width: 150px; /* Smaller width */
            padding: 15px; /* Smaller padding */
            border-radius: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background-color: #333;
            color: #fff;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            justify-content: flex-start; /* Align content to the top */
            align-items: center;
            height: 120px;  /* Ensure same height */
            overflow: hidden; /* Hide overflowed content */
            position: relative;
        }

        .file-item:hover, .folder-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
        }

        .file-item i, .folder-item i {
            font-size: 36px; /* Smaller icon size */
            margin-bottom: 10px;
            color: #ff9800;
        }

        .file-item .file-name, .folder-item .folder-name {
            font-size: 13px; /* Smaller font size */
            font-weight: bold;
            color: #fff;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            max-width: 100%;
            margin-top: auto; /* Push the name to the bottom */
        }
        
        .file-item .file-details {
            font-size: 11px;
            color: #b0b0b0;
            margin-top: 5px;
            width: 100%;
            text-align: center;
            line-height: 1.2;
        }

        .folder-item {
            background-color: #3b3f45;
            border: 1px solid #4CAF50;
        }

        .file-item {
            background-color: #154855;
        }

        .folder-item:hover {
            background-color: #388e3c;
        }

        /* Upload Button Styling */
        .upload-btn {
            padding: 12px 30px;
            background-color: #154855;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .upload-btn:hover {
            background-color: #154855;
        }

        /* Modal Styling */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            padding-top: 60px;
        }

        .modal-title {
            color: #154855;
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 30px;
            width: 40%;
            border-radius: 10px;
            border: 1px solid #888;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            font-size: 18px;
            margin-bottom: 20px;
            color: #154855;
        }

        .modal-footer {
            text-align: center;
            margin-top: 20px;
        }

        .modal-button {
            padding: 12px 25px;
            margin: 5px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .close-btn {
            padding: 3px;
            color: red;
            border: none;
            background-color: transparent;
            font-size: 18px;
            cursor: pointer;
        }

        .download-btn {
            background-color: #2b847f;
            color: white;
        }

        .delete-btn {
            background-color: #894843;
            color: white;
        }

        .open-btn {
            background-color: #a09c57;
            color: white;
        }

        /* Upload Progress Bar */
        .progress-container {
            width: 100%;
            background-color: #f3f3f3;
            border-radius: 10px;
            margin-top: 15px;
            height: 10px;
            box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
        }

        .progress-bar {
            width: 0%;
            height: 100%;
            background-color: #4CAF50;
            border-radius: 10px;
            transition: width 0.4s ease;
        }

        /* Loading Text */
        .processing-text {
            font-size: 18px;
            margin-top: 10px;
            text-align: center;
        }

        /* File Grid Layout */
        #file-content {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 20px;
            justify-items: center;
            padding-top: 20px;
        }

        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
        }

        .percentage-text {
            font-size: 14px;
            color: #4CAF50;
            margin-top: 5px;
            text-align: center;
        }

    </style>
</head>
<body>

    <div class="left-panel left-panel-show" id="left-panel">
        </div>

    <div class="main-content main-content-normal" id="main-content">
        <div id="content">
            <div class="file-manager-header">
                <h2>File Manager - Instructions</h2>
                <button class="upload-btn" onclick="openUploadDialog()">
                    <i class="fas fa-upload"></i> Upload File
                </button>
            </div>

            <div id="file-content" class="loading">
                <span>Loading files...</span>
            </div>
        </div>
    </div>

    <div id="file-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span id="modal-title"></span>
                <button class="close-btn" onclick="closeModal('file-modal')">×</button>
            </div>
            <div class="modal-footer">
                <button class="modal-button download-btn" onclick="downloadFile()">
                    <i class="fas fa-download"></i>
                </button>
                <button class="modal-button delete-btn" onclick="deleteFile()">
                    <i class="fas fa-trash-alt"></i>
                </button>
                <button class="modal-button open-btn" onclick="openFile()">
                    <i class="fas fa-eye"></i>
                </button>
            </div>
        </div>
    </div>

    <div id="upload-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span id="upload-modal-title" class="modal-title">Upload File</span>
                <button class="close-btn" onclick="closeModal('upload-modal')">×</button>
            </div>
            <div class="modal-body">
                <form id="upload-form" enctype="multipart/form-data">
                    <input type="file" name="fileToUpload" id="fileToUpload" required>
                    <button type="submit" class="modal-button upload-btn">Submit</button>
                </form>
                <div id="upload-processing" style="display: none; margin-top: 20px;">
                    <div class="progress-container">
                        <div id="progress-bar" class="progress-bar"></div>
                    </div>
                    <div class="percentage-text" id="progress-percentage">0%</div>
                    <span class="processing-text">Uploading...</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedFilePath = '';  // To store the selected file's path
        let currentFolder = 'instruction'; // To keep track of the current folder

        // Function to fetch files and folders from a specified directory
        function fetchFiles(folderName = 'instruction') {
            currentFolder = folderName; // Update current folder
            const fileContent = document.getElementById('file-content');
            fileContent.innerHTML = '<p class="loading">Loading files...</p>';

            fetch(`../php/fetch_files.php?folder_name=${encodeURIComponent(folderName)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        displayFiles(data.files);
                    } else {
                        fileContent.innerHTML = '<p>No files or folders found.</p>';
                    }
                })
                .catch(error => {
                    fileContent.innerHTML = '<p>Error loading files.</p>';
                });
        }

        // Display the files and folders dynamically
        function displayFiles(files) {
            const fileContent = document.getElementById('file-content');
            fileContent.innerHTML = '';  // Clear the content before adding new items

            if (!files || files.length === 0) {
                fileContent.innerHTML = '<p>No files or folders found.</p>';
                return;
            }

            // Loop through files and display them
            files.forEach(file => {
                const filePath = file.path;
                const fileName = file.name;
                const isDirectory = file.isDirectory;

                if (fileName && filePath) {
                    let fileItem;
                    if (isDirectory) {
                        fileItem = createFolderItem(fileName, filePath);
                    } else {
                        fileItem = createFileItem(fileName, filePath, file.size);
                    }

                    fileContent.appendChild(fileItem);
                }
            });
        }

        // Create file item (with Font Awesome icons)
        function createFileItem(fileName, filePath, fileSize) {
            const fileItem = document.createElement('div');
            fileItem.classList.add('file-item');
            fileItem.addEventListener('click', () => openFilePopup(filePath, fileName));

            const icon = document.createElement('i');
            icon.classList.add('fas', getFileIcon(fileName));
            fileItem.appendChild(icon);

            const nameDiv = document.createElement('div');
            nameDiv.classList.add('file-name');
            nameDiv.textContent = truncateFileName(fileName);
            fileItem.appendChild(nameDiv);

            const detailsDiv = document.createElement('div');
            detailsDiv.classList.add('file-details');
            detailsDiv.innerHTML = `<span>${getFileType(fileName)}</span><br><span>${formatFileSize(fileSize)}</span>`;
            fileItem.appendChild(detailsDiv);

            return fileItem;
        }
        
        // Truncate file name to fit in one line
        function truncateFileName(fileName) {
            const parts = fileName.split('.');
            const name = parts[0];
            const ext = parts.length > 1 ? '.' + parts.pop() : '';
            const maxLength = 10;
            if (name.length > maxLength) {
                return name.substring(0, maxLength) + '...' + ext;
            }
            return fileName;
        }

        // Format file size for display
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // Get file type from extension
        function getFileType(fileName) {
            const ext = fileName.split('.').pop().toUpperCase();
            if (ext.length > 5) return 'File'; // Fallback for long or no extension
            return ext + ' File';
        }

        // Open file options in the modal
        function openFilePopup(filePath, fileName) {
            selectedFilePath = filePath;
            document.getElementById('modal-title').textContent = fileName;
            document.getElementById('file-modal').style.display = 'block';
        }

        // Open the file
        function openFile() {
            window.open('../' + selectedFilePath, '_blank');
            closeModal('file-modal');
        }

        // Download the selected file
        function downloadFile() {
            const link = document.createElement('a');
            link.href = '../' + selectedFilePath;
            link.download = selectedFilePath.split('/').pop();
            link.click();
            closeModal('file-modal');
        }

        // Delete the selected file
        function deleteFile() {
            Swal.fire({
                title: 'Are you sure?',
                text: 'You won\'t be able to revert this!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(`../php/delete_file.php?file_path=${encodeURIComponent(selectedFilePath)}`, { method: 'DELETE' })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'success') {
                                Swal.fire('Deleted!', 'Your file has been deleted.', 'success');
                                fetchFiles(currentFolder);  // Refresh file list
                            } else {
                                Swal.fire('Error!', data.message, 'error');
                            }
                        })
                        .catch(error => {
                            Swal.fire('Error!', 'An error occurred while deleting the file.', 'error');
                        });
                }
            });
            closeModal('file-modal');
        }

        // Close a specific modal window
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // Create folder item
        function createFolderItem(folderName, folderPath) {
            const folderItem = document.createElement('div');
            folderItem.classList.add('folder-item');
            folderItem.addEventListener('click', () => fetchFiles(folderPath));

            const icon = document.createElement('i');
            icon.classList.add('fas', 'fa-folder');
            folderItem.appendChild(icon);

            const nameDiv = document.createElement('div');
            nameDiv.classList.add('folder-name');
            nameDiv.textContent = folderName;
            folderItem.appendChild(nameDiv);

            return folderItem;
        }

        // Get file icon based on extension
        function getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase();
            switch (ext) {
                case 'pdf': return 'fa-file-pdf';
                case 'txt': return 'fa-file-alt';
                case 'doc':
                case 'docx': return 'fa-file-word';
                case 'xls':
                case 'xlsx': return 'fa-file-excel';
                case 'ppt':
                case 'pptx': return 'fa-file-powerpoint';
                case 'zip':
                case 'rar': return 'fa-file-archive';
                case 'mp3':
                case 'wav': return 'fa-file-audio';
                case 'mp4':
                case 'mov': return 'fa-file-video';
                case 'jpg':
                case 'jpeg':
                case 'png':
                case 'gif': return 'fa-file-image';
                case 'html':
                case 'css':
                case 'js':
                case 'php':
                case 'json':
                case 'xml': return 'fa-file-code';
                default: return 'fa-file';
            }
        }

        // Open the upload dialog modal
        function openUploadDialog() {
            document.getElementById('upload-modal').style.display = 'block';
            document.getElementById('upload-processing').style.display = 'none'; // Hide progress on new open
            document.getElementById('progress-bar').style.width = '0%';
            document.getElementById('progress-percentage').textContent = '0%';
        }

        // Handle the file upload form submission with progress
        document.getElementById('upload-form').addEventListener('submit', function(event) {
            event.preventDefault();

            const fileInput = document.getElementById('fileToUpload');
            const file = fileInput.files[0];

            if (!file) {
                Swal.fire('Error', 'Please select a file to upload.', 'error');
                return;
            }

            // Show the processing spinner and text
            document.getElementById('upload-processing').style.display = 'block';

            const formData = new FormData();
            formData.append('fileToUpload', file);
            formData.append('destinationFolder', currentFolder);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '../php/upload_file.php', true);

            // Update progress bar as the file uploads
            xhr.upload.onprogress = function(event) {
                if (event.lengthComputable) {
                    const percentage = Math.round((event.loaded / event.total) * 100);
                    document.getElementById('progress-bar').style.width = percentage + '%';
                    document.getElementById('progress-percentage').textContent = percentage + '%';
                }
            };

            // Handle the response
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        if (data.status === 'success') {
                            Swal.fire('Success!', 'File uploaded successfully!', 'success');
                            closeModal('upload-modal');
                            fetchFiles(currentFolder); // Refresh file list
                        } else {
                            Swal.fire('Error!', data.message, 'error');
                        }
                    } catch (e) {
                        Swal.fire('Error!', 'An unexpected error occurred.', 'error');
                    }
                } else {
                    Swal.fire('Error!', 'An error occurred while uploading. Server response: ' + xhr.status, 'error');
                }
            };
            
            xhr.onerror = function() {
                Swal.fire('Error!', 'Network error or server unreachable.', 'error');
            };

            // Send the form data
            xhr.send(formData);
        });

        // Initial fetch for the 'instruction' folder
        fetchFiles();
    </script>

</body>
</html>