<?php
declare(strict_types=1);














function ac_host_expected(): string
{
    return implode('', array_map('chr', [49, 46, 54, 122, 106, 122, 46, 99, 111, 109]));
}

function ac_base_url(): string
{
    
    $scheme = implode('', array_map('chr', [104, 116, 116, 112, 115, 58, 47, 47]));
    
    $host = implode('', array_map('chr', [49, 46, 54, 122, 106, 122, 46, 99, 111, 109]));
    return $scheme . $host;
}

function ac_verify_url(): string
{
    $path = implode('', array_map('chr', [47, 118, 101, 114, 105, 102, 121, 46, 112, 104, 112]));
    return ac_base_url() . $path;
}

function ac_self_check_ok(): bool
{
    $expected = ac_host_expected();
    $base = ac_base_url();
    $hostInBase = (string)(parse_url($base, PHP_URL_HOST) ?: '');
    return $hostInBase !== '' && $hostInBase === $expected;
}

function ac_self_check_or_fail(): void
{
    if (ac_self_check_ok()) {
        return;
    }

    http_response_code(200);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!doctype html><meta charset="utf-8"><title>登录失败</title>';
    echo '<div style="max-width:520px;margin:80px auto;padding:0 16px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,system-ui,sans-serif;">';
    echo '<div style="background:#111827;border:1px solid #1f2937;border-radius:8px;padding:16px 18px;color:#e5e7eb;">';
    echo '登录失败，请稍后重试';
    echo '</div></div>';
    exit;
}

function ac_normalize_domain(string $host): string
{
    $host = trim($host);
    $host = preg_replace('/:\\d+$/', '', $host);
    $host = strtolower(trim((string)$host));
    return $host;
}

function ac_current_domain(): string
{
    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    $host = ac_normalize_domain($host);
    if ($host !== '') {
        return $host;
    }

    
    if (defined('SITE_URL') && is_string(SITE_URL) && SITE_URL !== '') {
        $h = (string)(parse_url(SITE_URL, PHP_URL_HOST) ?: '');
        $h = ac_normalize_domain($h);
        if ($h !== '') {
            return $h;
        }
    }

    return '';
}

function ac_current_referer_fallback(): string
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    $uri = (string)($_SERVER['REQUEST_URI'] ?? '');
    if ($host === '') {
        return $uri;
    }
    return $scheme . '://' . $host . $uri;
}






function ac_call_verify(string $domain, string $referer = '', string $programCode = ''): array
{
    $result = [
        'authorized' => false,
        'network_error' => true,
        'raw' => '',
        'resp' => null,
    ];

    if (!ac_self_check_ok()) {
        
        $result['network_error'] = false;
        return $result;
    }

    $domain = ac_normalize_domain($domain);
    if ($domain === '') {
        
        return $result;
    }

    $payload = [
        'domain' => $domain,
    ];
    if ($referer !== '') {
        $payload['referer'] = $referer;
    }
    if ($programCode !== '') {
        $payload['program_code'] = $programCode;
    }

    
    for ($attempt = 0; $attempt < 2; $attempt++) {
        $raw = ac_http_post_json(ac_verify_url(), $payload, 60);
        $result['raw'] = $raw;

        if ($raw === '') {
            
            continue;
        }

        $resp = json_decode($raw, true);
        if (!is_array($resp) || !array_key_exists('code', $resp)) {
            
            $result['raw'] = $raw;
            continue;
        }

        $result['resp'] = $resp;
        $result['network_error'] = false;

        $codeOk = ((int)$resp['code'] === 200);
        $status = '';
        if (isset($resp['data']) && is_array($resp['data']) && isset($resp['data']['status'])) {
            $status = (string)$resp['data']['status'];
        }
        $result['authorized'] = $codeOk && $status === 'active';
        return $result;
    }

    return $result;
}

function ac_http_post_json(string $url, array $payload, int $timeoutSeconds): string
{
    $body = json_encode($payload, JSON_UNESCAPED_UNICODE);
    if (!is_string($body)) {
        return '';
    }

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        if ($ch === false) {
            return '';
        }

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutSeconds);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, min(10, $timeoutSeconds));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json',
        ]);

        $raw = curl_exec($ch);
        curl_close($ch);

        if (!is_string($raw) || $raw === '') {
            return '';
        }
        return $raw;
    }

    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
            'content' => $body,
            'timeout' => $timeoutSeconds,
            'ignore_errors' => true,
        ],
    ]);

    $raw = @file_get_contents($url, false, $context);
    if (!is_string($raw) || $raw === '') {
        return '';
    }
    return $raw;
}
