<?php
// cPanel Import AJAX Handler

// Set error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Start output buffering to catch any unwanted output
ob_start();

require_once('../auto-prepend.php');

// Check if user is authenticated
if (!defined('AUTH_USER')) {
    ob_clean();
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authenticated']);
    exit();
}

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

// Clean any output that might have been generated
ob_clean();

// Set JSON header
header('Content-Type: application/json');

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

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        switch ($_POST['action']) {
            case 'get_backup_files':
                $targetUser = $_POST['target_user'] ?? null;
                $result = ['success' => true, 'files' => getAvailableBackupFiles($targetUser)];
                echo json_encode($result);
                break;
                
            case 'select_backup':
                $result = selectBackupFile();
                echo json_encode($result);
                break;
                
            case 'list_users':
                if (AUTH_USER !== 'root') {
                    echo json_encode(['success' => false, 'error' => 'Not authorized']);
                    break;
                }
                $result = listSystemUsers();
                echo json_encode($result);
                break;
                
            case 'start_import':
                $targetUser = $_POST['target_user'] ?? null;
                $result = startImport($_POST['backup_file'], $targetUser);
                echo json_encode($result);
                break;
                
            case 'get_import_status':
                $result = getImportStatus($_POST['import_id']);
                echo json_encode($result);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Invalid action']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

function getAvailableBackupFiles($targetUser = null) {
    // Determine which user's directory to scan
    $username = AUTH_USER;
    if (AUTH_USER === 'root' && $targetUser) {
        $username = $targetUser;
    }
    
    $userfilesDir = '/docker/users/' . $username . '/userfiles';
    $backupFiles = [];
    
    if (is_dir($userfilesDir)) {
        $files = glob($userfilesDir . '/*.{tar.gz,tgz}', GLOB_BRACE);
        foreach ($files as $file) {
            $backupFiles[] = [
                'filename' => basename($file),
                'path' => $file,
                'size' => filesize($file),
                'modified' => filemtime($file)
            ];
        }
        
        // Sort by modification time (newest first)
        usort($backupFiles, function($a, $b) {
            return $b['modified'] - $a['modified'];
        });
    }
    
    return $backupFiles;
}

function selectBackupFile() {
    if (!isset($_POST['backup_file'])) {
        return ['success' => false, 'error' => 'No backup file selected'];
    }
    
    $selectedFile = $_POST['backup_file'];
    $userfilesDir = '/docker/users/' . AUTH_USER . '/userfiles';
    $fullPath = $userfilesDir . '/' . basename($selectedFile);
    
    // Validate file exists and is in userfiles directory
    if (!file_exists($fullPath) || dirname($fullPath) !== $userfilesDir) {
        return ['success' => false, 'error' => 'Invalid backup file selected'];
    }
    
    // Validate file extension
    if (!preg_match('/\.(tar\.gz|tgz)$/i', $selectedFile)) {
        return ['success' => false, 'error' => 'Invalid file type. Must be a .tar.gz or .tgz file'];
    }
    
    return [
        'success' => true,
        'filename' => basename($selectedFile),
        'path' => $fullPath,
        'size' => filesize($fullPath)
    ];
}

function startImport($backupFilePath, $targetUser = null) {
    global $pdo;
    
    if (!file_exists($backupFilePath)) {
        return ['success' => false, 'error' => 'Backup file not found'];
    }
    
    // Determine the target username
    $username = AUTH_USER;
    if (AUTH_USER === 'root' && $targetUser) {
        $username = $targetUser;
    }
    
    // Create import record
    $importId = uniqid('import_');
    $stmt = $pdo->prepare("
        INSERT INTO cpanel_imports (import_id, username, backup_file, status, created_at) 
        VALUES (?, ?, ?, 'running', NOW())
    ");
    $stmt->execute([$importId, $username, $backupFilePath]);
    
    // Start import in background
    $scriptPath = "/root/whp/scripts/run-cpanel-import.php";
    
    // Check if script exists
    if (!file_exists($scriptPath)) {
        return ['success' => false, 'error' => 'Import script not found: ' . $scriptPath];
    }
    
    // Build command with proper logging
    $logFile = "/var/log/cpanel-import-{$importId}.log";
    $command = "php " . escapeshellarg($scriptPath) . " " . 
               escapeshellarg($importId) . " " . 
               escapeshellarg($username) . " " . 
               escapeshellarg($backupFilePath) . " > " . escapeshellarg($logFile) . " 2>&1 &";
    
    // Log the command for debugging
    error_log("Starting cPanel import with command: " . $command);
    
    // Execute command and capture return value
    $output = [];
    $returnCode = 0;
    exec($command, $output, $returnCode);
    
    // Check if command started successfully
    if ($returnCode !== 0) {
        error_log("Failed to start cPanel import process. Return code: " . $returnCode);
        return ['success' => false, 'error' => 'Failed to start import process'];
    }
    
    // Log successful start
    error_log("cPanel import process started successfully for import ID: " . $importId);
    
    return [
        'success' => true,
        'import_id' => $importId,
        'log_file' => $logFile
    ];
}

function getImportStatus($importId) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT * FROM cpanel_imports WHERE import_id = ? AND username = ?");
    $stmt->execute([$importId, AUTH_USER]);
    $import = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$import) {
        return ['success' => false, 'error' => 'Import not found'];
    }
    
    return [
        'success' => true,
        'status' => $import['status'],
        'progress' => $import['progress'] ?? 0,
        'log' => $import['log'] ? json_decode($import['log'], true) : [],
        'error' => $import['error_message'],
        'completed_at' => $import['completed_at']
    ];
}

/**
 * List system users for root user selection
 */
function listSystemUsers() {
    $users = [];
    
    // Get users from /etc/passwd who have home directories in /docker/users/
    $passwdContent = file_get_contents('/etc/passwd');
    $lines = explode("\n", $passwdContent);
    
    foreach ($lines as $line) {
        $parts = explode(':', $line);
        if (count($parts) >= 6) {
            $username = $parts[0];
            $homeDir = $parts[5];
            
            // Skip system users
            if (in_array($username, ['root', 'bin', 'daemon', 'adm', 'lp', 'sync', 'shutdown', 'halt', 'mail', 'operator', 'games', 'ftp', 'nobody', 'systemd-network', 'dbus', 'polkitd', 'sshd', 'postfix', 'chrony', 'mysql', 'apache', 'nginx', 'named', 'rpc', 'rpcuser', 'nfsnobody'])) {
                continue;
            }
            
            // Check if user has a directory in /docker/users/
            if (is_dir("/docker/users/$username")) {
                $users[] = $username;
            }
        }
    }
    
    sort($users);
    
    return [
        'success' => true,
        'users' => $users
    ];
}
?>