<?php
/**
 * 远程 cloak API（byApi / byApiRisk）请求与响应审计，供 visitor_logs 落库与日志页展示。
 */
class VisitorApiAudit
{
    const SESSION_BY_REQUEST  = 'cloak_api_by_request';
    const SESSION_BY_RESPONSE = 'cloak_api_by_response';
    const SESSION_BY_CALLED   = 'cloak_api_by_called';

    public static function clearByApi()
    {
        unset(
            $_SESSION[self::SESSION_BY_REQUEST],
            $_SESSION[self::SESSION_BY_RESPONSE],
            $_SESSION[self::SESSION_BY_CALLED]
        );
    }

    public static function wasByApiCalledThisRequest()
    {
        return !empty($_SESSION[self::SESSION_BY_CALLED]);
    }

    /**
     * @param array|string $payload
     */
    public static function recordByApiRequest($payload)
    {
        $_SESSION[self::SESSION_BY_CALLED]   = 1;
        $_SESSION[self::SESSION_BY_REQUEST] = self::encode($payload);
    }

    /**
     * @param array|string|null $payload
     */
    public static function recordByApiResponse($payload)
    {
        if ($payload === null || $payload === '') {
            return;
        }
        $_SESSION[self::SESSION_BY_RESPONSE] = self::encode($payload);
    }

    /**
     * 写入日志数组（仅合并当前请求内已调用的 byApi 审计数据）
     *
     * @param array $logs
     * @return array
     */
    public static function mergeIntoLogs(array $logs)
    {
        if (!self::wasByApiCalledThisRequest()) {
            return $logs;
        }
        $map = [
            'api_by_request'  => self::SESSION_BY_REQUEST,
            'api_by_response' => self::SESSION_BY_RESPONSE,
        ];
        foreach ($map as $col => $sessionKey) {
            if (empty($logs[$col]) && !empty($_SESSION[$sessionKey])) {
                $logs[$col] = (string) $_SESSION[$sessionKey];
            }
        }
        return $logs;
    }

    /**
     * @param mixed $data
     */
    public static function encode($data)
    {
        if (is_string($data)) {
            return $data;
        }
        $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return $json !== false ? $json : '';
    }

    /**
     * 日志表格展示：未调用时返回「-」
     *
     * @param mixed $raw
     */
    public static function displayText($raw)
    {
        $raw = trim((string) $raw);
        return $raw === '' ? '-' : $raw;
    }
}
