<?php
/**
 * 心跳接口 - 用于维持与授权服务器的在线状态
 * 根据API文档，心跳间隔应为5秒
 */

require_once __DIR__ . '/../MPHX/common.php';
require_once __DIR__ . '/../MPHX/AuthManager.php';

// 允许跨域请求（如果需要）
header('Content-Type: application/json');

// 检查登录状态
if (!is_admin_login()) {
    exit(json_encode(['code' => 401, 'message' => '未登录']));
}

$authManager = new AuthManager($DB);

// 获取token（会自动处理刷新逻辑）
$token_result = $authManager->getToken();

if ($token_result['code'] != 200) {
    // 清除session中的token
    unset($_SESSION['auth_token']);
    unset($_SESSION['auth_token_expire']);
    
    if ($token_result['code'] == 403 && isset($token_result['data']['need_auth'])) {
        exit(json_encode(['code' => 403, 'message' => $token_result['message']]));
    }
    
    exit(json_encode(['code' => 500, 'message' => '获取token失败: ' . ($token_result['message'] ?? '未知错误')]));
}

$token = $token_result['data']['token'];

// 保存token到session
$_SESSION['auth_token'] = $token;
$_SESSION['auth_token_expire'] = strtotime($token_result['data']['expire_time'] ?? '') ?: (time() + 86400);

// 发送心跳
$heartbeat = $authManager->heartbeat($token);

if ($heartbeat['code'] == 200) {
    exit(json_encode([
        'code' => 200,
        'message' => '心跳成功',
        'data' => [
            'status' => $heartbeat['data']['status'] ?? 'online',
            'expire_time' => $heartbeat['data']['expire_time'] ?? '',
            'remain_seconds' => $heartbeat['data']['remain_seconds'] ?? 0
        ]
    ]));
} else {
    // Token可能已过期，清除session中的token
    unset($_SESSION['auth_token']);
    unset($_SESSION['auth_token_expire']);
    exit(json_encode(['code' => 401, 'message' => '心跳失败: ' . ($heartbeat['message'] ?? 'token无效')]));
}
