<?php
header('Content-Type: application/json');

// Check API permission
check_api_permission('terminal');

require_once('/docker/whp/web/libs/mysqlmgmt.php');

$response = ['success' => false, 'error' => 'Unknown error'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['error'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

$is_root = (defined('AUTH_USER') && AUTH_USER === 'root');

try {
    $MySQLMgmt = new mysqlmgmt();
    $db = $MySQLMgmt->getMySQLConnection();
    if (!$db) {
        $response = ['success' => false, 'error' => 'Database connection failed'];
        echo json_encode($response);
        exit;
    }
    
    switch ($action) {
        case 'list_containers':
            if ($is_root) {
                // Root sees all containers
                $stmt = $db->query("
                    SELECT 
                        sc.container_id,
                        s.site_name,
                        s.username,
                        COALESCE(sd.fqdn, d.domain_name) as primary_domain,
                        ct.name as container_type
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    JOIN whp.domains d ON s.primary_domain_id = d.id
                    LEFT JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.container_types ct ON s.container_type_id = ct.id
                    WHERE sc.status = 'running'
                    ORDER BY s.username, s.site_name, sc.container_number
                ");
            } else {
                // Regular users see only their containers
                $stmt = $db->prepare("
                    SELECT 
                        sc.container_id,
                        s.site_name,
                        s.username,
                        COALESCE(sd.fqdn, d.domain_name) as primary_domain,
                        ct.name as container_type
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    JOIN whp.domains d ON s.primary_domain_id = d.id
                    LEFT JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                    JOIN whp.container_types ct ON s.container_type_id = ct.id
                    WHERE sc.status = 'running' AND s.username = ?
                    ORDER BY s.site_name, sc.container_number
                ");
                $stmt->execute([AUTH_USER]);
            }
            
            $containers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $response = ['success' => true, 'containers' => $containers];
            break;
            
        case 'execute_command':
            $container_id = $input['container_id'] ?? '';
            $command = $input['command'] ?? '';
            $user = $input['user'] ?? '';
            $shell = $input['shell'] ?? 'bash';
            
            if (empty($container_id) || empty($command)) {
                $response['error'] = 'Missing required parameters';
                break;
            }
            
            // Verify container access
            if ($is_root) {
                $stmt = $db->prepare("
                    SELECT s.username 
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    WHERE sc.container_id = ?
                ");
                $stmt->execute([$container_id]);
            } else {
                $stmt = $db->prepare("
                    SELECT s.username 
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    WHERE sc.container_id = ? AND s.username = ?
                ");
                $stmt->execute([$container_id, AUTH_USER]);
            }
            
            $container_info = $stmt->fetch();
            if (!$container_info) {
                $response['error'] = 'Access denied or container not found';
                break;
            }
            
            // Default to container owner if no user specified
            if (empty($user)) {
                $user = $container_info['username'];
            }
            
            // Build docker exec command
            $docker_cmd = sprintf(
                "docker exec -i %s %s -c %s 2>&1",
                escapeshellarg($container_id),
                escapeshellarg($shell),
                escapeshellarg($command)
            );
            
            if ($user !== 'root') {
                $docker_cmd = sprintf(
                    "docker exec -i --user %s %s %s -c %s 2>&1",
                    escapeshellarg($user),
                    escapeshellarg($container_id),
                    escapeshellarg($shell),
                    escapeshellarg($command)
                );
            }
            
            // Execute command
            $output = shell_exec($docker_cmd);
            
            $response = [
                'success' => true,
                'output' => $output,
                'command' => $command
            ];
            break;
            
        case 'create_session':
            $container_id = $input['container_id'] ?? '';
            $user = $input['user'] ?? '';
            $shell = $input['shell'] ?? 'bash';
            
            if (empty($container_id)) {
                $response['error'] = 'Missing container ID';
                break;
            }
            
            // Verify container access (same as execute_command)
            if ($is_root) {
                $stmt = $db->prepare("
                    SELECT s.username 
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    WHERE sc.container_id = ?
                ");
                $stmt->execute([$container_id]);
            } else {
                $stmt = $db->prepare("
                    SELECT s.username 
                    FROM whp.site_containers sc
                    JOIN whp.sites s ON sc.site_id = s.id
                    WHERE sc.container_id = ? AND s.username = ?
                ");
                $stmt->execute([$container_id, AUTH_USER]);
            }
            
            $container_info = $stmt->fetch();
            if (!$container_info) {
                $response['error'] = 'Access denied or container not found';
                break;
            }
            
            // Default to container owner if no user specified
            if (empty($user)) {
                $user = $container_info['username'];
            }
            
            // Create a unique session ID
            $session_id = bin2hex(random_bytes(16));
            
            // Store session info
            $_SESSION['terminal_sessions'][$session_id] = [
                'container_id' => $container_id,
                'user' => $user,
                'shell' => $shell,
                'created' => time()
            ];
            
            $response = [
                'success' => true,
                'session_id' => $session_id,
                'user' => $user,
                'shell' => $shell
            ];
            break;
            
        default:
            $response['error'] = 'Invalid action';
            break;
    }
} catch (Exception $e) {
    error_log("Terminal API error: " . $e->getMessage());
    $response = ['success' => false, 'error' => 'Internal server error'];
}

echo json_encode($response);