<?php
// 短链公开入口使用独立 Session 名，避免继承用户端/后台 PHPSESSID。
$hasShortLinkParam = array_key_exists('u', $_GET);
$shortCodeCandidate = isset($_GET['u']) ? trim($_GET['u']) : '';
$oauthOrderId = '';
if (!empty($_GET['code']) && isset($_GET['state'])) {
    $oauthState = trim($_GET['state']);
    if (preg_match('/^TF[A-Za-z0-9]+$/', $oauthState)) {
        $oauthOrderId = $oauthState;
    } elseif ($shortCodeCandidate === '') {
        $shortCodeCandidate = $oauthState;
    }
}
$isShortLinkCandidate = preg_match('/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{4}$/', $shortCodeCandidate);
if (($isShortLinkCandidate && (isset($_GET['fire']) || !empty($_GET['code']))) || $oauthOrderId !== '') {
    $sessionSeed = $isShortLinkCandidate ? $shortCodeCandidate : $oauthOrderId;
    $isHttps = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
        || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])[0])) === 'https');
    session_name('SL' . substr(hash('sha256', $sessionSeed), 0, 12));
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'secure' => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

require_once dirname(__FILE__) . '/api/config.php';
require_once dirname(__FILE__) . '/api/db.php';
require_once dirname(__FILE__) . '/includes/access_guard.php';
AccessGuard::run();
require_once dirname(__FILE__) . '/api/SysConfig.php';
require_once dirname(__FILE__) . '/api/ShortLink.php';

// 未安装时跳转到安装程序
if (!INSTALLED) {
    header('Location: ./pages/install.php');
    exit;
}

if ($hasShortLinkParam && !$isShortLinkCandidate) {
    http_response_code(404);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>';
    exit;
}

// 授权回跳可能带订单号 state
if ($oauthOrderId !== '') {
    $db = Database::getInstance()->getPdo();
    $stmt = $db->prepare("SELECT order_id FROM `orders` WHERE order_id = ? LIMIT 1");
    $stmt->execute([$oauthOrderId]);
    $orderId = (string)($stmt->fetchColumn() ?: '');
    if ($orderId === '') {
        http_response_code(404);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>';
        exit;
    }
    unset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
    define('SHORT_LINK_CONTEXT', true);
    $publicShortCode = ShortLink::ensureForOrder($db, $orderId);
    $_GET['order'] = $orderId;
    include dirname(__FILE__) . '/pages/receive.php';
    exit;
}

// /?u=Ab3K&fire=1：按短码直接渲染收款页，地址栏不跳回长链接。
if ($isShortLinkCandidate) {
    $db = Database::getInstance()->getPdo();
    $orderId = ShortLink::findOrderId($db, $shortCodeCandidate);
    if ($orderId === '') {
        http_response_code(404);
        header('Content-Type: text/html; charset=utf-8');
        echo '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>';
        exit;
    }

    unset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
    define('SHORT_LINK_CONTEXT', true);
    $publicShortCode = $shortCodeCandidate;
    $_GET['u'] = $shortCodeCandidate;
    $_GET['order'] = $orderId;
    include dirname(__FILE__) . '/pages/receive.php';
    exit;
}

// 读取落地页开关
$landingEnabled = SysConfig::get('landing_enabled', '1');

if ($landingEnabled === '1') {
    // 启用落地页：直接显示引导页面
    include dirname(__FILE__) . '/pages/landing.php';
    exit;
}

// 未启用落地页：保持原角色跳转逻辑
if (!empty($_SESSION['role']) && $_SESSION['role'] === 'admin') {
    header('Location: ./pages/admin.php');
} else {
    header('Location: ./pages/index.php');
}
exit;
