<?php
/**
 * 真实页 URL 解析（DB_FP 轮询 + KEEP_PARAMS）
 */
class FpUrlHelper
{
    /**
     * 解析本次应跳转的真实页 URL（与 FpPageRenderer / f_check 逻辑一致）
     *
     * @param string $configName check_config 配置名（如 index）
     * @param bool   $mutateNt   是否更新 nt.txt / nt Cookie（f_check 通过时为 true）
     * @return array{url:string,now_url:int}
     */
    public static function resolve($configName, $mutateNt = true)
    {
        $all_fp_url = DB_FP;
        $num        = is_array($all_fp_url) ? count($all_fp_url) : 1;
        $now_url    = 0;

        if ($num < 1) {
            return ['url' => is_string($all_fp_url) ? (string) $all_fp_url : '', 'now_url' => 0];
        }

        if (isset($_COOKIE['nt']) && is_numeric($_COOKIE['nt'])) {
            $ntCookie = (int) $_COOKIE['nt'];
            if ($ntCookie >= 1 && $ntCookie <= $num) {
                $now_url = $ntCookie;
            }
        }

        if (!$now_url) {
            $match = false;
            $nt    = 2;
            $ot    = false;
            $handle = @fopen('nt.txt', 'r');
            if ($handle) {
                while (!feof($handle)) {
                    $buffer = fgets($handle);
                    $bb     = explode('||||||', $buffer);
                    if (trim($bb[0] ?? '') !== $configName) {
                        continue;
                    }
                    if (!isset($bb[1]) || trim($bb[1]) === '') {
                        continue;
                    }
                    $match = true;
                    $ot    = trim($bb[1]);
                    $nt    = trim($bb[1]);
                    break;
                }
                fclose($handle);
            }

            if ($match) {
                if ((int) $nt <= $num) {
                    $now_url = max(1, (int) $ot);
                    $nt      = (int) $nt + 1;
                } else {
                    $now_url = 1;
                    $nt      = 2;
                }
            } else {
                $now_url = 1;
                $nt      = 2;
            }

            if ($mutateNt) {
                write_nt_list($configName, $nt, $ot);
            }
        }

        if (is_array($all_fp_url)) {
            $idx     = max(0, min(max(1, (int) $now_url) - 1, $num - 1));
            $fp_url  = $all_fp_url[$idx];
            $now_url = $idx + 1;
        } else {
            $fp_url = (string) $all_fp_url;
        }

        if ($mutateNt) {
            setCrossDomainCookie('nt', $now_url, 3600 * 24 + time());
        }

        if (defined('KEEP_PARAMS') && KEEP_PARAMS === 'ON' && !empty($_GET) && $fp_url !== '') {
            $params   = http_build_query($_GET);
            $urlParts = parse_url($fp_url);
            if (isset($urlParts['query'])) {
                $fp_url .= '&' . $params;
            } else {
                $fp_url .= '?' . $params;
            }
        }

        return ['url' => (string) $fp_url, 'now_url' => (int) $now_url];
    }

    /**
     * 真实页 / 安全页兜底 URL（DB_FP 首项，否则 DB_ZP）
     */
    public static function fallbackUrl()
    {
        $all = DB_FP;
        if (is_array($all)) {
            foreach ($all as $u) {
                if (trim((string) $u) !== '') {
                    return (string) $u;
                }
            }
        } elseif (is_string($all) && trim($all) !== '') {
            return $all;
        }
        return defined('DB_ZP') ? (string) DB_ZP : '';
    }
}
