<?php
// Start output buffering to control all output
ob_start();

// Permission checking is now handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/docker-api.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');
$DockerAPI = new docker_api();
$MySQLMgmt = new mysqlmgmt();

$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'restart_container':
                if (!empty($_POST['container_id'])) {
                    $result = $DockerAPI->restart_container($_POST['container_id']);
                    if ($result['success']) {
                        $message = 'Container restarted successfully: ' . $_POST['container_id'];
                        $message_type = 'success';
                    } else {
                        $message = 'Error restarting container: ' . $result['error'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'stop_container':
                if (!empty($_POST['container_id'])) {
                    $result = $DockerAPI->stop_container($_POST['container_id']);
                    if ($result['success']) {
                        $message = 'Container stopped successfully: ' . $_POST['container_id'];
                        $message_type = 'success';
                    } else {
                        $message = 'Error stopping container: ' . $result['error'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'remove_container':
                if (!empty($_POST['container_id'])) {
                    // Only allow removal of user containers, not system containers
                    $container_info = $DockerAPI->inspect_container($_POST['container_id']);
                    if ($container_info['success']) {
                        $labels = $container_info['data']['Config']['Labels'] ?? [];
                        if (isset($labels['whp.user']) && $labels['whp.user'] !== 'root') {
                            $result = $DockerAPI->remove_container($_POST['container_id']);
                            if ($result['success']) {
                                $message = 'Container removed successfully: ' . $_POST['container_id'];
                                $message_type = 'success';
                            } else {
                                $message = 'Error removing container: ' . $result['error'];
                                $message_type = 'danger';
                            }
                        } else {
                            $message = 'Cannot remove system containers';
                            $message_type = 'danger';
                        }
                    } else {
                        $message = 'Container not found';
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'create_container_type':
                if (!empty($_POST['name']) && !empty($_POST['base_image'])) {
                    // Prepare environment variables JSON
                    $startup_env = [];
                    if (!empty($_POST['env_vars_json'])) {
                        $env_vars_raw = trim($_POST['env_vars_json']);
                        if (!empty($env_vars_raw)) {
                            $decoded = json_decode($env_vars_raw, true);
                            if (json_last_error() === JSON_ERROR_NONE) {
                                $startup_env = $decoded;
                            }
                        }
                    }
                    
                    // Prepare user variables JSON
                    $user_variables = [];
                    if (!empty($_POST['user_vars_json'])) {
                        $user_vars_raw = trim($_POST['user_vars_json']);
                        if (!empty($user_vars_raw)) {
                            $decoded = json_decode($user_vars_raw, true);
                            if (json_last_error() === JSON_ERROR_NONE) {
                                $user_variables = $decoded;
                            }
                        }
                    }
                    
                    // Prepare mount options JSON
                    $mount_options = [];
                    if (!empty($_POST['mount_options_json'])) {
                        // Parse mount options from textarea (JSON format)
                        $mount_options_raw = trim($_POST['mount_options_json']);
                        if (!empty($mount_options_raw)) {
                            $decoded = json_decode($mount_options_raw, true);
                            if (json_last_error() === JSON_ERROR_NONE) {
                                $mount_options = $decoded;
                            }
                        }
                    }
                    
                    $result = $MySQLMgmt->createContainerType(
                        $_POST['name'],
                        $_POST['description'] ?? '',
                        $_POST['base_image'],
                        floatval($_POST['min_cpu'] ?? 0.25),
                        intval($_POST['min_memory'] ?? 256),
                        $startup_env,
                        $user_variables,
                        $mount_options,
                        intval($_POST['listen_port'] ?? 80),
                        isset($_POST['listen_port_tls']) ? 1 : 0
                    );
                    
                    if ($result['status'] === '0') {
                        // Automatically pull the Docker image after creating the container type
                        $pull_result = $DockerAPI->pull_image($_POST['base_image']);
                        if ($pull_result['success']) {
                            $message = 'Container type created successfully and image pulled: ' . $_POST['name'];
                            $message_type = 'success';
                        } else {
                            $message = 'Container type created successfully, but failed to pull image: ' . $pull_result['error'];
                            $message_type = 'warning';
                        }
                    } else {
                        $message = 'Error creating container type: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                

                

                

        }
    }
}

// Get all containers
$containers = $DockerAPI->list_containers(true); // Include stopped containers

// Get container types with usage count
$container_types_result = $MySQLMgmt->listContainerTypes();
if ($container_types_result['status'] === '0') {
    $container_types = $container_types_result['container_types'];
} else {
    $container_types = [];
}

// Get available dynamic variables
$dynamic_vars_result = $MySQLMgmt->getDynamicVariables();
if ($dynamic_vars_result['status'] === '0') {
    $dynamic_variables = $dynamic_vars_result['variables'];
} else {
    $dynamic_variables = [];
}

// Get site and container type information for containers
$site_info = [];
$container_type_info = [];
try {
    $db = $MySQLMgmt->getMySQLConnection();
    if ($db) {
        // Get site information
        $stmt = $db->query("SELECT s.id, s.site_name, s.container_type_id, d.domain_name FROM whp.sites s JOIN whp.domains d ON s.primary_domain_id = d.id");
        $sites = $stmt->fetchAll();
        foreach ($sites as $site) {
            $site_info[$site['id']] = [
                'site_name' => $site['site_name'],
                'domain' => $site['domain_name'],
                'container_type_id' => $site['container_type_id']
            ];
        }
        
        // Get container type information
        $stmt = $db->query("SELECT id, name, listen_port FROM whp.container_types");
        $types = $stmt->fetchAll();
        foreach ($types as $type) {
            $container_type_info[$type['id']] = [
                'name' => $type['name'],
                'listen_port' => $type['listen_port'] ?? 80
            ];
        }
    }
} catch (PDOException $e) {
    // Ignore database errors for container metadata
}
?>

<div class="row">
    <div class="col-md-12">
        <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <i class="fa fa-<?php echo $message_type === 'success' ? 'check' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Container Management -->
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Running Containers</h5>
            </div>
            <div class="card-body">
                <?php if (empty($containers)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No containers found</strong> - No containers are currently running on this server.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Container ID</th>
                                <th>Name</th>
                                <th>Container Type</th>
                                <th>Site</th>
                                <th>Status</th>
                                <th>User</th>
                                <th>Created</th>
                                <th>Ports</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($containers as $container): ?>
                            <?php 
                            $container_id = substr($container['Id'], 0, 12);
                            $labels = $container['Labels'] ?? [];
                            $user = $labels['whp.user'] ?? 'system';
                            $is_removable = ($user !== 'root' && $user !== 'system');
                            
                            // Get site and container type information
                            $site_id = $labels['whp.site_id'] ?? null;
                            $domain = $labels['whp.domain'] ?? null;
                            $container_type = 'Unknown';
                            $site_display = 'N/A';
                            
                            if ($site_id && isset($site_info[$site_id])) {
                                $site_data = $site_info[$site_id];
                                $site_display = $site_data['site_name'] . ' (' . $site_data['domain'] . ')';
                                if (isset($container_type_info[$site_data['container_type_id']])) {
                                    $container_type = $container_type_info[$site_data['container_type_id']]['name'];
                                }
                            } elseif ($domain) {
                                $site_display = $domain . ' (legacy)';
                                // Try to determine container type from image name
                                $image = $container['Image'];
                                if (strpos($image, 'apache') !== false || strpos($image, 'php') !== false) {
                                    $container_type = 'Apache/PHP';
                                } elseif (strpos($image, 'nginx') !== false) {
                                    $container_type = 'Nginx';
                                } elseif (strpos($image, 'node') !== false) {
                                    $container_type = 'Node.js';
                                } elseif (strpos($image, 'python') !== false) {
                                    $container_type = 'Python';
                                } else {
                                    $container_type = 'Custom';
                                }
                            } elseif ($user === 'system' || $user === 'root') {
                                $site_display = 'System';
                                $container_type = 'System';
                            }
                            ?>
                            <tr>
                                <td><code><?php echo htmlspecialchars($container_id); ?></code></td>
                                <td><?php echo htmlspecialchars($container['Names'][0] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($container_type); ?></td>
                                <td style="max-width: 200px;">
                                    <div style="font-size: 0.9em; word-wrap: break-word; overflow-wrap: break-word;">
                                        <?php echo htmlspecialchars($site_display); ?>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge <?php echo $container['State'] === 'running' ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo ucfirst($container['State']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($user); ?></td>
                                <td><?php echo date('Y-m-d H:i', $container['Created']); ?></td>
                                <td style="min-width: 80px;">
                                    <?php if (!empty($container['Ports'])): ?>
                                        <?php foreach ($container['Ports'] as $port): ?>
                                            <div class="text-muted" style="font-size: 0.85em; line-height: 1.2;">
                                                <?php if (isset($port['PublicPort']) && isset($port['PrivatePort'])): ?>
                                                    <?php echo $port['PublicPort']; ?>:<?php echo $port['PrivatePort']; ?>
                                                    <?php if (isset($port['Type'])): ?>
                                                        <small>/<?php echo $port['Type']; ?></small>
                                                    <?php endif; ?>
                                                <?php elseif (isset($port['PrivatePort'])): ?>
                                                    <?php echo $port['PrivatePort']; ?>
                                                    <?php if (isset($port['Type'])): ?>
                                                        <small>/<?php echo $port['Type']; ?></small>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <?php 
                                        // Fallback to container type port if available
                                        $fallback_port = null;
                                        if ($site_id && isset($site_info[$site_id])) {
                                            $site_data = $site_info[$site_id];
                                            if (isset($container_type_info[$site_data['container_type_id']])) {
                                                $fallback_port = $container_type_info[$site_data['container_type_id']]['listen_port'];
                                            }
                                        }
                                        ?>
                                        <?php if ($fallback_port): ?>
                                            <div class="text-muted" style="font-size: 0.85em; line-height: 1.2;">
                                                <?php echo $fallback_port; ?> <small class="text-info">(from type)</small>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted" style="font-size: 0.85em;">None</span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <?php if ($container['State'] === 'running'): ?>
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="action" value="restart_container">
                                            <input type="hidden" name="container_id" value="<?php echo htmlspecialchars($container['Id']); ?>">
                                            <button type="submit" class="btn btn-warning btn-sm" title="Restart">
                                                <i class="fa fa-refresh"></i>
                                            </button>
                                        </form>
                                        <form method="post" style="display: inline;">
                                            <input type="hidden" name="action" value="stop_container">
                                            <input type="hidden" name="container_id" value="<?php echo htmlspecialchars($container['Id']); ?>">
                                            <button type="submit" class="btn btn-secondary btn-sm" title="Stop">
                                                <i class="fa fa-stop"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                        <?php if ($site_id && $is_removable): ?>
                                        <button type="button" class="btn btn-info btn-sm recreate-container-btn" 
                                                data-site-id="<?php echo htmlspecialchars($site_id); ?>" 
                                                data-container-id="<?php echo htmlspecialchars($container['Id']); ?>"
                                                title="Recreate with latest image"
                                                style="font-size: 0.75rem; white-space: nowrap;">
                                            Recreate
                                        </button>
                                        <?php endif; ?>
                                        <?php if ($is_removable): ?>
                                        <form method="post" style="display: inline;" onsubmit="return confirm('Are you sure you want to remove this container? This action cannot be undone.');">
                                            <input type="hidden" name="action" value="remove_container">
                                            <input type="hidden" name="container_id" value="<?php echo htmlspecialchars($container['Id']); ?>">
                                            <button type="submit" class="btn btn-danger btn-sm" title="Remove">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Container Types Management -->
<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Container Types</h5>
            </div>
            <div class="card-body">
                <?php if (empty($container_types)): ?>
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>No container types defined</strong> - Create container types to allow users to deploy sites.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Base Image</th>
                                <th>Min CPU</th>
                                <th>Min Memory</th>
                                <th>HAProxy Port</th>
                                <th>Usage</th>
                                <th>Last Pull</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($container_types as $type): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($type['name']); ?></strong>
                                    <?php if (!empty($type['user_variables'])): ?>
                                    <br><small class="text-muted"><i class="fa fa-cog"></i> Configurable</small>
                                    <?php endif; ?>
                                </td>
                                <td style="max-width: 200px;">
                                    <div style="font-size: 0.9em; word-wrap: break-word; overflow-wrap: break-word;">
                                        <?php echo htmlspecialchars($type['description']); ?>
                                    </div>
                                    <?php if (!empty($type['startup_env'])): ?>
                                    <br><small class="text-muted">
                                        <i class="fa fa-list"></i> 
                                        <?php echo count(json_decode($type['startup_env'], true) ?: []); ?> env vars
                                    </small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <code><?php echo htmlspecialchars($type['base_image']); ?></code>
                                    <br>
                                    <button type="button" class="btn btn-xs btn-outline-primary pull-image-btn" 
                                            data-image-name="<?php echo htmlspecialchars($type['base_image']); ?>" title="Pull Latest Image">
                                        <i class="fa fa-download"></i> Pull
                                    </button>
                                </td>
                                <td><?php echo $type['min_cpu']; ?> cores</td>
                                <td><?php echo $type['min_memory']; ?> MB</td>
                                <td>
                                    <code><?php echo htmlspecialchars($type['listen_port'] ?? 80); ?></code>
                                </td>
                                <td>
                                    <?php if ($type['usage_count'] > 0): ?>
                                        <span class="badge bg-info"><?php echo $type['usage_count']; ?> in use</span>
                                    <?php else: ?>
                                        <span class="text-muted">None</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small class="text-muted"><?php echo $type['last_pull_formatted']; ?></small>
                                </td>
                                <td>
                                    <span class="badge <?php echo $type['active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo $type['active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group-vertical btn-group-sm">
                                        <button type="button" class="btn btn-sm <?php echo $type['active'] ? 'btn-secondary' : 'btn-success'; ?> toggle-type-btn" 
                                                data-type-id="<?php echo $type['id']; ?>" data-current-status="<?php echo $type['active'] ? '1' : '0'; ?>">
                                            <?php echo $type['active'] ? 'Disable' : 'Enable'; ?>
                                        </button>
                                        
                                        <?php if ($type['usage_count'] == 0): ?>
                                        <button type="button" class="btn btn-sm btn-danger remove-type-btn" 
                                                data-type-id="<?php echo $type['id']; ?>" data-type-name="<?php echo htmlspecialchars($type['name']); ?>">
                                            <i class="fa fa-trash"></i> Remove
                                        </button>
                                        <?php else: ?>
                                        <button class="btn btn-sm btn-secondary" disabled title="Cannot remove - in use">
                                            <i class="fa fa-trash"></i> Remove
                                        </button>
                                        <?php endif; ?>
                                        
                                        <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#detailsModal<?php echo $type['id']; ?>">
                                            <i class="fa fa-info-circle"></i> Details
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Dynamic Variables Reference -->
<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fa fa-list-alt"></i> Available Dynamic Variables</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-light border">
                    <h6 class="mb-3"><strong>Use these variables in your environment variables and mount options:</strong></h6>
                    <div class="row">
                        <?php 
                        $vars_by_category = [];
                        foreach ($dynamic_variables as $var) {
                            $vars_by_category[$var['category']][] = $var;
                        }
                        foreach ($vars_by_category as $category => $vars): 
                        ?>
                        <div class="col-md-3 mb-3">
                            <h6 class="text-primary mb-2"><i class="fa fa-tag"></i> <?php echo ucfirst($category); ?></h6>
                            <?php foreach ($vars as $var): ?>
                            <div class="mb-1">
                                <code class="bg-light text-dark px-2 py-1 rounded d-inline-block" 
                                      title="<?php echo htmlspecialchars($var['description']); ?> (Example: <?php echo htmlspecialchars($var['example_value']); ?>)">
                                    <?php echo htmlspecialchars($var['variable_name']); ?>
                                </code>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Container Type Form -->
<div class="row mt-4">
    <div class="col-md-8 mx-auto">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Add Enhanced Container Type</h5>
            </div>
            <div class="card-body">
                <form method="post" id="containerTypeForm">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="action" value="create_container_type">
                    
                    <!-- Basic Information -->
                    <h6 class="fw-bold mb-3">Basic Information</h6>
                    
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Display name for this container type</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="2"></textarea>
                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Brief description of this container type</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="base_image" class="form-label">Base Image</label>
                        <input type="text" class="form-control" id="base_image" name="base_image" required 
                               placeholder="whp/apache-php:8.2">
                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Docker image to use for this container type</div>
                    </div>
                    
                    <!-- Resource Requirements -->
                    <h6 class="fw-bold mb-3 mt-4">Resource Requirements</h6>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="min_cpu" class="form-label">Min CPU (cores)</label>
                                <input type="number" class="form-control" id="min_cpu" name="min_cpu" 
                                       step="0.25" min="0.25" max="8" value="0.25">
                                <div class="form-text text-light bg-dark px-2 py-1 rounded">Minimum required</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="min_memory" class="form-label">Min Memory (MB)</label>
                                <input type="number" class="form-control" id="min_memory" name="min_memory" 
                                       min="128" max="8192" value="256">
                                <div class="form-text text-light bg-dark px-2 py-1 rounded">Minimum required</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="listen_port" class="form-label">HAProxy Listen Port</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="listen_port" name="listen_port" 
                                           min="1" max="65535" value="80">
                                    <div class="input-group-text">
                                        <input type="checkbox" id="listen_port_tls" name="listen_port_tls" value="1">
                                        <label for="listen_port_tls" class="ms-2 mb-0">TLS/SSL</label>
                                    </div>
                                </div>
                                <div class="form-text text-light bg-dark px-2 py-1 rounded">Port HAProxy connects to. Check TLS/SSL if this port uses HTTPS.</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Environment Variables -->
                    <h6 class="fw-bold mb-3 mt-4">Startup Environment Variables</h6>
                    <div class="mb-3">
                        <div class="form-text text-light bg-dark px-2 py-1 rounded mb-3">
                            <strong>Environment Variables:</strong> Define variables that will be set when the container starts. Use dynamic variables like \${WHP_USER}, \${WHP_DOMAIN}, etc.
                        </div>
                        <div id="env-vars-builder">
                            <!-- Environment variables will be added here dynamically -->
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="add-env-var">
                            <i class="fa fa-plus"></i> Add Environment Variable
                        </button>
                        <textarea class="form-control d-none" id="env_vars_json" name="env_vars_json" rows="4"></textarea>
                    </div>
                    
                    <!-- User Configurable Variables -->
                    <h6 class="fw-bold mb-3 mt-4">User Configurable Variables</h6>
                    <div class="mb-3">
                        <div class="form-text text-light bg-dark px-2 py-1 rounded mb-3">
                            <strong>User Variables:</strong> Define variables that users can configure when creating containers. Types: text, number, select, checkbox, textarea
                        </div>
                        <div id="user-vars-builder">
                            <!-- User variables will be added here dynamically -->
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="add-user-var">
                            <i class="fa fa-plus"></i> Add User Variable
                        </button>
                        <textarea class="form-control d-none" id="user_vars_json" name="user_vars_json" rows="4"></textarea>
                    </div>
                    
                    <!-- Mount Options -->
                    <h6 class="fw-bold mb-3 mt-4">Mount Options &amp; Volumes</h6>
                    <div class="mb-3">
                        <div class="form-text text-light bg-dark px-2 py-1 rounded mb-3">
                            <strong>Mount Options:</strong> Define volume mounts, tmpfs mounts, and additional Docker options. Use dynamic variables like \${WHP_HOME} for paths.
                        </div>
                        
                        <!-- Volume Mounts -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="mb-0">Volume Mounts</h6>
                            </div>
                            <div class="card-body">
                                <div id="volume-mounts-builder">
                                    <!-- Volume mounts will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="add-volume-mount">
                                    <i class="fa fa-plus"></i> Add Volume Mount
                                </button>
                            </div>
                        </div>
                        
                        <!-- Tmpfs Mounts -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="mb-0">Tmpfs Mounts</h6>
                            </div>
                            <div class="card-body">
                                <div id="tmpfs-mounts-builder">
                                    <!-- Tmpfs mounts will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="add-tmpfs-mount">
                                    <i class="fa fa-plus"></i> Add Tmpfs Mount
                                </button>
                            </div>
                        </div>
                        
                        <!-- Docker Options -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="mb-0">Docker Options</h6>
                            </div>
                            <div class="card-body">
                                <div id="docker-options-builder">
                                    <!-- Docker options will be added here dynamically -->
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="add-docker-option">
                                    <i class="fa fa-plus"></i> Add Docker Option
                                </button>
                            </div>
                        </div>
                        
                        <textarea class="form-control d-none" id="mount_options_json" name="mount_options_json" rows="6"></textarea>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary" id="createTypeBtn">
                            <i class="fa fa-plus"></i> Create Enhanced Container Type
                        </button>
                    </div>
                    
                    <div id="formMessages" class="mt-3"></div>
                </form>
            </div>
        </div>

    </div>
</div>

<!-- Container Type Details Modals -->
<?php foreach ($container_types as $type): ?>
<div class="modal fade" id="detailsModal<?php echo $type['id']; ?>" tabindex="-1">
    <div class="modal-dialog modal-fullscreen-lg-down modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Container Type Details: <?php echo htmlspecialchars($type['name']); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-4">
                    <!-- Basic Information -->
                    <div class="col-lg-4 col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="fa fa-info-circle"></i> Basic Information</h6>
                            </div>
                            <div class="card-body">
                                <dl class="row mb-0">
                                    <dt class="col-sm-4">Name:</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($type['name']); ?></dd>
                                    
                                    <dt class="col-sm-4">Description:</dt>
                                    <dd class="col-sm-8"><?php echo htmlspecialchars($type['description']); ?></dd>
                                    
                                    <dt class="col-sm-4">Base Image:</dt>
                                    <dd class="col-sm-8"><code class="text-primary"><?php echo htmlspecialchars($type['base_image']); ?></code></dd>
                                    
                                    <dt class="col-sm-4">Status:</dt>
                                    <dd class="col-sm-8"><span class="badge <?php echo $type['active'] ? 'bg-success' : 'bg-secondary'; ?>"><?php echo $type['active'] ? 'Active' : 'Inactive'; ?></span></dd>
                                    
                                    <dt class="col-sm-4">Usage:</dt>
                                    <dd class="col-sm-8"><span class="badge bg-info"><?php echo $type['usage_count']; ?> in use</span></dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Resource Requirements -->
                    <div class="col-lg-4 col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-secondary text-white">
                                <h6 class="mb-0"><i class="fa fa-cogs"></i> Resource Requirements</h6>
                            </div>
                            <div class="card-body">
                                <dl class="row mb-0">
                                    <dt class="col-sm-6">Min CPU:</dt>
                                    <dd class="col-sm-6"><?php echo $type['min_cpu']; ?> cores</dd>
                                    
                                    <dt class="col-sm-6">Min Memory:</dt>
                                    <dd class="col-sm-6"><?php echo $type['min_memory']; ?> MB</dd>
                                    
                                    <dt class="col-sm-6">HAProxy Port:</dt>
                                    <dd class="col-sm-6"><code class="text-primary"><?php echo htmlspecialchars($type['listen_port'] ?? 80); ?></code></dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Environment Variables -->
                    <div class="col-lg-4 col-md-6">
                        <div class="card h-100">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0"><i class="fa fa-list"></i> Environment Variables</h6>
                            </div>
                            <div class="card-body">
                                <?php 
                                $env_vars = json_decode($type['startup_env'], true) ?: [];
                                if (!empty($env_vars)): 
                                ?>
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped">
                                        <thead class="table-light">
                                            <tr><th>Variable</th><th>Value</th></tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($env_vars as $key => $value): ?>
                                            <tr>
                                                <td><code class="text-primary"><?php echo htmlspecialchars($key); ?></code></td>
                                                <td><code class="text-secondary"><?php echo htmlspecialchars($value); ?></code></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fa fa-info-circle fa-2x mb-2"></i>
                                    <p class="mb-0"><em>No environment variables defined</em></p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Second Row for User Variables and Mount Options -->
                <div class="row g-4 mt-2">
                    <!-- User Variables -->
                    <div class="col-lg-6 col-md-12">
                        <div class="card h-100">
                            <div class="card-header bg-warning text-dark">
                                <h6 class="mb-0"><i class="fa fa-user-cog"></i> User Configurable Variables</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($type['user_variables'])): ?>
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped">
                                        <thead class="table-light">
                                            <tr><th>Variable</th><th>Type</th><th>Required</th></tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $user_vars = json_decode($type['user_variables'], true) ?: [];
                                            foreach ($user_vars as $key => $config): 
                                            ?>
                                            <tr>
                                                <td><strong><?php echo htmlspecialchars($config['label'] ?? $key); ?></strong></td>
                                                <td><span class="badge bg-secondary"><?php echo htmlspecialchars($config['type']); ?></span></td>
                                                <td><?php echo !empty($config['required']) ? '<span class="badge bg-danger">Yes</span>' : '<span class="badge bg-success">No</span>'; ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fa fa-info-circle fa-2x mb-2"></i>
                                    <p class="mb-0"><em>No user variables defined</em></p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Mount Options -->
                    <div class="col-lg-6 col-md-12">
                        <div class="card h-100">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="fa fa-hdd"></i> Mount Options</h6>
                            </div>
                            <div class="card-body">
                                <?php 
                                $mount_opts = json_decode($type['mount_options'], true) ?: [];
                                $has_mounts = false;
                                ?>
                                
                                <?php if (!empty($mount_opts['volumes'])): ?>
                                <div class="mb-3">
                                    <h6 class="text-primary mb-2"><i class="fa fa-folder"></i> Volumes:</h6>
                                    <div class="list-group list-group-flush">
                                        <?php foreach ($mount_opts['volumes'] as $volume): ?>
                                        <div class="list-group-item py-2">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <code class="text-primary"><?php echo htmlspecialchars($volume['source']); ?></code> 
                                                    <i class="fa fa-arrow-right text-muted mx-2"></i> 
                                                    <code class="text-secondary"><?php echo htmlspecialchars($volume['target']); ?></code>
                                                </div>
                                                <span class="badge bg-light text-dark"><?php echo htmlspecialchars($volume['type']); ?></span>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php $has_mounts = true; endif; ?>
                                
                                <?php if (!empty($mount_opts['tmpfs'])): ?>
                                <div class="mb-3">
                                    <h6 class="text-primary mb-2"><i class="fa fa-bolt"></i> Tmpfs:</h6>
                                    <div class="list-group list-group-flush">
                                        <?php foreach ($mount_opts['tmpfs'] as $tmpfs): ?>
                                        <div class="list-group-item py-2">
                                            <code class="text-secondary"><?php echo htmlspecialchars($tmpfs); ?></code>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php $has_mounts = true; endif; ?>
                                
                                <?php if (!empty($mount_opts['options'])): ?>
                                <div class="mb-3">
                                    <h6 class="text-primary mb-2"><i class="fa fa-cog"></i> Options:</h6>
                                    <div class="list-group list-group-flush">
                                        <?php foreach ($mount_opts['options'] as $option): ?>
                                        <div class="list-group-item py-2">
                                            <code class="text-secondary"><?php echo htmlspecialchars($option); ?></code>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php $has_mounts = true; endif; ?>
                                
                                <?php if (!$has_mounts): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fa fa-info-circle fa-2x mb-2"></i>
                                    <p class="mb-0"><em>No mount options defined</em></p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary edit-container-type-btn" data-type-id="<?php echo $type['id']; ?>">
                    <i class="fa fa-edit"></i> Edit Container Type
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>

<!-- Edit Container Type Modal -->
<div class="modal fade" id="editContainerTypeModal" tabindex="-1">
    <div class="modal-dialog modal-fullscreen-lg-down modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Container Type</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editContainerTypeForm" method="post">
                    <input type="hidden" id="edit_type_id" name="type_id">
                    <input type="hidden" id="edit_env_vars_json" name="env_vars_json" value="{}">
                    <input type="hidden" id="edit_user_vars_json" name="user_vars_json" value="{}">
                    <input type="hidden" id="edit_mount_options_json" name="mount_options_json" value="{}">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">Basic Information</h6>
                            
                            <div class="mb-3">
                                <label for="edit_name" class="form-label">Name *</label>
                                <input type="text" class="form-control" id="edit_name" name="name" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="edit_description" class="form-label">Description</label>
                                <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="edit_base_image" class="form-label">Base Image *</label>
                                <input type="text" class="form-control" id="edit_base_image" name="base_image" required>
                                <div class="form-text">Docker image name (e.g., nginx:latest)</div>
                            </div>
                            
                            <!-- Resource Requirements -->
                            <h6 class="fw-bold mb-3 mt-4">Resource Requirements</h6>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="edit_min_cpu" class="form-label">Min CPU (cores)</label>
                                        <input type="number" class="form-control" id="edit_min_cpu" name="min_cpu" 
                                               step="0.25" min="0.25" max="8" value="0.25">
                                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Minimum required</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="edit_min_memory" class="form-label">Min Memory (MB)</label>
                                        <input type="number" class="form-control" id="edit_min_memory" name="min_memory" 
                                               min="128" max="8192" value="256">
                                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Minimum required</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="edit_listen_port" class="form-label">HAProxy Port</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="edit_listen_port" name="listen_port" 
                                                   min="1" max="65535" value="80">
                                            <div class="input-group-text">
                                                <input type="checkbox" id="edit_listen_port_tls" name="listen_port_tls" value="1">
                                                <label for="edit_listen_port_tls" class="ms-2 mb-0">TLS/SSL</label>
                                            </div>
                                        </div>
                                        <div class="form-text text-light bg-dark px-2 py-1 rounded">Port HAProxy connects to. Check TLS/SSL if this port uses HTTPS.</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">Configuration</h6>
                            
                            <!-- Environment Variables -->
                            <div class="mb-3">
                                <label class="form-label">Environment Variables</label>
                                <div id="edit-env-vars-builder"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="edit-add-env-var">
                                    <i class="fa fa-plus"></i> Add Variable
                                </button>
                            </div>
                            
                            <!-- User Variables -->
                            <div class="mb-3">
                                <label class="form-label">User Configurable Variables</label>
                                <div id="edit-user-vars-builder"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="edit-add-user-var">
                                    <i class="fa fa-plus"></i> Add Variable
                                </button>
                            </div>
                            
                            <!-- Mount Options -->
                            <div class="mb-3">
                                <label class="form-label">Volume Mounts</label>
                                <div id="edit-volume-mounts-builder"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="edit-add-volume-mount">
                                    <i class="fa fa-plus"></i> Add Volume
                                </button>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Tmpfs Mounts</label>
                                <div id="edit-tmpfs-mounts-builder"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="edit-add-tmpfs-mount">
                                    <i class="fa fa-plus"></i> Add Tmpfs
                                </button>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Docker Options</label>
                                <div id="edit-docker-options-builder"></div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="edit-add-docker-option">
                                    <i class="fa fa-plus"></i> Add Option
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="editTypeBtn">
                    <i class="fa fa-save"></i> Update Container Type
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<style>
/* Modal layout fixes */
.modal-xl {
    max-width: 90%;
}

.modal-body {
    max-height: 70vh;
    overflow-y: auto;
}

.modal-footer {
    position: sticky;
    bottom: 0;
    background: var(--bs-modal-bg);
    border-top: 1px solid var(--bs-modal-header-border-color);
    z-index: 1050;
}

/* Ensure form elements don't overflow */
.form-control-sm {
    font-size: 0.875rem;
}

/* Card layout improvements */
.card-body {
    padding: 1rem;
}

/* Button spacing */
.btn-group-vertical .btn {
    margin-bottom: 0.25rem;
}

.btn-group-vertical .btn:last-child {
    margin-bottom: 0;
}
</style>

<script>
// Define CSRF token for AJAX requests
const nonce = '<?php echo get_csrf_token(); ?>';

// Enhanced Container Type management with validation and AJAX
document.addEventListener('DOMContentLoaded', function() {
    
    // Form builder helpers
    let envVarCounter = 0;
    let userVarCounter = 0;
    let volumeCounter = 0;
    let tmpfsCounter = 0;
    let optionCounter = 0;
    
    // Environment Variables Builder
    function addEnvVar(name = '', value = '') {
        const envVarsBuilder = document.getElementById('env-vars-builder');
        const varId = 'env-var-' + (++envVarCounter);
        
        const varHtml = `
            <div class="row mb-2" id="${varId}">
                <div class="col-md-5">
                    <input type="text" class="form-control form-control-sm" placeholder="Variable name" value="${name}">
                </div>
                                 <div class="col-md-6">
                     <input type="text" class="form-control form-control-sm" placeholder="Variable value (use \${WHP_USER}, etc.)" value="${value}">
                 </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${varId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        envVarsBuilder.insertAdjacentHTML('beforeend', varHtml);
        updateEnvVarsJSON();
    }
    
    function updateEnvVarsJSON() {
        const envVarsBuilder = document.getElementById('env-vars-builder');
        const envVars = {};
        
        envVarsBuilder.querySelectorAll('.row').forEach((row, index) => {
            const inputs = row.querySelectorAll('input[type="text"]');
            
            if (inputs.length >= 2) {
                const nameInput = inputs[0];
                const valueInput = inputs[1];
                
                if (nameInput.value.trim() && valueInput.value.trim()) {
                    envVars[nameInput.value.trim()] = valueInput.value.trim();
                }
            }
        });
        
        document.getElementById('env_vars_json').value = JSON.stringify(envVars);
    }
    
    // User Variables Builder
    function addUserVar(name = '', config = {}) {
        const userVarsBuilder = document.getElementById('user-vars-builder');
        const varId = 'user-var-' + (++userVarCounter);
        
        const varHtml = `
            <div class="card mb-2" id="${varId}">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-md-3">
                            <input type="text" class="form-control form-control-sm" placeholder="Variable name" value="${name}">
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control form-control-sm" placeholder="Display label" value="${config.label || ''}">
                        </div>
                        <div class="col-md-2">
                            <select class="form-control form-control-sm var-type-select">
                                <option value="text" ${config.type === 'text' ? 'selected' : ''}>Text</option>
                                <option value="number" ${config.type === 'number' ? 'selected' : ''}>Number</option>
                                <option value="select" ${config.type === 'select' ? 'selected' : ''}>Select</option>
                                <option value="checkbox" ${config.type === 'checkbox' ? 'selected' : ''}>Checkbox</option>
                                <option value="textarea" ${config.type === 'textarea' ? 'selected' : ''}>Textarea</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control form-control-sm" placeholder="Default value" value="${config.default || ''}">
                        </div>
                        <div class="col-md-1">
                            <label class="form-check-label">
                                <input type="checkbox" class="form-check-input" ${config.required ? 'checked' : ''}> Required
                            </label>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${varId}')">
                                <i class="fa fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="row mt-2 select-options" style="display: ${config.type === 'select' ? 'block' : 'none'};">
                        <div class="col-md-12">
                            <input type="text" class="form-control form-control-sm" placeholder="Options (comma-separated)" value="${config.options ? config.options.join(', ') : ''}">
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        userVarsBuilder.insertAdjacentHTML('beforeend', varHtml);
        
        // Add event listener for type change
        const lastCard = userVarsBuilder.lastElementChild;
        const typeSelect = lastCard.querySelector('.var-type-select');
        const optionsRow = lastCard.querySelector('.select-options');
        
        typeSelect.addEventListener('change', function() {
            optionsRow.style.display = this.value === 'select' ? 'block' : 'none';
            updateUserVarsJSON();
        });
        
        updateUserVarsJSON();
    }
    
    function updateUserVarsJSON() {
        const userVarsBuilder = document.getElementById('user-vars-builder');
        const userVars = {};
        
        userVarsBuilder.querySelectorAll('.card').forEach(card => {
            const nameInput = card.querySelector('input:first-child');
            const labelInput = card.querySelector('input:nth-child(2)');
            const typeSelect = card.querySelector('.var-type-select');
            const defaultInput = card.querySelector('input:nth-child(4)');
            const requiredInput = card.querySelector('input[type="checkbox"]');
            const optionsInput = card.querySelector('.select-options input');
            
            if (nameInput && nameInput.value.trim() && typeSelect) {
                const config = {
                    type: typeSelect.value,
                    label: labelInput ? (labelInput.value.trim() || nameInput.value.trim()) : nameInput.value.trim(),
                    required: requiredInput ? requiredInput.checked : false
                };
                
                if (defaultInput && defaultInput.value.trim()) {
                    config.default = defaultInput.value.trim();
                }
                
                if (typeSelect.value === 'select' && optionsInput && optionsInput.value.trim()) {
                    config.options = optionsInput.value.split(',').map(opt => opt.trim()).filter(opt => opt);
                }
                
                userVars[nameInput.value.trim()] = config;
            }
        });
        
        document.getElementById('user_vars_json').value = JSON.stringify(userVars);
    }
    
    // Volume Mounts Builder
    function addVolumeMount(source = '', target = '', type = 'bind') {
        const volumeBuilder = document.getElementById('volume-mounts-builder');
        const volId = 'volume-' + (++volumeCounter);
        
        const volHtml = `
            <div class="row mb-2" id="${volId}">
                                 <div class="col-md-4">
                     <input type="text" class="form-control form-control-sm" placeholder="Source path (use \${WHP_HOME}, etc.)" value="${source}">
                 </div>
                <div class="col-md-4">
                    <input type="text" class="form-control form-control-sm" placeholder="Container path" value="${target}">
                </div>
                <div class="col-md-3">
                    <select class="form-control form-control-sm">
                        <option value="bind" ${type === 'bind' ? 'selected' : ''}>Bind</option>
                        <option value="volume" ${type === 'volume' ? 'selected' : ''}>Volume</option>
                    </select>
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${volId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        volumeBuilder.insertAdjacentHTML('beforeend', volHtml);
        updateMountOptionsJSON();
    }
    
    // Tmpfs Mounts Builder
    function addTmpfsMount(path = '') {
        const tmpfsBuilder = document.getElementById('tmpfs-mounts-builder');
        const tmpfsId = 'tmpfs-' + (++tmpfsCounter);
        
        const tmpfsHtml = `
            <div class="row mb-2" id="${tmpfsId}">
                <div class="col-md-11">
                    <input type="text" class="form-control form-control-sm" placeholder="Tmpfs mount path" value="${path}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${tmpfsId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        tmpfsBuilder.insertAdjacentHTML('beforeend', tmpfsHtml);
        updateMountOptionsJSON();
    }
    
    // Docker Options Builder
    function addDockerOption(option = '') {
        const optionBuilder = document.getElementById('docker-options-builder');
        const optionId = 'option-' + (++optionCounter);
        
        const optionHtml = `
            <div class="row mb-2" id="${optionId}">
                <div class="col-md-11">
                    <input type="text" class="form-control form-control-sm" placeholder="Docker option (e.g., --cap-drop=ALL)" value="${option}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${optionId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        optionBuilder.insertAdjacentHTML('beforeend', optionHtml);
        updateMountOptionsJSON();
    }
    
    function updateMountOptionsJSON() {
        const mountOptions = {
            volumes: [],
            tmpfs: [],
            options: []
        };
        
        // Get volume mounts
        document.getElementById('volume-mounts-builder').querySelectorAll('.row').forEach(row => {
            const inputs = row.querySelectorAll('input');
            const typeSelect = row.querySelector('select');
            
            if (inputs.length >= 2 && inputs[0].value.trim() && inputs[1].value.trim()) {
                mountOptions.volumes.push({
                    source: inputs[0].value.trim(),
                    target: inputs[1].value.trim(),
                    type: typeSelect ? typeSelect.value : 'bind'
                });
            }
        });
        
        // Get tmpfs mounts
        document.getElementById('tmpfs-mounts-builder').querySelectorAll('.row').forEach(row => {
            const pathInput = row.querySelector('input');
            
            if (pathInput && pathInput.value.trim()) {
                mountOptions.tmpfs.push(pathInput.value.trim());
            }
        });
        
        // Get docker options
        document.getElementById('docker-options-builder').querySelectorAll('.row').forEach(row => {
            const optionInput = row.querySelector('input');
            
            if (optionInput && optionInput.value.trim()) {
                mountOptions.options.push(optionInput.value.trim());
            }
        });
        
        document.getElementById('mount_options_json').value = JSON.stringify(mountOptions);
    }
    
    // Edit form counters
    let editEnvVarCounter = 0;
    let editUserVarCounter = 0;
    let editVolumeCounter = 0;
    let editTmpfsCounter = 0;
    let editOptionCounter = 0;
    
    // Edit Environment Variables Builder
    function addEditEnvVar(name = '', value = '') {
        const envVarsBuilder = document.getElementById('edit-env-vars-builder');
        const varId = 'edit-env-var-' + (++editEnvVarCounter);
        
        const varHtml = `
            <div class="row mb-2" id="${varId}">
                <div class="col-md-5">
                    <input type="text" class="form-control form-control-sm" placeholder="Variable name" value="${name}">
                </div>
                <div class="col-md-6">
                    <input type="text" class="form-control form-control-sm" placeholder="Variable value (use \${WHP_USER}, etc.)" value="${value}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${varId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        envVarsBuilder.insertAdjacentHTML('beforeend', varHtml);
        updateEditEnvVarsJSON();
    }
    
    function updateEditEnvVarsJSON() {
        const envVarsBuilder = document.getElementById('edit-env-vars-builder');
        const envVars = {};
        
        envVarsBuilder.querySelectorAll('.row').forEach((row, index) => {
            const inputs = row.querySelectorAll('input[type="text"]');
            
            if (inputs.length >= 2) {
                const nameInput = inputs[0];
                const valueInput = inputs[1];
                
                if (nameInput.value.trim() && valueInput.value.trim()) {
                    envVars[nameInput.value.trim()] = valueInput.value.trim();
                }
            }
        });
        
        document.getElementById('edit_env_vars_json').value = JSON.stringify(envVars);
    }
    
    // Edit User Variables Builder
    function addEditUserVar(name = '', config = {}) {
        const userVarsBuilder = document.getElementById('edit-user-vars-builder');
        const varId = 'edit-user-var-' + (++editUserVarCounter);
        
        const varHtml = `
            <div class="card mb-2" id="${varId}">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-md-3">
                            <input type="text" class="form-control form-control-sm" placeholder="Variable name" value="${name}">
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control form-control-sm" placeholder="Display label" value="${config.label || ''}">
                        </div>
                        <div class="col-md-2">
                            <select class="form-control form-control-sm edit-var-type-select">
                                <option value="text" ${config.type === 'text' ? 'selected' : ''}>Text</option>
                                <option value="number" ${config.type === 'number' ? 'selected' : ''}>Number</option>
                                <option value="select" ${config.type === 'select' ? 'selected' : ''}>Select</option>
                                <option value="checkbox" ${config.type === 'checkbox' ? 'selected' : ''}>Checkbox</option>
                                <option value="textarea" ${config.type === 'textarea' ? 'selected' : ''}>Textarea</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control form-control-sm" placeholder="Default value" value="${config.default || ''}">
                        </div>
                        <div class="col-md-1">
                            <label class="form-check-label">
                                <input type="checkbox" class="form-check-input" ${config.required ? 'checked' : ''}> Required
                            </label>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${varId}')">
                                <i class="fa fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="row mt-2 edit-select-options" style="display: ${config.type === 'select' ? 'block' : 'none'};">
                        <div class="col-md-12">
                            <input type="text" class="form-control form-control-sm" placeholder="Options (comma-separated)" value="${config.options ? config.options.join(', ') : ''}">
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        userVarsBuilder.insertAdjacentHTML('beforeend', varHtml);
        
        // Add event listener for type change
        const lastCard = userVarsBuilder.lastElementChild;
        const typeSelect = lastCard.querySelector('.edit-var-type-select');
        const optionsRow = lastCard.querySelector('.edit-select-options');
        
        if (typeSelect) {
            typeSelect.addEventListener('change', function() {
                if (optionsRow) {
                    optionsRow.style.display = this.value === 'select' ? 'block' : 'none';
                }
                updateEditUserVarsJSON();
            });
        }
        
        updateEditUserVarsJSON();
    }
    
    function updateEditUserVarsJSON() {
        const userVarsBuilder = document.getElementById('edit-user-vars-builder');
        const userVars = {};
        
        userVarsBuilder.querySelectorAll('.card').forEach(card => {
            const nameInput = card.querySelector('input:first-child');
            const labelInput = card.querySelector('input:nth-child(2)');
            const typeSelect = card.querySelector('.edit-var-type-select');
            const defaultInput = card.querySelector('input:nth-child(4)');
            const requiredInput = card.querySelector('input[type="checkbox"]');
            const optionsInput = card.querySelector('.edit-select-options input');
            
            if (nameInput && nameInput.value.trim() && typeSelect) {
                const config = {
                    type: typeSelect.value,
                    label: labelInput ? (labelInput.value.trim() || nameInput.value.trim()) : nameInput.value.trim(),
                    required: requiredInput ? requiredInput.checked : false
                };
                
                if (defaultInput && defaultInput.value.trim()) {
                    config.default = defaultInput.value.trim();
                }
                
                if (typeSelect.value === 'select' && optionsInput && optionsInput.value.trim()) {
                    config.options = optionsInput.value.split(',').map(opt => opt.trim()).filter(opt => opt);
                }
                
                userVars[nameInput.value.trim()] = config;
            }
        });
        
        document.getElementById('edit_user_vars_json').value = JSON.stringify(userVars);
    }
    
    // Edit Volume Mounts Builder
    function addEditVolumeMount(source = '', target = '', type = 'bind') {
        const volumeBuilder = document.getElementById('edit-volume-mounts-builder');
        const volId = 'edit-volume-' + (++editVolumeCounter);
        
        const volHtml = `
            <div class="row mb-2" id="${volId}">
                <div class="col-md-4">
                    <input type="text" class="form-control form-control-sm" placeholder="Source path (use \${WHP_HOME}, etc.)" value="${source}">
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control form-control-sm" placeholder="Container path" value="${target}">
                </div>
                <div class="col-md-3">
                    <select class="form-control form-control-sm">
                        <option value="bind" ${type === 'bind' ? 'selected' : ''}>Bind</option>
                        <option value="volume" ${type === 'volume' ? 'selected' : ''}>Volume</option>
                    </select>
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${volId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        volumeBuilder.insertAdjacentHTML('beforeend', volHtml);
        updateEditMountOptionsJSON();
    }
    
    // Edit Tmpfs Mounts Builder
    function addEditTmpfsMount(path = '') {
        const tmpfsBuilder = document.getElementById('edit-tmpfs-mounts-builder');
        const tmpfsId = 'edit-tmpfs-' + (++editTmpfsCounter);
        
        const tmpfsHtml = `
            <div class="row mb-2" id="${tmpfsId}">
                <div class="col-md-11">
                    <input type="text" class="form-control form-control-sm" placeholder="Tmpfs mount path" value="${path}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${tmpfsId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        tmpfsBuilder.insertAdjacentHTML('beforeend', tmpfsHtml);
        updateEditMountOptionsJSON();
    }
    
    // Edit Docker Options Builder
    function addEditDockerOption(option = '') {
        const optionBuilder = document.getElementById('edit-docker-options-builder');
        const optionId = 'edit-option-' + (++editOptionCounter);
        
        const optionHtml = `
            <div class="row mb-2" id="${optionId}">
                <div class="col-md-11">
                    <input type="text" class="form-control form-control-sm" placeholder="Docker option (e.g., --cap-drop=ALL)" value="${option}">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeElement('${optionId}')">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        
        optionBuilder.insertAdjacentHTML('beforeend', optionHtml);
        updateEditMountOptionsJSON();
    }
    
    function updateEditMountOptionsJSON() {
        const mountOptions = {
            volumes: [],
            tmpfs: [],
            options: []
        };
        
        // Get volume mounts
        document.getElementById('edit-volume-mounts-builder').querySelectorAll('.row').forEach(row => {
            const inputs = row.querySelectorAll('input');
            const typeSelect = row.querySelector('select');
            
            if (inputs.length >= 2 && inputs[0].value.trim() && inputs[1].value.trim()) {
                mountOptions.volumes.push({
                    source: inputs[0].value.trim(),
                    target: inputs[1].value.trim(),
                    type: typeSelect ? typeSelect.value : 'bind'
                });
            }
        });
        
        // Get tmpfs mounts
        document.getElementById('edit-tmpfs-mounts-builder').querySelectorAll('.row').forEach(row => {
            const pathInput = row.querySelector('input');
            
            if (pathInput && pathInput.value.trim()) {
                mountOptions.tmpfs.push(pathInput.value.trim());
            }
        });
        
        // Get docker options
        document.getElementById('edit-docker-options-builder').querySelectorAll('.row').forEach(row => {
            const optionInput = row.querySelector('input');
            
            if (optionInput && optionInput.value.trim()) {
                mountOptions.options.push(optionInput.value.trim());
            }
        });
        
        document.getElementById('edit_mount_options_json').value = JSON.stringify(mountOptions);
    }
    
         // Generic remove element function
     window.removeElement = function(elementId) {
         const element = document.getElementById(elementId);
         if (element) {
             element.remove();
             
             // Update create form
             updateEnvVarsJSON();
             updateUserVarsJSON();
             updateMountOptionsJSON();
             
             // Update edit form if it exists
             if (document.getElementById('edit-env-vars-builder')) {
                 updateEditEnvVarsJSON();
                 updateEditUserVarsJSON();
                 updateEditMountOptionsJSON();
             }
         }
     }
    
    // Initialize builders
    document.getElementById('add-env-var').addEventListener('click', () => addEnvVar());
    document.getElementById('add-user-var').addEventListener('click', () => addUserVar());
    document.getElementById('add-volume-mount').addEventListener('click', () => addVolumeMount());
    document.getElementById('add-tmpfs-mount').addEventListener('click', () => addTmpfsMount());
    document.getElementById('add-docker-option').addEventListener('click', () => addDockerOption());
    
    // Initialize edit builders
    document.getElementById('edit-add-env-var').addEventListener('click', () => addEditEnvVar());
    document.getElementById('edit-add-user-var').addEventListener('click', () => addEditUserVar());
    document.getElementById('edit-add-volume-mount').addEventListener('click', () => addEditVolumeMount());
    document.getElementById('edit-add-tmpfs-mount').addEventListener('click', () => addEditTmpfsMount());
    document.getElementById('edit-add-docker-option').addEventListener('click', () => addEditDockerOption());
    
    // Add event listeners for real-time updates
    document.getElementById('env-vars-builder').addEventListener('input', updateEnvVarsJSON);
    document.getElementById('user-vars-builder').addEventListener('input', updateUserVarsJSON);
    document.getElementById('volume-mounts-builder').addEventListener('input', updateMountOptionsJSON);
    document.getElementById('tmpfs-mounts-builder').addEventListener('input', updateMountOptionsJSON);
    document.getElementById('docker-options-builder').addEventListener('input', updateMountOptionsJSON);
    
    // Add event listeners for edit form real-time updates
    document.getElementById('edit-env-vars-builder').addEventListener('input', updateEditEnvVarsJSON);
    document.getElementById('edit-user-vars-builder').addEventListener('input', updateEditUserVarsJSON);
    document.getElementById('edit-volume-mounts-builder').addEventListener('input', updateEditMountOptionsJSON);
    document.getElementById('edit-tmpfs-mounts-builder').addEventListener('input', updateEditMountOptionsJSON);
    document.getElementById('edit-docker-options-builder').addEventListener('input', updateEditMountOptionsJSON);
    
         // Add some default entries
     addEnvVar('APACHE_DOCUMENT_ROOT', '/var/www/html/\${WHP_DOMAIN}');
     addEnvVar('WHP_USER', '\${WHP_USER}');
     addEnvVar('WHP_UID', '\${WHP_UID}');
     addEnvVar('WHP_GID', '\${WHP_GID}');
     addEnvVar('LISTEN_PORT', '\${WHP_LISTEN_PORT}');
     
     addVolumeMount('\${WHP_HOME}/public_html', '/var/www/html', 'bind');
     addTmpfsMount('/tmp');
     addDockerOption('--cap-drop=ALL');
     addDockerOption('--cap-add=CHOWN');
    
             // Form submission with validation
    const containerTypeForm = document.getElementById('containerTypeForm');
    if (containerTypeForm) {
        containerTypeForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Update JSON fields from form builders
            updateEnvVarsJSON();
            updateUserVarsJSON();
            updateMountOptionsJSON();
            
            // Basic form validation
            const requiredFields = ['name', 'base_image'];
            let isValid = true;
            
            requiredFields.forEach(fieldName => {
                const field = document.getElementById(fieldName);
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                showMessage('Please fill in all required fields.', 'danger');
                return;
            }
            
            // Submit via AJAX
            const formData = new FormData(containerTypeForm);
            const submitBtn = document.getElementById('createTypeBtn');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Creating...';
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 403) {
                        throw new Error('CSRF token validation failed. Please refresh the page and try again.');
                    }
                    throw new Error(`Server error: ${response.status} ${response.statusText}`);
                }
                return response.text();
            })
            .then(data => {
                // Check if response contains success or error messages
                if (data.includes('Container type created successfully')) {
                    showMessage('Container type created successfully!', 'success');
                    containerTypeForm.reset();
                    
                    // Clear form builders
                    document.getElementById('env-vars-builder').innerHTML = '';
                    document.getElementById('user-vars-builder').innerHTML = '';
                    document.getElementById('volume-mounts-builder').innerHTML = '';
                    document.getElementById('tmpfs-mounts-builder').innerHTML = '';
                    document.getElementById('docker-options-builder').innerHTML = '';
                    
                    // Reset counters
                    envVarCounter = 0;
                    userVarCounter = 0;
                    volumeCounter = 0;
                    tmpfsCounter = 0;
                    optionCounter = 0;
                    
                    // Reload the page after a short delay to refresh the list
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else if (data.includes('Error creating container type')) {
                    const errorMatch = data.match(/Error creating container type: ([^<]+)/);
                    const errorMsg = errorMatch ? errorMatch[1] : 'Unknown error occurred';
                    showMessage('Error: ' + errorMsg, 'danger');
                } else if (data.includes('CSRF token validation failed')) {
                    showMessage('Security validation failed. Please refresh the page and try again.', 'danger');
                } else if (data.includes('403 Forbidden')) {
                    showMessage('Access denied. Please refresh the page and try again.', 'danger');
                } else {
                    // Assume success if no explicit error found
                    showMessage('Container type created successfully!', 'success');
                    containerTypeForm.reset();
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-plus"></i> Create Enhanced Container Type';
            });
        });
    }
    
    // Edit form submission
    const editContainerTypeForm = document.getElementById('editContainerTypeForm');
    if (editContainerTypeForm) {
        document.getElementById('editTypeBtn').addEventListener('click', function(e) {
            e.preventDefault();
            
            // Update JSON fields from form builders
            updateEditEnvVarsJSON();
            updateEditUserVarsJSON();
            updateEditMountOptionsJSON();
            
            // Basic form validation
            const requiredFields = ['edit_name', 'edit_base_image'];
            let isValid = true;
            
            requiredFields.forEach(fieldName => {
                const field = document.getElementById(fieldName);
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                showMessage('Please fill in all required fields.', 'danger');
                return;
            }
            
            // Submit via AJAX
            const formData = new FormData(editContainerTypeForm);
            formData.append('action', 'update_container_type');
            
            // Debug: Log what we're sending
            console.log('Sending form data:');
            for (let [key, value] of formData.entries()) {
                console.log(key + ': ' + value);
            }
            
            const submitBtn = this;
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Updating...';
            
            fetch('api/container-types.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === '0') {
                    showMessage('Container type updated successfully!', 'success');
                    // Close the modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editContainerTypeModal'));
                    if (modal) {
                        modal.hide();
                    }
                    // Reload the page after a short delay to refresh the list
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showMessage('Error: ' + data.msg, 'danger');
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-save"></i> Update Container Type';
            });
        });
    }
    
    // Toggle container type status
    document.querySelectorAll('.toggle-type-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const typeId = this.dataset.typeId;
            const currentStatus = this.dataset.currentStatus;
            const action = currentStatus === '1' ? 'Disabling' : 'Enabling';
            
            this.disabled = true;
            this.innerHTML = `<i class="fa fa-spinner fa-spin"></i> ${action}...`;
            
            const formData = new FormData();
            formData.append('action', 'toggle_container_type');
            formData.append('type_id', typeId);
            
            fetch('api/container-types.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === '0') {
                    showMessage('Container type status updated successfully!', 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showMessage('Error updating container type status: ' + data.msg, 'danger');
                    this.disabled = false;
                    this.innerHTML = currentStatus === '1' ? 'Disable' : 'Enable';
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
                this.disabled = false;
                this.innerHTML = currentStatus === '1' ? 'Disable' : 'Enable';
            });
        });
    });
    
    // Remove container type
    document.querySelectorAll('.remove-type-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const typeId = this.dataset.typeId;
            const typeName = this.dataset.typeName;
            
            if (!confirm(`Are you sure you want to remove the container type "${typeName}"? This action cannot be undone.`)) {
                return;
            }
            
            this.disabled = true;
            this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Removing...';
            
            const formData = new FormData();
            formData.append('action', 'remove_container_type');
            formData.append('type_id', typeId);
            
            fetch('api/container-types.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === '0') {
                    showMessage('Container type removed successfully!', 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else if (data.msg && data.msg.includes('in use')) {
                    showMessage('Cannot remove container type that is in use', 'warning');
                    this.disabled = false;
                    this.innerHTML = '<i class="fa fa-trash"></i> Remove';
                } else {
                    showMessage('Error removing container type: ' + data.msg, 'danger');
                    this.disabled = false;
                    this.innerHTML = '<i class="fa fa-trash"></i> Remove';
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
                this.disabled = false;
                this.innerHTML = '<i class="fa fa-trash"></i> Remove';
            });
        });
    });
    
    // Edit container type
    document.querySelectorAll('.edit-container-type-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const typeId = this.dataset.typeId;
            
            // Close the details modal
            const detailsModal = this.closest('.modal');
            if (detailsModal) {
                const modalInstance = bootstrap.Modal.getInstance(detailsModal);
                if (modalInstance) {
                    modalInstance.hide();
                }
            }
            
            // Load container type data for editing
            const formData = new FormData();
            formData.append('action', 'get_container_type');
            formData.append('type_id', typeId);
            
            fetch('api/container-types.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Received data:', data);
                if (data.status === '0') {
                    // Populate the edit form
                    populateEditForm(data.container_type);
                    // Show the edit modal
                    const editModal = new bootstrap.Modal(document.getElementById('editContainerTypeModal'));
                    editModal.show();
                } else {
                    showMessage('Error loading container type data: ' + data.msg, 'danger');
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
            });
        });
    });
    
    function populateEditForm(containerType) {
        console.log('Populating edit form with:', containerType);
        
        // Basic fields
        document.getElementById('edit_name').value = containerType.name;
        document.getElementById('edit_description').value = containerType.description;
        document.getElementById('edit_base_image').value = containerType.base_image;
        document.getElementById('edit_min_cpu').value = containerType.min_cpu;
        document.getElementById('edit_min_memory').value = containerType.min_memory;
        document.getElementById('edit_listen_port').value = containerType.listen_port || 80;
        document.getElementById('edit_type_id').value = containerType.id;
        // Set TLS checkbox
        document.getElementById('edit_listen_port_tls').checked = containerType.listen_port_tls == 1;
        
        // Clear existing builders
        document.getElementById('edit-env-vars-builder').innerHTML = '';
        document.getElementById('edit-user-vars-builder').innerHTML = '';
        document.getElementById('edit-volume-mounts-builder').innerHTML = '';
        document.getElementById('edit-tmpfs-mounts-builder').innerHTML = '';
        document.getElementById('edit-docker-options-builder').innerHTML = '';
        
        // Reset counters
        editEnvVarCounter = 0;
        editUserVarCounter = 0;
        editVolumeCounter = 0;
        editTmpfsCounter = 0;
        editOptionCounter = 0;
        
        // Environment variables
        if (containerType.startup_env && typeof containerType.startup_env === 'object') {
            const envVars = containerType.startup_env;
            if (Array.isArray(envVars)) {
                // Handle array format (should be empty for this case)
                if (envVars.length === 0) {
                    // Add some default environment variables for empty containers
                    addEditEnvVar('APACHE_DOCUMENT_ROOT', '/var/www/html/${WHP_DOMAIN}');
                    addEditEnvVar('WHP_USER', '${WHP_USER}');
                    addEditEnvVar('WHP_UID', '${WHP_UID}');
                    addEditEnvVar('WHP_GID', '${WHP_GID}');
                    addEditEnvVar('LISTEN_PORT', '${WHP_LISTEN_PORT}');
                }
            } else {
                // Handle object format
                Object.entries(envVars).forEach(([name, value]) => {
                    addEditEnvVar(name, value);
                });
            }
        } else {
            // Add default environment variables for completely empty containers
            addEditEnvVar('APACHE_DOCUMENT_ROOT', '/var/www/html/${WHP_DOMAIN}');
            addEditEnvVar('WHP_USER', '${WHP_USER}');
            addEditEnvVar('WHP_UID', '${WHP_UID}');
            addEditEnvVar('WHP_GID', '${WHP_GID}');
            addEditEnvVar('LISTEN_PORT', '${WHP_LISTEN_PORT}');
        }
        
        // User variables
        if (containerType.user_variables) {
            const userVars = containerType.user_variables;
            if (typeof userVars === 'object') {
                Object.entries(userVars).forEach(([name, config]) => {
                    addEditUserVar(name, config);
                });
            }
        }
        
        // Mount options
        if (containerType.mount_options) {
            const mountOpts = containerType.mount_options;
            if (typeof mountOpts === 'object') {
                if (mountOpts.volumes) {
                    mountOpts.volumes.forEach(volume => {
                        addEditVolumeMount(volume.source, volume.target, volume.type);
                    });
                }
                
                if (mountOpts.tmpfs) {
                    mountOpts.tmpfs.forEach(tmpfs => {
                        addEditTmpfsMount(tmpfs);
                    });
                }
                
                if (mountOpts.options) {
                    mountOpts.options.forEach(option => {
                        addEditDockerOption(option);
                    });
                }
            }
        }
    }
    
    // Pull image
    document.querySelectorAll('.pull-image-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const imageName = this.dataset.imageName;
            
            this.disabled = true;
            this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Pulling...';
            
            const formData = new FormData();
            formData.append('action', 'pull_image');
            formData.append('image_name', imageName);
            
            fetch('api/container-types.php', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': nonce
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === '0') {
                    showMessage(`Image ${imageName} pulled successfully!`, 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showMessage('Error pulling image: ' + data.msg, 'danger');
                    this.disabled = false;
                    this.innerHTML = '<i class="fa fa-download"></i> Pull';
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
                this.disabled = false;
                this.innerHTML = '<i class="fa fa-download"></i> Pull';
            });
        });
    });
    
    // Helper function to show messages
    function showMessage(message, type) {
        const messagesDiv = document.getElementById('formMessages');
        if (messagesDiv) {
            messagesDiv.innerHTML = `
                <div class="alert alert-${type} alert-dismissible" role="alert">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    <i class="fa fa-${type === 'success' ? 'check' : type === 'warning' ? 'exclamation-triangle' : 'times'}"></i>
                    ${message}
                </div>
            `;
        } else {
            // Fallback - show message at top of page
            const existingAlerts = document.querySelectorAll('.row .alert');
            existingAlerts.forEach(alert => alert.remove());
            
            const alertDiv = document.createElement('div');
            alertDiv.className = 'row';
            alertDiv.innerHTML = `
                <div class="col-md-12">
                    <div class="alert alert-${type} alert-dismissible" role="alert">
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        <i class="fa fa-${type === 'success' ? 'check' : type === 'warning' ? 'exclamation-triangle' : 'times'}"></i>
                        ${message}
                    </div>
                </div>
            `;
            
            const firstRow = document.querySelector('.row');
            if (firstRow) {
                firstRow.parentNode.insertBefore(alertDiv, firstRow);
            }
        }
    }
    
    // Recreate container functionality
    document.querySelectorAll('.recreate-container-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const siteId = this.dataset.siteId;
            const containerId = this.dataset.containerId;
            
            if (!confirm('Are you sure you want to recreate this container with the latest image? This will pull the latest image and recreate the container.')) {
                return;
            }
            
            this.disabled = true;
            this.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Recreating...';
            this.style.minWidth = '80px';
            
            fetch('api/sites.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': nonce
                },
                body: JSON.stringify({
                    action: 'recreate_container',
                    site_id: siteId,
                    container_id: containerId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showMessage('Container recreated successfully', 'success');
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    showMessage('Error recreating container: ' + data.message, 'danger');
                    this.disabled = false;
                    this.innerHTML = 'Recreate';
                }
            })
            .catch(error => {
                showMessage('Network error: ' + error.message, 'danger');
                this.disabled = false;
                this.innerHTML = 'Recreate';
            });
        });
    });
});
</script> 