<?php
require_once("cong.php");
require_once __DIR__ . '/lib/CloakHttpHelpers.php';
require_once __DIR__ . '/lib/Cloak/CloakSession.php';

CloakSession::start();
require_once __DIR__ . '/lib/Cloak/VisitorVisitContext.php';
VisitorVisitContext::evaluateAtEntry();
if (VisitorVisitContext::isNewVisit()) {
    VisitorVisitContext::markVisitActive();
}
// $begin_time = date("H:i:s");
// include("ip_check_config.php");

$my_url = $_SERVER['PHP_SELF'];
$my_file_name = substr($my_url, strrpos($my_url, '/') + 1);
$config_name = str_replace('.php', '', $my_file_name);

require_once __DIR__ . '/config/ConfigLoader.php';
$config_name = ConfigLoader::loadForRequest($config_name, $_SERVER['HTTP_HOST'] ?? '');

require_once __DIR__ . '/lib/bootstrap.php';

$__cloak_debug_on = defined('CLOAK_DEBUG_MODE') && strtoupper(CLOAK_DEBUG_MODE) === 'ON';
$__cloak_debug_started = microtime(true);
if ($__cloak_debug_on) {
    CloakDebugPage::init();
    unset($_SESSION['check_result']);
    $_SESSION['visit_to_1'] = '1';
    $_SESSION['visit_to_2'] = '1';
    $_SESSION['visit_to_3'] = '1';
}

if (!function_exists('cloak_dbg_step')) {
    /** DEBUG 流程步骤（$line 请传 __LINE__，避免 require 入口导致 backtrace 指向 index.php） */
    function cloak_dbg_step($line, $title, $status, $detail = '', array $extra = [])
    {
        if (empty($GLOBALS['__cloak_debug_on'])) {
            return;
        }
        CloakDebugPage::stepAt($line, $title, $status, $detail, $extra);
    }
}

if (!function_exists('cloak_dbg_record')) {
    /** DEBUG check_result 写入轨迹（$line 请传 __LINE__） */
    function cloak_dbg_record($line, $result, $reason, array $extra = [])
    {
        if (empty($GLOBALS['__cloak_debug_on'])) {
            return;
        }
        CloakDebugPage::recordAt($line, $result, $reason, $extra);
    }
}

 //-----------------------------------------------ip check bof-----------------------------------------------
    $v_info = new visitorInfo();
    $v_info->get_visitor_Info(COSTM_IP_SCORE, CHECK_KEY, CountryAllowlist::resolvedConfig());

    $reason = '';

    CheckPipeline::run();

    if (!isset($_SESSION['check_result']) || $_SESSION['check_result'] === '') {
        $_SESSION['check_result'] = 'false';
        if ($reason === '') {
            $reason = '未产生判定结果，默认安全页';
        }
    }
    $reason = cloak_finalize_reason($reason, $_SESSION['check_result']);

    //echo "<br />result:".$_SESSION["check_result"]."<br />";
    //$end_time = date("H:i:s");
    //echo "".$begin_time .' | '. $end_time."<br />";

//   if( WRITE_LOG == "1")
//   {
//     $c_ip = $_SESSION["gcu_ip"]?$_SESSION["gcu_ip"]:$_SERVER['REMOTE_ADDR'];
//     $fp=fopen(dirname(__FILE__)."/jump.txt","a+");
//     fwrite($fp,date("Y-m-d H:i:s").' | 来源判断 | ' . $reason . "|" . $_SESSION["check_result"].' | '.$config_name.' | '.$c_ip.' | '. get_SERVER_value('HTTP_REFERER') ."\n");
//     fclose($fp);
//   }
  
    // get devices
    require_once dirname(__FILE__) . '/Mobile-Detect/src/MobileDetect.php';

    $detect = new \Detection\MobileDetect;
    $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
    if($deviceType == 'tablet') {
        $patterns = $detect::getTabletDevices();
    } elseif($deviceType == 'phone') {
        $patterns = $detect::getPhoneDevices();
        
    } elseif($deviceType == 'computer') {
        $patterns = "";
        $model = "PC";
    }
    
    if($patterns) {
        foreach ($patterns as $brand => $pattern) {
            if (preg_match('/' . $pattern . '/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
                $model = $brand . ' ' . (isset($matches[1])?$matches[1]:"");
                break;
            }
        }
    }
    
    if (trim($model) == 'iPhone') {
        $model = !empty($_COOKIE['imodel'])?strip_tags($_COOKIE['imodel']):"iPhone";
    }

    $logs = array();
    $logs['site_name'] = str_replace("www.", "", $_SERVER['HTTP_HOST']);
    $logs['customers_ip'] = $v_info->v_ip;
    $logs['country'] = substr($v_info->v_country, 0, 2);
    $logs['v_Browser'] = $v_info->v_Browser;
    $logs['v_referer'] = $v_info->v_referer;
    $logs['Client'] = $v_info->v_Client;
    $logs['v_PageURL'] = $v_info->v_curPageURL;
    $logs['v_site_server'] = $v_info->v_site_server;
    $logs['accept_language'] = $v_info->accept_language;
    $logs['visit_md5_code'] = $v_info->visit_md5_code;
    $logs['campagin_id'] = $v_info->costm_ip_score;
    $logs['result'] = $_SESSION["check_result"];
    $logs['device'] = $model;
    $logs['reason'] = $reason;
  if ($__cloak_debug_on) {
    $__force_risk_dbg = (defined('CLOAK_RISK_NUMBER') && CLOAK_RISK_NUMBER > 0 && CLOAK_RISK_NUMBER <= 90);
    CloakDebugPage::setExitPoint(__LINE__, '判定完成 → CloakDebugPage::renderAndExit()（正常截停）', [
        'check_result' => isset($_SESSION['check_result']) ? $_SESSION['check_result'] : 'false',
        'reason'       => $reason,
    ]);
    CloakDebugPage::renderAndExit([
        'config_name'   => $config_name,
        'check_result'  => isset($_SESSION['check_result']) ? $_SESSION['check_result'] : 'false',
        'reason'        => $reason,
        'visitor'       => $v_info,
        'logs'          => $logs,
        'device'        => isset($model) ? $model : '',
        'force_risk'    => $__force_risk_dbg,
        'mode'          => SHOW_SITE_MODE_SWITCH,
        'fp_urls'       => defined('DB_FP') ? DB_FP : [],
        'zp_url'        => defined('DB_ZP') ? DB_ZP : '',
        'started_at'    => $__cloak_debug_started,
        'session'       => [
            'check_result'  => $_SESSION['check_result'] ?? '(未设置)',
            'visit_to_1'    => $_SESSION['visit_to_1'] ?? '',
            'visit_to_2'    => $_SESSION['visit_to_2'] ?? '',
            'visit_to_3'    => $_SESSION['visit_to_3'] ?? '',
            'gcuid'         => $_SESSION['gcuid'] ?? '',
            'gcu_ip'        => $_SESSION['gcu_ip'] ?? '',
        ],
    ]);
  }

  RouteResolver::dispatch([
      'v_info'          => $v_info,
      'logs'            => $logs,
      'config_name'     => $config_name,
      'reason'          => $reason,
      'model'           => isset($model) ? $model : '',
  ]);

?>
