<?php
// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

require_once 'libs/CpanelBackupImporter.php';
require_once 'libs/mysqlmgmt.php';

$pageTitle = "cPanel Backup Import";
$currentPage = 'cpanel-import';

// Initialize database connection
$MySQLMgmt = new mysqlmgmt();
$pdo = $MySQLMgmt->getMySQLConnection();

// AJAX requests are handled by /api/cpanel-import-ajax.php



?>

<!-- cPanel Backup Import Content -->
<div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="mb-4">
                    <h2><i class="bi bi-upload"></i> cPanel Backup Import</h2>
                </div>
                
                <!-- Early Release Notice -->
                <div class="alert alert-warning">
                    <h6><i class="bi bi-exclamation-triangle"></i> Early Release Feature</h6>
                    <p class="mb-0">This cPanel backup import feature is currently in early release. While functional, please test with non-critical data first and report any issues you encounter.</p>
                </div>
                
                <?php if (AUTH_USER === 'root'): ?>
                <!-- Root User - Target User Selection -->
                <div class="alert alert-info">
                    <h6><i class="bi bi-person-gear"></i> Root User - Import for Another User</h6>
                    <div class="mb-3">
                        <label for="target_user_select" class="form-label">Select Target User</label>
                        <select class="form-select" id="target_user_select" required>
                            <option value="">Loading users...</option>
                        </select>
                        <div class="form-text">Select the user account to import the cPanel backup into.</div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Import Steps -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Import Process</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="text-center">
                                    <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center" 
                                         style="width: 40px; height: 40px;">
                                        <span>1</span>
                                    </div>
                                    <p class="mt-2 mb-0">Upload Backup</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="text-center">
                                    <div class="bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" 
                                         style="width: 40px; height: 40px;" id="step2">
                                        <span>2</span>
                                    </div>
                                    <p class="mt-2 mb-0">Analyze Backup</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="text-center">
                                    <div class="bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" 
                                         style="width: 40px; height: 40px;" id="step3">
                                        <span>3</span>
                                    </div>
                                    <p class="mt-2 mb-0">Import Data</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="text-center">
                                    <div class="bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" 
                                         style="width: 40px; height: 40px;" id="step4">
                                        <span>4</span>
                                    </div>
                                    <p class="mt-2 mb-0">Complete</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Backup Selection Form -->
        <div class="row" id="selection-section">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Step 1: Select cPanel Backup File</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h6><i class="bi bi-info-circle"></i> Upload Instructions</h6>
                            <p><strong>Before using this tool:</strong></p>
                            <ol class="mb-2">
                                <?php if (AUTH_USER === 'root'): ?>
                                <li>Select the target user account above</li>
                                <li>Upload the cPanel backup (.tar.gz or .tgz) file to the user's <strong>userfiles</strong> directory</li>
                                <li>You can access userfiles through the File Manager or FTP at: <code>/userfiles/</code> for each user</li>
                                <li>Once uploaded, the backup files will appear in the dropdown below</li>
                                <?php else: ?>
                                <li>Upload your cPanel backup (.tar.gz or .tgz) file to your <strong>userfiles</strong> directory</li>
                                <li>You can access userfiles through the File Manager or FTP at: <code>/userfiles/</code></li>
                                <li>Once uploaded, refresh this page and select your backup file below</li>
                                <?php endif; ?>
                            </ol>
                            <p class="mb-0"><strong>This tool will import:</strong> Domains, website files, MySQL databases, and create DNS records. SSL certificates are handled automatically by our system.</p>
                        </div>

                        <div id="backup-files-container">
                            <div class="mb-3">
                                <label for="backup_file_select" class="form-label">Available Backup Files</label>
                                <select class="form-select" id="backup_file_select" required>
                                    <option value="">Loading backup files...</option>
                                </select>
                                <div class="form-text">
                                    Backup files from your userfiles directory. 
                                    <button type="button" class="btn btn-link btn-sm p-0" onclick="refreshBackupFiles()">
                                        <i class="bi bi-arrow-clockwise"></i> Refresh List
                                    </button>
                                </div>
                            </div>
                            
                            <div id="selected-backup-info" class="alert alert-secondary" style="display: none;">
                                <h6>Selected Backup:</h6>
                                <div id="backup-details"></div>
                            </div>

                            <button type="button" class="btn btn-primary" id="select-backup-btn" disabled>
                                <i class="bi bi-check-circle"></i> Select This Backup
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Import Progress -->
        <div class="row" id="import-section" style="display: none;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Import Progress</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <div class="progress">
                                <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                     id="import-progress" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>
                        
                        <div id="import-status" class="mb-3">
                            <span class="badge bg-primary">Starting Import...</span>
                        </div>
                        
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">Import Log</h6>
                            </div>
                            <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                                <pre id="import-log" class="mb-0"></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Import Results -->
        <div class="row" id="results-section" style="display: none;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Import Complete</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success">
                            <h6><i class="bi bi-check-circle"></i> Import Successful!</h6>
                            <div id="import-summary"></div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <a href="?page=sites" class="btn btn-primary">
                                <i class="bi bi-globe"></i> View Sites
                            </a>
                            <a href="?page=dashboard" class="btn btn-outline-secondary">
                                <i class="bi bi-house"></i> Dashboard
                            </a>
                            <button type="button" class="btn btn-outline-primary" onclick="startNewImport()">
                                <i class="bi bi-upload"></i> Import Another Backup
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const nonce = '<?php echo get_csrf_token(); ?>';
        let currentImportId = null;
        let statusCheckInterval = null;
        let availableBackups = [];

        // Load backup files on page load
        document.addEventListener('DOMContentLoaded', function() {
            <?php if (AUTH_USER === 'root'): ?>
            // For root, load users first, then backup files will load when user is selected
            loadUsers();
            <?php else: ?>
            // For regular users, load backup files immediately
            refreshBackupFiles();
            <?php endif; ?>
        });

        <?php if (AUTH_USER === 'root'): ?>
        // Load users for root user
        async function loadUsers() {
            try {
                const response = await fetch('/api/cpanel-import-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-Token': nonce
                    },
                    body: new URLSearchParams({
                        action: 'list_users'
                    })
                });

                const result = await response.json();
                const userSelect = document.getElementById('target_user_select');

                if (result.success) {
                    userSelect.innerHTML = '<option value="">Select a user...</option>';
                    result.users.forEach(user => {
                        const option = document.createElement('option');
                        option.value = user;
                        option.textContent = user;
                        userSelect.appendChild(option);
                    });
                    
                    // Add event listener to refresh backup files when user changes
                    userSelect.addEventListener('change', function() {
                        if (this.value) {
                            refreshBackupFiles();
                        } else {
                            // Clear backup files if no user selected
                            const backupSelect = document.getElementById('backup_file_select');
                            backupSelect.innerHTML = '<option value="">Select a user first</option>';
                            document.getElementById('select-backup-btn').disabled = true;
                        }
                    });
                } else {
                    userSelect.innerHTML = '<option value="">Failed to load users</option>';
                }
            } catch (error) {
                console.error('Failed to load users:', error);
                document.getElementById('target_user_select').innerHTML = '<option value="">Error loading users</option>';
            }
        }
        <?php endif; ?>

        // Refresh backup files list
        async function refreshBackupFiles() {
            try {
                const params = {
                    action: 'get_backup_files'
                };
                
                <?php if (AUTH_USER === 'root'): ?>
                // For root, include the selected target user
                const targetUserSelect = document.getElementById('target_user_select');
                if (targetUserSelect && targetUserSelect.value) {
                    params.target_user = targetUserSelect.value;
                } else if (targetUserSelect && !targetUserSelect.value) {
                    // No user selected yet, show message
                    const backupSelect = document.getElementById('backup_file_select');
                    backupSelect.innerHTML = '<option value="">Select a user first</option>';
                    return;
                }
                <?php endif; ?>
                
                const response = await fetch('/api/cpanel-import-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-Token': nonce
                    },
                    body: new URLSearchParams(params)
                });

                const result = await response.json();
                
                if (result.success) {
                    availableBackups = result.files;
                    updateBackupFilesList();
                } else {
                    console.error('Failed to load backup files:', result.error);
                    updateBackupFilesList([]);
                }
            } catch (error) {
                console.error('Error loading backup files:', error);
                updateBackupFilesList([]);
            }
        }

        // Update the backup files dropdown
        function updateBackupFilesList() {
            const select = document.getElementById('backup_file_select');
            select.innerHTML = '';

            if (availableBackups.length === 0) {
                select.innerHTML = '<option value="">No backup files found in userfiles directory</option>';
                document.getElementById('select-backup-btn').disabled = true;
            } else {
                select.innerHTML = '<option value="">Select a backup file...</option>';
                
                availableBackups.forEach(backup => {
                    const option = document.createElement('option');
                    option.value = backup.filename;
                    option.textContent = `${backup.filename} (${formatFileSize(backup.size)} - ${formatDate(backup.modified)})`;
                    select.appendChild(option);
                });
            }
        }

        // Handle backup file selection
        document.getElementById('backup_file_select').addEventListener('change', function() {
            const selectedFilename = this.value;
            const selectedBackup = availableBackups.find(b => b.filename === selectedFilename);
            
            if (selectedBackup) {
                // Show backup details
                const detailsDiv = document.getElementById('backup-details');
                detailsDiv.innerHTML = `
                    <strong>File:</strong> ${selectedBackup.filename}<br>
                    <strong>Size:</strong> ${formatFileSize(selectedBackup.size)}<br>
                    <strong>Modified:</strong> ${formatDate(selectedBackup.modified)}
                `;
                document.getElementById('selected-backup-info').style.display = 'block';
                document.getElementById('select-backup-btn').disabled = false;
            } else {
                document.getElementById('selected-backup-info').style.display = 'none';
                document.getElementById('select-backup-btn').disabled = true;
            }
        });

        // Handle backup selection confirmation
        document.getElementById('select-backup-btn').addEventListener('click', async function() {
            const selectedFilename = document.getElementById('backup_file_select').value;
            
            if (!selectedFilename) {
                alert('Please select a backup file');
                return;
            }

            try {
                const response = await fetch('/api/cpanel-import-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-Token': nonce
                    },
                    body: new URLSearchParams({
                        action: 'select_backup',
                        backup_file: selectedFilename,
                        nonce: nonce
                    })
                });

                const result = await response.json();

                if (result.success) {
                    // Update step indicator
                    updateStepIndicator(2);
                    
                    // Start import
                    startImport(result.path);
                } else {
                    alert('Failed to select backup: ' + result.error);
                }
            } catch (error) {
                alert('Failed to select backup: ' + error.message);
            }
        });

        async function startImport(backupFilePath) {
            <?php if (AUTH_USER === 'root'): ?>
            // Check if target user is selected for root
            const targetUserSelect = document.getElementById('target_user_select');
            if (!targetUserSelect.value) {
                alert('Please select a target user for the import');
                return;
            }
            <?php endif; ?>
            
            try {
                const params = {
                    action: 'start_import',
                    backup_file: backupFilePath
                };
                
                <?php if (AUTH_USER === 'root'): ?>
                params.target_user = targetUserSelect.value;
                <?php endif; ?>
                
                const response = await fetch('/api/cpanel-import-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-Token': nonce
                    },
                    body: new URLSearchParams(params)
                });

                const result = await response.json();

                if (result.success) {
                    currentImportId = result.import_id;
                    
                    // Hide selection section and show import progress
                    document.getElementById('selection-section').style.display = 'none';
                    document.getElementById('import-section').style.display = 'block';
                    
                    // Update step indicator
                    updateStepIndicator(3);
                    
                    // Start status checking
                    startStatusChecking();
                } else {
                    alert('Failed to start import: ' + result.error);
                }
            } catch (error) {
                alert('Failed to start import: ' + error.message);
            }
        }

        function startStatusChecking() {
            statusCheckInterval = setInterval(checkImportStatus, 2000);
            checkImportStatus(); // Check immediately
        }

        async function checkImportStatus() {
            if (!currentImportId) return;

            try {
                const response = await fetch('/api/cpanel-import-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRF-Token': nonce
                    },
                    body: new URLSearchParams({
                        action: 'get_import_status',
                        import_id: currentImportId
                    })
                });

                const result = await response.json();

                if (result.success) {
                    updateImportProgress(result);
                    
                    if (result.status === 'completed' || result.status === 'failed') {
                        clearInterval(statusCheckInterval);
                        
                        if (result.status === 'completed') {
                            showImportResults(result);
                        } else {
                            showImportError(result.error);
                        }
                    }
                }
            } catch (error) {
                console.error('Failed to check import status:', error);
            }
        }

        function updateImportProgress(status) {
            const progressBar = document.getElementById('import-progress');
            const statusDiv = document.getElementById('import-status');
            const logDiv = document.getElementById('import-log');
            
            // Update progress bar
            progressBar.style.width = (status.progress || 0) + '%';
            
            // Update status
            let badgeClass = 'bg-primary';
            if (status.status === 'completed') badgeClass = 'bg-success';
            else if (status.status === 'failed') badgeClass = 'bg-danger';
            
            statusDiv.innerHTML = `<span class="badge ${badgeClass}">${status.status.toUpperCase()}</span>`;
            
            // Update log
            if (status.log && status.log.length > 0) {
                logDiv.textContent = status.log.join('\n');
                logDiv.scrollTop = logDiv.scrollHeight;
            }
        }

        function showImportResults(status) {
            // Update step indicator
            updateStepIndicator(4);
            
            // Hide import progress
            document.getElementById('import-section').style.display = 'none';
            
            // Show results
            document.getElementById('results-section').style.display = 'block';
            
            // TODO: Parse and display import summary from status
            const summary = document.getElementById('import-summary');
            // Build the summary via DOM nodes (rather than innerHTML) so the
            // server-supplied `status.completed_at` value is treated as text.
            // The .local-time span lets the global whp-times.js handler
            // rewrite it to the user's locale + timezone.
            summary.replaceChildren();
            const intro = document.createElement('p');
            intro.textContent = 'Your cPanel backup has been successfully imported!';
            const completed = document.createElement('p');
            completed.appendChild(document.createTextNode('Import completed at: '));
            const timeEl = document.createElement('span');
            timeEl.className = 'local-time';
            timeEl.setAttribute('data-utc', status.completed_at);
            timeEl.setAttribute('data-format', 'datetime-seconds');
            timeEl.textContent = status.completed_at;
            completed.appendChild(timeEl);
            summary.appendChild(intro);
            summary.appendChild(completed);
        }

        function showImportError(error) {
            alert('Import failed: ' + error);
            
            // Reset to selection form
            document.getElementById('import-section').style.display = 'none';
            document.getElementById('selection-section').style.display = 'block';
            updateStepIndicator(1);
        }

        function updateStepIndicator(step) {
            for (let i = 1; i <= 4; i++) {
                const stepElement = document.getElementById(`step${i}`);
                if (stepElement) {
                    if (i <= step) {
                        stepElement.className = stepElement.className.replace('bg-secondary', 'bg-primary');
                    } else {
                        stepElement.className = stepElement.className.replace('bg-primary', 'bg-secondary');
                    }
                }
            }
        }

        function startNewImport() {
            // Reset form and show selection section
            document.getElementById('backup_file_select').value = '';
            document.getElementById('selected-backup-info').style.display = 'none';
            document.getElementById('select-backup-btn').disabled = true;
            document.getElementById('results-section').style.display = 'none';
            document.getElementById('selection-section').style.display = 'block';
            
            updateStepIndicator(1);
            currentImportId = null;
            
            if (statusCheckInterval) {
                clearInterval(statusCheckInterval);
            }
            
            refreshBackupFiles();
        }

        // Utility functions
        function formatFileSize(bytes) {
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            if (bytes === 0) return '0 Bytes';
            const i = Math.floor(Math.log(bytes) / Math.log(1024));
            return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
        }

        function formatDate(timestamp) {
            return new Date(timestamp * 1000).toLocaleString();
        }
    </script>
</div>