<?php
// Container Types API
// Handle AJAX requests for container type operations

// Auth gate — auto-prepend skips redirect for /api/* paths so this script
// must self-enforce. AUTH_USER is defined by auto-prepend.php on a successful
// authenticated request.
if (!defined('AUTH_USER')) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Authentication required']);
    exit;
}
// All actions on this endpoint mutate Docker state — root only.
if (AUTH_USER !== 'root') {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Admin only']);
    exit;
}

// Start output buffering
ob_start();

// Include required libraries
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/docker-api.php');

$MySQLMgmt = new mysqlmgmt();
$DockerAPI = new docker_api();

// Set JSON content type
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

// Handle the request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'get_container_type':
            if (!empty($_POST['type_id'])) {
                try {
                    $result = $MySQLMgmt->getContainerType($_POST['type_id']);
                    echo json_encode($result);
                } catch (Exception $e) {
                    echo json_encode(['status' => '1', 'msg' => 'Error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['status' => '1', 'msg' => 'No type_id provided']);
            }
            break;
            
        case 'update_container_type':
            if (!empty($_POST['type_id'])) {
                try {
                    $type_id = intval($_POST['type_id']);
                    $name = trim($_POST['name']);
                    $description = trim($_POST['description'] ?? '');
                    $base_image = trim($_POST['base_image']);
                    $min_cpu = floatval($_POST['min_cpu'] ?? 0.25);
                    $min_memory = intval($_POST['min_memory'] ?? 256);
                    $listen_port = intval($_POST['listen_port'] ?? 80);
                    $listen_port_tls = isset($_POST['listen_port_tls']) ? 1 : 0;
                    $is_premium = isset($_POST['is_premium']) ? 1 : 0;
                    // Parse JSON data
                    $startup_env = json_decode($_POST['env_vars_json'] ?? '{}', true) ?: [];
                    $user_variables = json_decode($_POST['user_vars_json'] ?? '{}', true) ?: [];
                    $mount_options = json_decode($_POST['mount_options_json'] ?? '{}', true) ?: [];
                    $result = $MySQLMgmt->updateContainerType($type_id, [
                        'name' => $name,
                        'description' => $description,
                        'base_image' => $base_image,
                        'min_cpu' => $min_cpu,
                        'min_memory' => $min_memory,
                        'listen_port' => $listen_port,
                        'listen_port_tls' => $listen_port_tls,
                        'is_premium' => $is_premium,
                        'startup_env' => $startup_env,
                        'user_variables' => $user_variables,
                        'mount_options' => $mount_options
                    ]);
                    
                    if ($result['status'] === '0') {
                        echo json_encode(['status' => '0', 'msg' => 'Container type updated successfully']);
                    } else {
                        echo json_encode(['status' => '1', 'msg' => 'Error updating container type: ' . $result['msg']]);
                    }
                } catch (Exception $e) {
                    echo json_encode(['status' => '1', 'msg' => 'Error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['status' => '1', 'msg' => 'No type_id provided']);
            }
            break;
            
        case 'toggle_container_type':
            if (!empty($_POST['type_id'])) {
                try {
                    $result = $MySQLMgmt->toggleContainerTypeStatus($_POST['type_id']);
                    echo json_encode($result);
                } catch (Exception $e) {
                    echo json_encode(['status' => '1', 'msg' => 'Error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['status' => '1', 'msg' => 'No type_id provided']);
            }
            break;
            
        case 'remove_container_type':
            if (!empty($_POST['type_id'])) {
                try {
                    // Get container type details before deletion to know the image name
                    $type_result = $MySQLMgmt->getContainerType($_POST['type_id']);
                    $image_name = '';
                    
                    if ($type_result['status'] === '0') {
                        $image_name = $type_result['container_type']['base_image'];
                    }
                    
                    $result = $MySQLMgmt->deleteContainerType($_POST['type_id']);
                    
                    if ($result['status'] === '0') {
                        $response = ['status' => '0', 'msg' => 'Container type removed successfully'];
                        
                        // Try to clean up the image if it's no longer in use
                        if (!empty($image_name)) {
                            $cleanup_result = $DockerAPI->cleanup_image_if_unused($image_name);
                            if ($cleanup_result['success']) {
                                $response['msg'] .= '. ' . $cleanup_result['message'];
                            } else {
                                $response['msg'] .= '. Note: ' . $cleanup_result['message'];
                            }
                        }
                        
                        echo json_encode($response);
                    } else {
                        echo json_encode($result);
                    }
                } catch (Exception $e) {
                    echo json_encode(['status' => '1', 'msg' => 'Error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['status' => '1', 'msg' => 'No type_id provided']);
            }
            break;
            
        case 'pull_image':
            if (!empty($_POST['image_name'])) {
                try {
                    $result = $DockerAPI->pull_image($_POST['image_name']);
                    if ($result['success']) {
                        echo json_encode(['status' => '0', 'msg' => 'Image pulled successfully: ' . $_POST['image_name']]);
                    } else {
                        echo json_encode(['status' => '1', 'msg' => 'Error pulling image: ' . $result['error']]);
                    }
                } catch (Exception $e) {
                    echo json_encode(['status' => '1', 'msg' => 'Error: ' . $e->getMessage()]);
                }
            } else {
                echo json_encode(['status' => '1', 'msg' => 'No image_name provided']);
            }
            break;
            
        default:
            echo json_encode(['status' => '1', 'msg' => 'Invalid action']);
            break;
    }
} else {
    echo json_encode(['status' => '1', 'msg' => 'Invalid request method']);
}
?> 