<?php
/**
 * Health check endpoint para Docker
 * Verifica que todos los servicios estén funcionando
 */

header('Content-Type: application/json');

$health = [
    'status' => 'healthy',
    'timestamp' => date('Y-m-d H:i:s'),
    'checks' => []
];

// 1. Check PHP
$health['checks']['php'] = [
    'status' => 'ok',
    'version' => PHP_VERSION
];

// 2. Check Database
try {
    require_once __DIR__ . '/config/config.php';
    $db = Database::getInstance();
    $result = $db->query("SELECT 1")->fetch();
    
    $health['checks']['database'] = [
        'status' => $result ? 'ok' : 'error',
        'host' => DB_HOST
    ];
} catch (Exception $e) {
    $health['checks']['database'] = [
        'status' => 'error',
        'error' => $e->getMessage()
    ];
    $health['status'] = 'unhealthy';
}

// 3. Check Redis
try {
    $redis = new Predis\Client([
        'scheme' => getenv('REDIS_SCHEME') ?: 'tcp',
        'host'   => getenv('REDIS_HOST') ?: 'redis',
        'port'   => getenv('REDIS_PORT') ?: 6379,
    ]);
    
    $ping = $redis->ping();
    
    $health['checks']['redis'] = [
        'status' => ($ping === 'PONG' || $ping === true) ? 'ok' : 'error',
        'host' => getenv('REDIS_HOST') ?: 'redis'
    ];
} catch (Exception $e) {
    $health['checks']['redis'] = [
        'status' => 'error',
        'error' => $e->getMessage()
    ];
    $health['status'] = 'unhealthy';
}

// 4. Check logs directory
$health['checks']['logs'] = [
    'status' => is_writable(__DIR__ . '/logs') ? 'ok' : 'error',
    'writable' => is_writable(__DIR__ . '/logs')
];

// 5. Check uploads directory
$health['checks']['uploads'] = [
    'status' => is_writable(__DIR__ . '/uploads') ? 'ok' : 'error',
    'writable' => is_writable(__DIR__ . '/uploads')
];

// 6. Check Queue stats (opcional)
try {
    require_once __DIR__ . '/queue/RedisQueue.php';
    $queue = new WhatsApp\Queue\RedisQueue();
    $stats = $queue->getStats();
    
    $health['checks']['queue'] = [
        'status' => 'ok',
        'stats' => $stats
    ];
} catch (Exception $e) {
    $health['checks']['queue'] = [
        'status' => 'warning',
        'error' => $e->getMessage()
    ];
}

// HTTP status code
http_response_code($health['status'] === 'healthy' ? 200 : 503);

echo json_encode($health, JSON_PRETTY_PRINT);
