#!/usr/bin/env php
<?php

/**
 * Background script to run cPanel backup imports
 * 
 * Usage: php run-cpanel-import.php <import_id> <username> <backup_file_path>
 */

// Check command line arguments
if ($argc !== 4) {
    echo "Usage: php run-cpanel-import.php <import_id> <username> <backup_file_path>\n";
    exit(1);
}

$importId = $argv[1];
$username = $argv[2];
$backupFilePath = $argv[3];

// Include required files
require_once __DIR__ . '/../web-files/configs/config.php';
require_once __DIR__ . '/../web-files/libs/CpanelBackupImporter.php';
require_once __DIR__ . '/../web-files/libs/mysqlmgmt.php';

// Log function (define early so we can use it everywhere)
function logMessage($message, $level = 'info') {
    global $importId;
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] [$level] $message";
    echo "$logEntry\n";
    error_log("CpanelImport[$importId]: $logEntry");
}

// Connect to database using the same method as other WHP scripts
try {
    $MySQLMgmt = new mysqlmgmt();
    $pdo = $MySQLMgmt->getMySQLConnection();
    
    if (!$pdo) {
        throw new Exception('Failed to establish database connection');
    }
    
    // Select the whp database
    $pdo->exec("USE whp");
    
    logMessage("Database connection established successfully");
} catch (Exception $e) {
    logMessage("Database connection failed: " . $e->getMessage(), 'error');
    
    // Try to update status if possible, but don't fail if we can't
    if (isset($pdo) && $pdo) {
        updateImportStatus($importId, 'failed', 0, 'Database connection failed: ' . $e->getMessage());
    }
    exit(1);
}

// Update import status
function updateImportStatus($importId, $status, $progress = null, $errorMessage = null, $log = null) {
    global $pdo;
    
    $sql = "UPDATE cpanel_imports SET status = ?";
    $params = [$status];
    
    if ($progress !== null) {
        $sql .= ", progress = ?";
        $params[] = $progress;
    }
    
    if ($errorMessage !== null) {
        $sql .= ", error_message = ?";
        $params[] = $errorMessage;
    }
    
    if ($log !== null) {
        $sql .= ", log = ?";
        $params[] = json_encode($log);
    }
    
    if ($status === 'completed' || $status === 'failed') {
        $sql .= ", completed_at = NOW()";
    }
    
    $sql .= " WHERE import_id = ?";
    $params[] = $importId;
    
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    } catch (PDOException $e) {
        error_log("Failed to update import status: " . $e->getMessage());
    }
}

// Log function moved to top of file for early availability

// Main import process
try {
    logMessage("Starting cPanel backup import for user: $username");
    updateImportStatus($importId, 'running', 5);
    
    // Validate input
    if (!file_exists($backupFilePath)) {
        throw new Exception("Backup file not found: $backupFilePath");
    }
    
    if (!is_readable($backupFilePath)) {
        throw new Exception("Backup file is not readable: $backupFilePath");
    }
    
    logMessage("Backup file validated: " . basename($backupFilePath));
    updateImportStatus($importId, 'running', 10);
    
    // Create importer instance
    $importer = new CpanelBackupImporter($pdo, $username);
    
    // Run the import
    logMessage("Starting backup import process");
    updateImportStatus($importId, 'running', 15);
    
    $result = $importer->importBackup($backupFilePath);
    
    if ($result['success']) {
        logMessage("Import completed successfully");
        logMessage("Domains imported: " . $result['domains_imported']);
        logMessage("Sites created: " . $result['sites_created']);
        
        updateImportStatus($importId, 'completed', 100, null, $result['log']);
        
        // Clean up uploaded file
        if (file_exists($backupFilePath)) {
            unlink($backupFilePath);
            logMessage("Cleaned up uploaded backup file");
        }
        
    } else {
        throw new Exception($result['error']);
    }
    
} catch (Exception $e) {
    $errorMessage = $e->getMessage();
    logMessage("Import failed: $errorMessage", 'error');
    
    updateImportStatus($importId, 'failed', null, $errorMessage);
    
    // Clean up uploaded file even on failure
    if (file_exists($backupFilePath)) {
        unlink($backupFilePath);
        logMessage("Cleaned up uploaded backup file after failure");
    }
    
    exit(1);
}

logMessage("cPanel backup import process completed");
exit(0);