<?php
/**
 * 访客日志「第几次访问」：写入时计算，避免列表接口 N+1 查询。
 */
class VisitorLogVtimes
{
    /**
     * @param mysqli $conn
     * @param string $ip
     * @param string $domain
     */
    public static function resolveForInsert($conn, $ip, $domain)
    {
        $ipEsc     = cloak_db_escape($conn, $ip);
        $domainEsc = cloak_db_escape($conn, $domain);
        $sql       = "SELECT COUNT(*) AS `c` FROM `visitor_logs` WHERE `IP`='{$ipEsc}' AND `domain`='{$domainEsc}'";
        $count     = 0;
        if ($res = $conn->query($sql)) {
            $row = $res->fetch_assoc();
            $count = (int) ($row['c'] ?? 0);
            $res->free();
        }
        return $count + 1;
    }

    /**
     * @param array $logs cloak_write_log_db 结构
     */
    public static function mergeIntoLogs(array $logs, $conn)
    {
        if (!empty($logs['vtimes']) && (int) $logs['vtimes'] > 0) {
            return $logs;
        }
        $ip     = (string) ($logs['customers_ip'] ?? '');
        $domain = (string) ($logs['site_name'] ?? '');
        if ($ip !== '' && $domain !== '') {
            $logs['vtimes'] = self::resolveForInsert($conn, $ip, $domain);
        }
        return $logs;
    }
}
