<?php
/*******************************************************************************************************************
| EasyStream Health Check Endpoint
| Container health monitoring for Docker deployment
|*******************************************************************************************************************/

// Set headers for health check
header('Content-Type: application/json');
header('X-Container: vs-php');
header('X-Hostname: ' . gethostname());

// Basic health check data
$health = [
    'status' => 'healthy',
    'timestamp' => date('c'),
    'container' => 'vs-php',
    'hostname' => gethostname(),
    'php_version' => PHP_VERSION,
    'memory_usage' => memory_get_usage(true),
    'memory_peak' => memory_get_peak_usage(true)
];

// Check core system files
$core_files = [
    'f_core/config.core.php',
    'index.php',
    '.htaccess'
];

$files_ok = true;
foreach ($core_files as $file) {
    if (!file_exists($file)) {
        $health['status'] = 'unhealthy';
        $health['error'] = "Missing core file: $file";
        $files_ok = false;
        break;
    }
}

// Check database connection if core files exist
if ($files_ok) {
    try {
        if (file_exists('f_core/config.core.php')) {
            include_once 'f_core/config.core.php';
            
            // Test database connection
            if (isset($class_database) && is_object($class_database)) {
                $health['database'] = 'connected';
            } else {
                $health['database'] = 'disconnected';
                $health['status'] = 'degraded';
            }
        }
    } catch (Exception $e) {
        $health['database'] = 'error';
        $health['database_error'] = $e->getMessage();
        $health['status'] = 'degraded';
    }
}

// Set appropriate HTTP status code
switch ($health['status']) {
    case 'healthy':
        http_response_code(200);
        break;
    case 'degraded':
        http_response_code(200); // Still operational
        break;
    case 'unhealthy':
        http_response_code(503);
        break;
}

echo json_encode($health, JSON_PRETTY_PRINT);
?>