<?php
/**
 * 主站入口：未登录或卡密失效则跳转登录页，否则输出主站内容
 * 防止通过直接访问 index.html 或禁用 JS 绕过登录
 */
require_once __DIR__ . '/auth/bootstrap.php';

if (!isUserLoggedIn()) {
    header('Location: login.html');
    exit;
}

$user_id = (int) $_SESSION['user_id'];
$stmt = $pdo->prepare('SELECT card_key_id FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$user_id]);
$user = $stmt->fetch();
if (!$user) {
    unset($_SESSION['user_id'], $_SESSION['username']);
    header('Location: login.html');
    exit;
}
if (!empty($user['card_key_id'])) {
    $stmt = $pdo->prepare('SELECT id, paused, expires_at FROM card_keys WHERE id = ? LIMIT 1');
    $stmt->execute([$user['card_key_id']]);
    $card = $stmt->fetch();
    if (!$card || !empty($card['paused']) || ($card['expires_at'] !== null && strtotime($card['expires_at']) < time())) {
        unset($_SESSION['user_id'], $_SESSION['username']);
        header('Location: login.html');
        exit;
    }
}

// 已登录且卡密有效，输出主站
$mainFile = __DIR__ . '/index.html';
if (!is_file($mainFile)) {
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>错误</title></head><body><p>主站文件缺失。</p></body></html>';
    exit;
}
header('Content-Type: text/html; charset=utf-8');
readfile($mainFile);
