<?php
// AJAX Status Endpoint - Bypasses authentication for status requests
// This file is called directly for AJAX status updates

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

// Get current service status
$ajax_service_status = [];
$services = ['httpd', 'php-fpm', 'docker', 'proftpd'];
foreach ($services as $service) {
    // Validate service name to prevent command injection
    $service = escapeshellarg($service);
    $status = trim(shell_exec("systemctl is-active $service 2>/dev/null"));
    $ajax_service_status[trim($service, "'")] = $status;
}

// Get current container status
$ajax_container_status = [];
$containers = ['mysql', 'haproxy-manager', 'memcache'];
foreach ($containers as $container) {
    // Validate container name to prevent command injection
    $container_escaped = escapeshellarg($container);
    $status = trim(shell_exec("docker ps --filter name=$container_escaped --format '{{.Status}}' 2>/dev/null"));
    if (!empty($status)) {
        $ajax_container_status[$container] = 'running';
    } else {
        // Check if container exists but is stopped
        $exists = trim(shell_exec("docker ps -a --filter name=$container_escaped --format '{{.Names}}' 2>/dev/null"));
        $ajax_container_status[$container] = !empty($exists) ? 'stopped' : 'not_found';
    }
}

// Return JSON response
echo json_encode([
    'service_status' => $ajax_service_status,
    'container_status' => $ajax_container_status,
    'timestamp' => date('Y-m-d H:i:s')
]);
exit; 