<?php
// Set content type to JSON
header('Content-Type: application/json');

// Check API permission
check_api_permission('docker-management');

require_once('/docker/whp/web/libs/docker-api.php');
require_once('/docker/whp/web/libs/db.php');

$DockerAPI = new docker_api();

// Get request method and action
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Handle different HTTP methods and actions
switch ($method) {
    case 'GET':
        switch ($action) {
            case 'containers':
                // List all containers
                $include_stopped = isset($_GET['include_stopped']) ? (bool)$_GET['include_stopped'] : false;
                $containers = $DockerAPI->list_containers($include_stopped);
                
                echo json_encode(array(
                    'status' => 'success',
                    'data' => $containers
                ));
                break;
                
            case 'container_types':
                // List all container types
                global $db;
                try {
                    $stmt = $db->query("SELECT * FROM container_types ORDER BY name ASC");
                    $container_types = $stmt->fetchAll();
                    
                    echo json_encode(array(
                        'status' => 'success',
                        'data' => $container_types
                    ));
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Database error: ' . $e->getMessage()
                    ));
                }
                break;
                
            case 'inspect':
                // Inspect a specific container
                if (empty($_GET['container_id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container ID is required'
                    ));
                    break;
                }
                
                $result = $DockerAPI->inspect_container($_GET['container_id']);
                if ($result['success']) {
                    echo json_encode(array(
                        'status' => 'success',
                        'data' => $result['data']
                    ));
                } else {
                    http_response_code(404);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['error']
                    ));
                }
                break;
                
            default:
                http_response_code(400);
                echo json_encode(array(
                    'status' => 'error',
                    'message' => 'Invalid action. Use containers, container_types, or inspect.'
                ));
                break;
        }
        break;
        
    case 'POST':
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            http_response_code(400);
            echo json_encode(array(
                'status' => 'error',
                'message' => 'Invalid JSON input'
            ));
            break;
        }
        
        switch ($action) {
            case 'restart':
                // Restart a container
                if (empty($input['container_id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container ID is required'
                    ));
                    break;
                }
                
                $result = $DockerAPI->restart_container($input['container_id']);
                if ($result['success']) {
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container restarted successfully',
                        'data' => array(
                            'container_id' => $input['container_id']
                        )
                    ));
                } else {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['error']
                    ));
                }
                break;
                
            case 'stop':
                // Stop a container
                if (empty($input['container_id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container ID is required'
                    ));
                    break;
                }
                
                $result = $DockerAPI->stop_container($input['container_id']);
                if ($result['success']) {
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container stopped successfully',
                        'data' => array(
                            'container_id' => $input['container_id']
                        )
                    ));
                } else {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['error']
                    ));
                }
                break;
                
            case 'remove':
                // Remove a container (only user containers)
                if (empty($input['container_id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container ID is required'
                    ));
                    break;
                }
                
                // Check if container is removable (not a system container)
                $container_info = $DockerAPI->inspect_container($input['container_id']);
                if (!$container_info['success']) {
                    http_response_code(404);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container not found'
                    ));
                    break;
                }
                
                $labels = $container_info['data']['Config']['Labels'] ?? [];
                if (!isset($labels['whp.user']) || $labels['whp.user'] === 'root' || $labels['whp.user'] === 'system') {
                    http_response_code(403);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Cannot remove system containers'
                    ));
                    break;
                }
                
                $result = $DockerAPI->remove_container($input['container_id']);
                if ($result['success']) {
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container removed successfully',
                        'data' => array(
                            'container_id' => $input['container_id']
                        )
                    ));
                } else {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => $result['error']
                    ));
                }
                break;
                
            case 'create_container_type':
                // Create a new container type
                if (empty($input['name']) || empty($input['base_image'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Name and base image are required'
                    ));
                    break;
                }
                
                global $db;
                try {
                    $stmt = $db->prepare("
                        INSERT INTO container_types (name, description, base_image, default_cpu, default_memory, active) 
                        VALUES (?, ?, ?, ?, ?, 1)
                    ");
                    $stmt->execute([
                        $input['name'],
                        $input['description'] ?? '',
                        $input['base_image'],
                        floatval($input['default_cpu'] ?? 0.25),
                        intval($input['default_memory'] ?? 256)
                    ]);
                    
                    $container_type_id = $db->lastInsertId();
                    
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container type created successfully',
                        'data' => array(
                            'id' => $container_type_id,
                            'name' => $input['name']
                        )
                    ));
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Database error: ' . $e->getMessage()
                    ));
                }
                break;
                
            case 'update_container_type':
                // Update a container type
                if (empty($input['id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container type ID is required'
                    ));
                    break;
                }
                
                global $db;
                try {
                    $updates = [];
                    $params = [];
                    
                    if (isset($input['name'])) {
                        $updates[] = "name = ?";
                        $params[] = $input['name'];
                    }
                    if (isset($input['description'])) {
                        $updates[] = "description = ?";
                        $params[] = $input['description'];
                    }
                    if (isset($input['base_image'])) {
                        $updates[] = "base_image = ?";
                        $params[] = $input['base_image'];
                    }
                    if (isset($input['default_cpu'])) {
                        $updates[] = "default_cpu = ?";
                        $params[] = floatval($input['default_cpu']);
                    }
                    if (isset($input['default_memory'])) {
                        $updates[] = "default_memory = ?";
                        $params[] = intval($input['default_memory']);
                    }
                    if (isset($input['active'])) {
                        $updates[] = "active = ?";
                        $params[] = (bool)$input['active'];
                    }
                    
                    if (empty($updates)) {
                        http_response_code(400);
                        echo json_encode(array(
                            'status' => 'error',
                            'message' => 'No fields to update'
                        ));
                        break;
                    }
                    
                    $params[] = $input['id'];
                    $sql = "UPDATE container_types SET " . implode(", ", $updates) . " WHERE id = ?";
                    $stmt = $db->prepare($sql);
                    $stmt->execute($params);
                    
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container type updated successfully',
                        'data' => array(
                            'id' => $input['id']
                        )
                    ));
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Database error: ' . $e->getMessage()
                    ));
                }
                break;
                
            case 'create_site_container':
                // Create a container for a user's site
                if (empty($input['domain']) || empty($input['user']) || empty($input['container_type_id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Domain, user, and container type are required'
                    ));
                    break;
                }
                
                // Get container type details
                global $db;
                try {
                    $stmt = $db->prepare("SELECT * FROM container_types WHERE id = ? AND active = 1");
                    $stmt->execute([$input['container_type_id']]);
                    $container_type = $stmt->fetch();
                    
                    if (!$container_type) {
                        http_response_code(400);
                        echo json_encode(array(
                            'status' => 'error',
                            'message' => 'Invalid or inactive container type'
                        ));
                        break;
                    }
                    
                    // Get user UID
                    $uid = trim(shell_exec("id -u " . escapeshellarg($input['user'])));
                    if (!is_numeric($uid)) {
                        http_response_code(400);
                        echo json_encode(array(
                            'status' => 'error',
                            'message' => 'Invalid user'
                        ));
                        break;
                    }
                    
                    // Create container with user settings
                    $container_config = [
                        'image' => $container_type['base_image'],
                        'name' => $input['user'] . '_' . str_replace('.', '_', $input['domain']),
                        'labels' => [
                            'whp.user' => $input['user'],
                            'whp.domain' => $input['domain'],
                            'whp.type' => $container_type['name']
                        ],
                        'env' => [
                            'WHP_USER=' . $input['user'],
                            'WHP_UID=' . $uid,
                            'WHP_DOMAIN=' . $input['domain'],
                            'PHP_VERSION=' . ($input['php_version'] ?? '8.2')
                        ],
                        'volumes' => [
                            // Document root is created within user's home directory
                            // User home: /docker/users/{user}/
                            // Site document root: /docker/users/{user}/{domain}/
                            '/docker/users/' . $input['user'] . '/' . $input['domain'] . ':/var/www/html'
                        ],
                        'cpu' => floatval($input['cpu_allocation'] ?? $container_type['default_cpu']),
                        'memory' => intval($input['memory_allocation'] ?? $container_type['default_memory']),
                        'network' => 'client-net'
                    ];
                    
                    $result = $DockerAPI->create_container($container_config);
                    if ($result['success']) {
                        echo json_encode(array(
                            'status' => 'success',
                            'message' => 'Site container created successfully',
                            'data' => array(
                                'container_id' => $result['container_id'],
                                'container_name' => $container_config['name'],
                                'domain' => $input['domain'],
                                'user' => $input['user']
                            )
                        ));
                    } else {
                        http_response_code(500);
                        echo json_encode(array(
                            'status' => 'error',
                            'message' => 'Failed to create container: ' . $result['error']
                        ));
                    }
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Database error: ' . $e->getMessage()
                    ));
                }
                break;
                
            default:
                http_response_code(400);
                echo json_encode(array(
                    'status' => 'error',
                    'message' => 'Invalid action. Use restart, stop, remove, create_container_type, update_container_type, or create_site_container.'
                ));
                break;
        }
        break;
        
    case 'DELETE':
        // Parse query string for DELETE requests
        parse_str(file_get_contents("php://input"), $input);
        
        switch ($action) {
            case 'container_type':
                // Delete a container type
                if (empty($input['id'])) {
                    http_response_code(400);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Container type ID is required'
                    ));
                    break;
                }
                
                global $db;
                try {
                    // Check if container type is in use
                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM domains WHERE container_type_id = ?");
                    $stmt->execute([$input['id']]);
                    $usage = $stmt->fetch();
                    
                    if ($usage['count'] > 0) {
                        http_response_code(400);
                        echo json_encode(array(
                            'status' => 'error',
                            'message' => 'Cannot delete container type that is in use'
                        ));
                        break;
                    }
                    
                    $stmt = $db->prepare("DELETE FROM container_types WHERE id = ?");
                    $stmt->execute([$input['id']]);
                    
                    echo json_encode(array(
                        'status' => 'success',
                        'message' => 'Container type deleted successfully'
                    ));
                } catch (PDOException $e) {
                    http_response_code(500);
                    echo json_encode(array(
                        'status' => 'error',
                        'message' => 'Database error: ' . $e->getMessage()
                    ));
                }
                break;
                
            default:
                http_response_code(400);
                echo json_encode(array(
                    'status' => 'error',
                    'message' => 'Invalid action for DELETE method'
                ));
                break;
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array(
            'status' => 'error',
            'message' => 'Method not allowed. Use GET, POST, or DELETE.'
        ));
        break;
}
?> 