<?php
// Container status checking API for site creation readiness
header('Content-Type: application/json');

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

require_once '../libs/mysqlmgmt.php';
require_once '../libs/docker-api.php';

if (!isset($_GET['site_id']) || !is_numeric($_GET['site_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid site ID']);
    exit;
}

$site_id = intval($_GET['site_id']);

try {
    $MySQLMgmt = new mysqlmgmt();
    $db = $MySQLMgmt->getMySQLConnection();
    
    // Verify user owns this site (unless root)
    $is_root = (defined('AUTH_USER') && AUTH_USER === 'root');
    if (!$is_root) {
        $stmt = $db->prepare("SELECT username FROM whp.sites WHERE id = ?");
        $stmt->execute([$site_id]);
        $site = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$site || $site['username'] !== AUTH_USER) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'Access denied']);
            exit;
        }
    }
    
    // Get all containers for this site
    $stmt = $db->prepare("SELECT container_id FROM whp.site_containers WHERE site_id = ? AND status = 'running'");
    $stmt->execute([$site_id]);
    $containers = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (empty($containers)) {
        echo json_encode(['success' => false, 'error' => 'No containers found for site']);
        exit;
    }
    
    $docker_api = new docker_api();
    $all_ready = true;
    $container_statuses = [];
    
    foreach ($containers as $container_id) {
        // Check if container is running
        $container_result = $docker_api->inspect_container($container_id);
        
        if (!$container_result['success'] || $container_result['data']['State']['Status'] !== 'running') {
            $all_ready = false;
            $container_statuses[$container_id] = 'not_running';
            continue;
        }
        
        // Check if container is responding to HTTP requests
        // We'll do a simple health check by trying to connect to the container
        $container_statuses[$container_id] = 'running';
        
        // Optional: Add more sophisticated health checks here
        // For now, if container is running, we consider it ready
    }
    
    echo json_encode([
        'success' => true,
        'all_ready' => $all_ready,
        'container_count' => count($containers),
        'ready_count' => count(array_filter($container_statuses, function($status) { 
            return $status === 'running'; 
        })),
        'statuses' => $container_statuses
    ]);
    
} catch (Exception $e) {
    error_log("Container status check error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Internal server error']);
}
?>