<?php
// 兜底：如果服务器将所有请求路由到 index.php，则对 /admin/* 的所有请求进行就地加载
// 防止后台页面被首页覆盖导致“返回首页”。
if (isset($_SERVER['REQUEST_URI'])) {
    $reqPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '';

    // 优先处理 user_article 直达请求，避免后续逻辑将其覆盖为首页
    if (preg_match('#^/user_article/(\d+)\.php$#', $reqPath)) {
        $_GET['id'] = (int)preg_replace('#^/user_article/(\d+)\.php$#', '$1', $reqPath);
        $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
        require __DIR__ . '/user_article/detail.php';
        return;
    }
    // 兼容直接访问 detail.php?id=XX 的形式
    if ($reqPath === '/user_article/detail.php') {
        $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
        require __DIR__ . '/user_article/detail.php';
        return;
    }

    // 兼容部分服务器或重写规则将原始路径改写为 /index.php，并通过查询参数或环境变量传递原始路径
    if (strpos($reqPath, '/admin/') !== 0) {
        $altPaths = [];
        // 常见查询参数名：q、path、route、r、s、p、_url
        foreach (['q','path','route','r','s','p','_url'] as $k) {
            if (!empty($_GET[$k])) {
                $v = '/' . ltrim((string)$_GET[$k], '/');
                $altPaths[] = parse_url($v, PHP_URL_PATH) ?: $v;
            }
        }
        // 常见的服务器环境变量：ORIG_PATH_INFO、REDIRECT_URL、HTTP_X_REWRITE_URL、HTTP_X_ORIGINAL_URI、PATH_INFO
        foreach (['ORIG_PATH_INFO','REDIRECT_URL','HTTP_X_REWRITE_URL','HTTP_X_ORIGINAL_URI','PATH_INFO'] as $ek) {
            if (!empty($_SERVER[$ek])) {
                $v = (string)$_SERVER[$ek];
                // 统一为以 / 开头的路径
                if ($v !== '' && $v[0] !== '/') { $v = '/' . $v; }
                $altPaths[] = parse_url($v, PHP_URL_PATH) ?: $v;
            }
        }
        foreach ($altPaths as $ap) {
            if (strpos($ap, '/admin/') === 0) { $reqPath = $ap; break; }
            if (strpos($ap, 'admin/') === 0) { $reqPath = '/' . $ap; break; }
            if (preg_match('#^/user_article/(\d+)\.php$#', $ap)) {
                $_GET['id'] = (int)preg_replace('#^/user_article/(\d+)\.php$#', '$1', $ap);
                $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
                require __DIR__ . '/user_article/detail.php';
                return;
            }
            if ($ap === '/user_article/detail.php') {
                $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
                require __DIR__ . '/user_article/detail.php';
                return;
            }
        }
    }
    if (strpos($reqPath, '/admin/') === 0) {
        $adminTarget = __DIR__ . $reqPath;
        // 仅当目标文件存在时才加载，避免包含目录或不存在文件
        if (is_file($adminTarget)) {
            require $adminTarget;
            return; // 结束当前脚本，避免继续渲染首页
        }
        // 如果是目录访问（如 /admin/），则默认跳到后台首页
        if (rtrim($reqPath, '/') === '/admin') {
            require __DIR__ . '/admin/index.php';
            return;
        }
    }
    // 兜底：如果原始路径就是 user_article 请求，直接加载详情页
    if (preg_match('#^/user_article/(\d+)\.php$#', $reqPath)) {
        $_GET['id'] = (int)preg_replace('#^/user_article/(\d+)\.php$#', '$1', $reqPath);
        $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
        require __DIR__ . '/user_article/detail.php';
        return;
    }
    if ($reqPath === '/user_article/detail.php') {
        $_SERVER['SCRIPT_NAME'] = '/user_article/detail.php';
        require __DIR__ . '/user_article/detail.php';
        return;
    }
}

// 在页面最开始尝试启动会话，保证 header/footer 能读取登录状态，且不会触发警告
if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
    session_start();
}

$config = require __DIR__ . '/config/database.php';
try {
    $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=%s', $config['host'], $config['port'], $config['database'], $config['charset']);
    $pdo = new PDO($dsn, $config['username'], $config['password'], $config['options']);
} catch (Throwable $e) {
    $pdo = null;
}

function ensureUrl($u) {
    $u = trim($u ?? '');
    if ($u === '') return '';
    if (preg_match('#^https?://#i', $u)) return $u;
    return (substr($u, 0, 1) === '/') ? $u : ('/' . $u);
}
// 选择 uploads 目录中的最新资源作为兜底
function latestUpload($subdir) {
    try {
        $dir = __DIR__ . '/uploads/' . trim($subdir, '/');
        $files = glob($dir . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
        if ($files && count($files) > 0) {
            usort($files, function($a, $b) { return filemtime($b) <=> filemtime($a); });
            return '/uploads/' . trim($subdir, '/') . '/' . basename($files[0]);
        }
    } catch (Throwable $e) { /* ignore */ }
    return '';
}

// 站点 logo、banner 与套餐封面兜底路径
$defaultBanner = latestUpload('banners');
if ($defaultBanner === '') { $defaultBanner = '/images/banner.png'; }
$siteLogo = latestUpload('medias');
if ($siteLogo === '') { $siteLogo = '/images/icon.png'; }
$defaultPackageCover = latestUpload('packages');
if ($defaultPackageCover === '') { $defaultPackageCover = '/images/setMeal.png'; }

// 中文注释：加载套餐列表（严格使用 items_json，不再关联旧媒体表）
$packages = [];
if ($pdo) {
    try {
        // 直接读取 packages 表，列表字段用于展示；媒体数以 JSON 长度为准
        $sql = "SELECT p.*,
                       CASE
                           WHEN p.items_json IS NULL OR JSON_TYPE(p.items_json) = 'NULL' THEN 0
                           ELSE JSON_LENGTH(p.items_json)
                       END AS json_media_count
                FROM packages p
                WHERE p.status = 1
                ORDER BY p.sort_order DESC, p.updated_at DESC";
        $packages = $pdo->query($sql)->fetchAll();
    } catch (Throwable $e) {
        $packages = [];
    }
}
$banners = [];
if ($pdo) {
    try {
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $isMobile = (bool)preg_match('/Mobile|Android|iPhone|iPad|iPod|Windows Phone|MQQBrowser/i', $ua);
        $deviceTarget = $isMobile ? 'mobile' : 'pc';

        // 兼容缺少 device 字段的旧表结构：如果不存在该字段，则不做分端筛选
        $hasDeviceColumn = false;
        try {
            $chk = $pdo->query("SHOW COLUMNS FROM banners LIKE 'device'");
            $hasDeviceColumn = $chk && $chk->rowCount() > 0;
        } catch (Throwable $ie) {
            $hasDeviceColumn = false;
        }

        if ($hasDeviceColumn) {
            $sql = 'SELECT id, title, image_url, link_url, device FROM banners WHERE status = 1 AND (device = "both" OR device = :device) ORDER BY sort_order DESC, updated_at DESC';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':device' => $deviceTarget]);
            $banners = $stmt->fetchAll();
        } else {
            // 无 device 字段时，默认返回全部作为兜底
            $sql = 'SELECT id, title, image_url, link_url FROM banners WHERE status = 1 ORDER BY sort_order DESC, updated_at DESC';
            $stmt = $pdo->query($sql);
            $rows = $stmt ? $stmt->fetchAll() : [];
            // 为后续模板渲染补齐 device 字段（视为 both）
            $banners = array_map(function($r) {
                if (!isset($r['device'])) { $r['device'] = 'both'; }
                return $r;
            }, $rows ?: []);
        }
    } catch (Throwable $e) {
        $banners = [];
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php
    // 从站点配置注入 SEO
    require_once __DIR__ . '/config/config.php';
    $siteName = trim(getSiteConfig('site_name')) ?: '我要久久发';
    $seoTitle = trim(getSiteConfig('seo_title'));
    $seoKeywords = trim(getSiteConfig('seo_keywords'));
    $seoDescription = trim(getSiteConfig('seo_description'));
    ?>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>我要久久发-软文发布_媒体发稿_新闻广告投放平台</title>
    <meta name="keywords" content="软文发布，媒体发稿，广告投放"/>
    <meta name="description" content="我要久久发(www.woyao998.com) 2009年起步,16年老品牌媒体投稿平台,企业和个人发布各种广告信息,客户覆盖全国,推广效果好,助您业绩翻倍。"/>
    <meta name="color-scheme" content="light dark"/>
    <link
            href="fontawesome/css/all.min.css"
            rel="stylesheet"
    />
    <link
            rel="stylesheet"
            href="/libs/swiper/swiper-bundle.min.css"
    />

    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/header.css">
    <link rel="stylesheet" href="css/footer.css">
    <link rel="icon" href="/images/icon.ico" type="image/png">

    <script src="/libs/jquery-3.7.1.min.js"></script>
    <script src="/libs/swiper/swiper-bundle.min.js"></script>
    <script src="js/header.js"></script>

<style>
        /* 统一轮播容器高度为自适应（不限制高度） */
        .swiper { height: auto !important; }

        .set-meal-item {
            background: #FFFFFF;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 0 15px #e0e0e0;
            margin-bottom: 15px;
        }

        .set-meal-item .set-meal-detail {
            display: flex;
            padding: 20px;
        }

        .set-meal-item .set-meal-detail .set-meal-icon {
            flex: 1;
            padding-right: 30px;
        }

        .set-meal-item .set-meal-detail .set-meal-icon img {
            width: 100%;
            border-radius: 4px;
        }

        .set-meal-item .set-meal-detail .set-meal-msg {
            flex: 2.5;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title {
            display: grid;
            grid-template-columns: auto 1fr auto;
            gap: 12px;
            align-items: center;
            margin-bottom: 10px;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .title-txt {
            font-size: 20px;
            color: var(--main);
            font-weight: bold;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link {
            justify-self: end;
            font-size: 14px;
            color: #343434;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link .link-text {
            display: block;
            font-weight: bold;
            position: relative;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link .link-text .hover {
            color: var(--main);
            position: absolute;
            right: 10px;
            opacity: 0;
            transition: opacity .3s, right .3s;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link .link-text span {
            transition: color .3s;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link .sub-link-text {
            display: block;
            font-size: 12px;
            border-top: 1px solid var(--main);
            transition: color .3s;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link:hover .link-text span,
        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link:hover .sub-link-text {
            color: var(--main);
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link:hover .link-text .hover {
            right: 0;
            opacity: 1;
        }


        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-content {
            line-height: 20px;
            font-size: 15px;
            color: #343434;
            border-left: 2px solid var(--main);
            padding-left: 20px;
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-content p {
            margin: 2px 0;
        }

        /* 中文注释：套餐参数行采用弹性布局，媒体数与投放订单数同列显示 */
        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params {
            color: #343434;
            font-size: 15px;
            margin-top: 40px;
            display: flex;            /* 弹性容器 */
            align-items: center;      /* 垂直居中对齐 */
            gap: 30px;                /* 两个参数之间的间距 */
            flex-wrap: nowrap;        /* 强制同一行显示 */
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params .param {
            margin-right: 0;          /* 由 gap 控制间距 */
            display: flex;            /* 参数项为弹性子项 */
            align-items: baseline;    /* 标签与数值基线对齐 */
            gap: 8px;                 /* 标签与数值之间的间距 */
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params .param label {
            display: inline-block;
            margin-right: 0;          /* 由子项 gap 控制 */
        }

        .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params .param-value {
            font-size: 18px;
            font-weight: 600;
            color: var(--sub-main);
        }

        .set-meal-item .set-meal-detail .set-meal-price {
            color: #343434;
            flex: .8;
        }

        .set-meal-price-content {
            background: url(images/bm_09.jpg);
            width: 179px;
            height: 120px;
            text-align: center;
            display: flex;
            flex-direction: column; /* 竖向排列 */
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中（需有高度） */
            margin: 20px auto;
        }

            .set-meal-item .set-meal-detail .set-meal-price .current-price {
            font-size: 18px;
            color: #FFFFFF;
            display: block;
            line-height: 42px;
        }

            .set-meal-item .set-meal-detail .set-meal-price .old-price {
            font-size: 14px;
            color: #f2c2b5;
            font-style: italic;
            text-decoration: line-through;
            margin-bottom: 10px;
        }

        .set-meal-item .set-meal-detail .set-meal-price .buy {
            height: 50px;
            line-height: 50px;
            font-size: 16px;
            border-top: 1px solid #f1af8c;
            font-weight: 200;
            background: none;
            color: #fff;
            width: 100%;
            cursor: pointer;
        }

        .set-meal-item .meta-list {
            background: #fdf3f0;
            margin: 0;
            padding: 20px 30px;
            list-style: none;
            display: grid;
            grid-template-columns: repeat(4, 1fr); /* 指定 3 列 */
            gap: 8px; /* 间距 */
            width: 100%;
        }

        .set-meal-item .meta-list li {
            color: #343434;
            font-weight: bold;
            font-size: 15px;
            padding: 5px 0;
            position: relative;
            cursor: pointer;
        }

        .set-meal-item .meta-list li a:before {
            content: '查看 | VIEW';
            color: #FFFFFF;
            text-align: center;
            font-size: 12px;
            line-height: 28px;
            position: absolute;
            top: 0;
            left: 0;
            display: block;
            width: 0;
            height: 100%;
            background: rgb(252, 111, 69, .5);
            backdrop-filter: blur(3px);
            overflow: hidden;
            border-radius: 4px;
            transition: width .3s;
        }

        .set-meal-item .meta-list li a:hover:before {
            width: 100%;
        }

        .set-meal-item .meta-list li i {
            color: var(--ok);
            margin-right: 10px;
        }

        @media (min-width: 1024px) {
        }

        .plan-title h3 {
            margin: 0;
        }


        .plan-price small {
            font-size: 12px;
            color: var(--muted);
            font-weight: 400;
        }


        .feat svg {
            width: 18px;
            height: 18px;
            opacity: 0.9;
        }

        .acc-item.open .acc-bd {
            display: block;
        }

        @media (max-width: 640px) {


            /* 适配移动端安全区域与整体留白 */
            body {
                padding-bottom: max(16px, env(safe-area-inset-bottom));
            }

            .container {
                padding: 0 12px;
            }

            /* Banner（移动端）：统一与全局样式，隐藏溢出避免右侧空白 */
            .swiper-content {
                border-radius: 0;
                overflow: hidden;
            }

            /* 每屏仅显示一个滑块，防止看到下一张 */
            .swiper-slide {
                overflow: hidden;
                width: 100% !important;
                flex: 0 0 100% !important;
            }

            /* 包裹图片的链接也需限制尺寸与溢出 */
            .swiper-slide a {
                display: block;
                width: 100%;
                height: auto;
                overflow: hidden;
            }

            /* 移动端轮播图片：宽度100%，左右边距为0 */
            .swiper-slide img {
                width: 100%;
                height: auto;
                display: block;
                border-radius: 0;
                margin-left: 0;
                margin-right: 0;
            }

            /* 移动端：仅隐藏首页套餐图片；价格与“立即购买”需展示 */
            .set-meal-icon {
                display: none !important;
            }
            /* 明确在移动端展示价格区块 */
            .set-meal-price {
                display: block !important;
            }

            /* 套餐卡片整体更精致的外观与间距 */
            .set-meal-item {
                border-radius: 12px;
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.06);
            }

            .set-meal-item .set-meal-detail {
                flex-direction: column;
                padding: 16px;
                gap: 12px;
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title {
                display: flex;
                justify-content: space-between; /* 标题靠左，详情按钮靠右 */
                align-items: center;
                gap: 8px;
                margin-bottom: 14px;
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .title-txt {
                font-size: 18px;
                line-height: 1.3;
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link {
                justify-self: end;
                font-size: 13px;
                color: var(--main);
                padding: 6px 10px;
                border: 1px solid var(--main);
                border-radius: 999px;
                -webkit-tap-highlight-color: transparent;
            }

            /* 移动端隐藏副标题英文，减少噪点 */
            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-title .detail-link .sub-link-text {
                display: none;
            }

            .set-meal-item .set-meal-detail .set-meal-icon {
                padding-right: 0;
                margin-bottom: 12px;
            }

            .set-meal-item .set-meal-detail .set-meal-icon img {
                border-radius: 10px;
                height: 180px;
                object-fit: cover;
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-content {
                font-size: 14px;
                line-height: 22px;
                padding-left: 12px;
            }

            /* 中文注释：移动端套餐参数保持单行且不换行，数字字号稍微缩小 */
            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params {
                display: flex;
                gap: 10px;
                margin: 16px 0 20px;
                text-align: left;
                flex-wrap: nowrap;        /* 禁止自动换行 */
                white-space: nowrap;      /* 文本不换行 */
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params .param {
                margin-right: 0;
                flex: 1;
            }

            .set-meal-item .set-meal-detail .set-meal-msg .set-meal-params .param-value {
                align-self: center;
                font-size: 18px;          /* 数字稍微缩小 */
                font-weight: 600;
            }

            .set-meal-item .set-meal-detail .set-meal-price {
                border-top: 1px solid var(--main);
                padding-top: 12px;
                padding-bottom: 20px;
            }

            .set-meal-price-content {
                width: 100%;
                height: auto;
                margin: 12px 0 0 0;
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                gap: 0;
                background: #fff;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                overflow: hidden;
                min-height: 46px;
                padding: 0 0 0 12px;
            }

            .set-meal-item .set-meal-detail .set-meal-price .buy {
                border-top: none;
                border-radius: 0 12px 12px 0;
                background: var(--main);
                color: #fff;
                padding: 0 18px;
                height: auto;
                line-height: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: none;
                width: auto;
                margin-left: auto;
                align-self: stretch;
                font-weight: 600;
                font-size: 16px;
            }

            .set-meal-item .set-meal-detail .set-meal-price .current-price {
                font-size: 18px;
                color: #111827;
                display: inline-block;
                line-height: 1;
                font-weight: 700;
                padding: 10px 0;
                white-space: nowrap;
                font-feature-settings: "tnum" 1, "lnum" 1;
            }
            .set-meal-item .set-meal-detail .set-meal-price .old-price {
                font-size: 14px;
                color: #9aa4b2;
                text-decoration: line-through;
                margin-left: 10px;
                font-style: normal;
                margin-bottom: 0;
                white-space: nowrap;
            }

            /* 媒体列表改为更易点按的卡片样式 */
            /* 移动端：首页不显示媒体模块 */
            .set-meal-item .meta-list {
                display: none !important;
            }

            .set-meal-item .meta-list li {
                font-size: 14px;
                background: #fff;
                border-radius: 8px;
                padding: 10px 12px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            }

            .set-meal-item .meta-list li a {
                display: block;
                color: inherit;
                text-decoration: none;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            /* 移动端禁用 hover 覆盖层，避免误触 */
            .set-meal-item .meta-list li a:before {
                display: none;
            }

            /* 基础的触控反馈与可访问性可视焦点 */
            .set-meal-title .detail-link:active {
                transform: translateY(1px);
            }

            .set-meal-title .detail-link:focus-visible {
                outline: 2px solid var(--main);
                outline-offset: 2px;
            }

        }

    </style>
</head>
<body>
<?php include __DIR__ . '/includes/site-header.php'; ?>

<main id="main">
    <section class="swiper">
        <div class="swiper-content" style="position:relative;">
            <!-- Additional required wrapper -->
            <div class="swiper-wrapper">
                <?php if (!empty($banners)) { foreach ($banners as $b) { 
                    $img = ensureUrl($b['image_url'] ?? '');
                    $link = trim($b['link_url'] ?? '');
                    $title = htmlspecialchars($b['title'] ?? '', ENT_QUOTES);
                ?>
                <div class="swiper-slide">
                    <?php if ($link !== '') { ?>
                    <a href="<?php echo htmlspecialchars($link, ENT_QUOTES); ?>" target="_blank" rel="noopener">
                        <img src="<?php echo htmlspecialchars($img ?: $defaultBanner, ENT_QUOTES); ?>" alt="<?php echo $title; ?>">
                    </a>
                    <?php } else { ?>
                    <img src="<?php echo htmlspecialchars($img ?: $defaultBanner, ENT_QUOTES); ?>" alt="<?php echo $title; ?>">
                    <?php } ?>
                </div>
                <?php } } else { ?>
                <div class="swiper-slide">
                    <img src="<?php echo htmlspecialchars($defaultBanner, ENT_QUOTES); ?>" alt="">
                </div>
                <?php } ?>
            </div>
            <?php if (function_exists('isMobile') ? !isMobile() : true) { ?>
            <?php if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])): ?>
            <div class="swiper-overlay" style="position:absolute;left:0;right:0;top:0;bottom:0;z-index:5;pointer-events:none;">
              <div class="container auth-wrap" style="height:100%;min-height:0;max-height:none;padding:0;display:flex;justify-content:flex-end;align-items:center;">
                <div class="form-card auth-card" style="pointer-events:auto;margin:0;">
                  <h2 style="margin:0 0 10px 0;font-weight:700;color:#333;font-size:18px;">HI，欢迎进入我要久久发广告平台</h2>
                  <div style="display:flex;gap:12px;border-bottom:1px solid #e9edf5;margin-bottom:12px;font-size:12px;">注册会员享超低发稿,开启海量推广
                  </div>
                  <form method="post" action="/user-login.php" style="display:flex;flex-direction:column;gap:10px;">
                     <div>
                       <input type="text" name="username" placeholder="请输入手机号/用户名" class="form-control" style="width:100%;background:#fff;color:#333;">
                     </div>
                     <div>
                       <input type="password" name="password" placeholder="请输入密码(长度6-15)" class="form-control" style="width:100%;background:#fff;color:#333;">
                     </div>
                    <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">
                      <label style="display:flex;align-items:center;gap:6px;color:#666;font-size:12px;"><input type="checkbox" name="remember" value="1"> 记住密码</label>
                      <a href="/user-login.php" style="color:#999;font-size:12px;text-decoration:none;">忘记密码？</a>
                    </div>
                    <div style="display:flex;gap:10px;align-items:center;">
                      <button type="submit" class="btn-primary" style="background:var(--main);height:44px;font-size:16px;width:auto !important;flex:1;">立即登录</button>
                      <a href="/user-register.php" class="btn-brand" style="width:auto !important;flex:1;">注册</a>
                    </div>
                </form>
              </div>
              </div>
            </div>
            <?php else: ?>
            <?php
              $userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
              $remainSum = 0;
              $publishedCount = 0;
              $pendingCount = 0;
              if ($pdo && $userId > 0) {
                  try {
                      require_once __DIR__ . '/includes/PackageQuota.php';
                      $map = PackageQuota::remainingProductQuotas($pdo, $userId);
                      foreach ($map as $k => $v) { $remainSum += max(0, (int)$v); }
                  } catch (Throwable $e) { $remainSum = 0; }
                  try {
                      require_once __DIR__ . '/includes/Database.php';
                      require_once __DIR__ . '/includes/UserCenter.php';
                      $counts = UserCenter::articleStatusCounts(Database::getInstance(), $userId);
                      $publishedCount = max(0, (int)($counts['published'] ?? 0));
                      $pendingCount = max(0, (int)($counts['pending'] ?? 0));
                  } catch (Throwable $e) {
                      $publishedCount = 0; $pendingCount = 0;
                  }
              }
              $uname = htmlspecialchars((string)($_SESSION['user_username'] ?? ''), ENT_QUOTES);
            ?>
            <div class="swiper-overlay" style="position:absolute;left:0;right:0;top:0;bottom:0;z-index:5;pointer-events:none;">
              <div class="container auth-wrap" style="height:100%;min-height:0;max-height:none;padding:0;display:flex;justify-content:flex-end;align-items:center;">
                <div class="form-card auth-card" style="pointer-events:auto;margin:0;">
                  <div class="account-card">
                    <div class="account-header">
                      <div class="avatar"><img src="/uploads/coin.png" alt="avatar"></div>
                      <div class="meta">
                        <div class="name">账号名</div>
                        <div class="extra">
                          <div><?php echo $uname !== '' ? $uname : '会员'; ?></div>
                        </div>
                      </div>
                    </div>
                    <div class="stats-cards">
                      <div class="stats-card"><div class="value"><?php echo (int)$remainSum; ?></div><div class="label">套餐剩余额度</div></div>
                      <div class="stats-card"><div class="value"><?php echo (int)$publishedCount; ?></div><div class="label">已发布广告</div></div>
                      <div class="stats-card"><div class="value"><?php echo (int)$pendingCount; ?></div><div class="label">审核中广告</div></div>
                    </div>
                    <div class="actions">
                      <a href="/index.php#packages" class="btn-brand"><i class="fa-solid fa-cart-shopping"></i> 购买套餐</a>
                      <a href="/user-center.php" class="btn-secondary-alt"><i class="fa-solid fa-user"></i> 个人中心</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <?php endif; ?>
            <?php } ?>
        </div>
    </section>
    <div style="height:8px;"></div>
    <section id="packages" class="container">
        <?php if (empty($packages)): ?>
            <div class="set-meal-item" style="padding:20px;">
                <div class="text-muted">暂无套餐数据</div>
            </div>
        <?php else: foreach ($packages as $pkg): ?>
            <?php
                $cover = !empty($pkg['cover_url']) ? ensureUrl($pkg['cover_url']) : $defaultPackageCover;
                $currentPrice = ($pkg['sale_price'] !== null && $pkg['sale_price'] !== '') ? (float)$pkg['sale_price'] : (float)$pkg['price'];
                $oldPrice = ($pkg['sale_price'] !== null && $pkg['sale_price'] !== '') ? (float)$pkg['price'] : null;
                // 中文注释：首页不再渲染媒体列表，严格按照 items_json 控制；此处仅计算数量
                $jsonMediaCount = isset($pkg['json_media_count']) ? intval($pkg['json_media_count']) : 0;
            ?>
            <div class="set-meal-item">
                <div class="set-meal-detail">
                    <div class="set-meal-icon">
                        <a href="set-meal-detail.php?id=<?php echo intval($pkg['id']); ?>"><img src="<?php echo htmlspecialchars($cover); ?>" alt=""/>
            </a></div>
                    <div class="set-meal-msg">
                        <div class="set-meal-title">
                            <span class="title-txt"><a href="set-meal-detail.php?id=<?php echo intval($pkg['id']); ?>"><?php echo htmlspecialchars($pkg['name']); ?></a></span>
                            <a class="detail-link" href="set-meal-detail.php?id=<?php echo intval($pkg['id']); ?>">
                                <span class="link-text">
                                    <span>详情</span>
                                    <i class="fa-solid fa-angles-right" style="margin-left: 10px;"></i>
                                    <i class="fa-solid fa-angles-right hover"></i>
                                </span>
                                <span class="sub-link-text">DETAIL</span>
                            </a>
                        </div>
                        <div class="set-meal-content">
                            <p><label>推荐理由：</label><?php echo htmlspecialchars($pkg['recommend_reason'] ?? ''); ?></p>
                            <p><label>投放规则：</label><?php echo htmlspecialchars($pkg['delivery_rule'] ?? ''); ?></p>
                        </div>
                        <div class="set-meal-params">
                            <span class="param"><label>媒体数：</label><span class="param-value"><?php echo $jsonMediaCount; ?></span></span>
                            <span class="param"><label>投放订单数：</label><span class="param-value"><?php echo intval($pkg['order_count'] ?? 0); ?></span></span>
                        </div>
                    </div>
                    <div class="set-meal-price">
                        <div class="set-meal-price-content">
                            <span class="current-price">￥<?php echo number_format($currentPrice, 2); ?></span>
                            <?php if ($oldPrice !== null): ?><span class="old-price">￥<?php echo number_format($oldPrice, 2); ?></span><?php endif; ?>
                            <span class="buy" role="button" aria-label="立即购买">立即购买</span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; endif; ?>
    </section>

    <?php include __DIR__ . '/includes/site-footer.php'; ?>

</main>

    <script>
      // 支付逻辑统一由 js/pay-modal.js 绑定与处理
    </script>
</body>
</html>
