<?php
/**
 * ===========================================
 * Health Check Endpoint
 * ===========================================
 * 
 * Purpose: Check server and database health
 * Used for: Automatic failover detection
 * 
 * Response Format:
 * {
 *   "success": true,
 *   "message": "Server is healthy",
 *   "data": {
 *     "timestamp": "2025-01-28 12:00:00",
 *     "server": "online",
 *     "database": "connected",
 *     "response_time_ms": 15
 *   }
 * }
 * ===========================================
 */

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Start timing
$start_time = microtime(true);

try {
    // Include database connection
    require_once __DIR__ . '/db.php';
    
    // Check if PDO connection exists
    if (!isset($pdo)) {
        throw new Exception("Database connection not available");
    }
    
    // Test database connection with a simple query
    $stmt = $pdo->query("SELECT 1");
    $result = $stmt->fetch();
    
    if ($result === false) {
        throw new Exception("Database query failed");
    }
    
    // Calculate response time
    $end_time = microtime(true);
    $response_time_ms = round(($end_time - $start_time) * 1000, 2);
    
    // Return success response
    echo json_encode([
        "success" => true,
        "message" => "Server is healthy",
        "data" => [
            "timestamp" => date("Y-m-d H:i:s"),
            "server" => "online",
            "database" => "connected",
            "response_time_ms" => $response_time_ms,
            "php_version" => phpversion(),
            "server_software" => $_SERVER['SERVER_SOFTWARE'] ?? "Unknown"
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    // Calculate response time even on error
    $end_time = microtime(true);
    $response_time_ms = round(($end_time - $start_time) * 1000, 2);
    
    // Return error response
    http_response_code(503); // Service Unavailable
    echo json_encode([
        "success" => false,
        "message" => "Server health check failed",
        "data" => [
            "timestamp" => date("Y-m-d H:i:s"),
            "server" => "online",
            "database" => "disconnected",
            "error" => $e->getMessage(),
            "response_time_ms" => $response_time_ms
        ]
    ], JSON_UNESCAPED_UNICODE);
}
?>
