<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();

if (!isset($_SESSION['member_id']) || empty($_SESSION['member_id'])) {
    header('Location: /member/login.php');
    exit;
}

require_once dirname(__FILE__) . '/../core/db/db.php';
require_once dirname(__FILE__) . '/../core/lib/common.php';

$db = \Core\Db\DB::getInstance();
$member = $db->fetch(
    "SELECT m.*, g.group_name FROM {$db->table('member')} m LEFT JOIN {$db->table('member_group')} g ON m.group_id = g.id WHERE m.id = ?",
    [$_SESSION['member_id']]
);

if (!$member) {
    session_destroy();
    header('Location: /member/login.php');
    exit;
}

$page = preg_replace('/[^a-z0-9_]/i', '', (string) ($_GET['page'] ?? 'dashboard'));
if ($page === '') {
    $page = 'dashboard';
}
$pageFile = dirname(__FILE__) . '/pages/' . $page . '.php';

if ($page === 'messages' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireMemberCsrfToken();
    cmsEnsureMemberMessageTable($db);
    $messageAction = trim((string) ($_POST['message_action'] ?? ''));
    if ($messageAction === 'read') {
        $db->update('member_message', ['is_read' => 1, 'read_time' => time()], 'id = ? AND to_id = ?', [intval($_POST['id'] ?? 0), intval($member['id'])]);
    } elseif ($messageAction === 'read_all') {
        $db->update('member_message', ['is_read' => 1, 'read_time' => time()], 'to_id = ? AND is_read = 0', [intval($member['id'])]);
    }
    $messagePage = max(1, intval($_POST['p'] ?? 1));
    header('Location: /member/index.php?page=messages&p=' . $messagePage);
    exit;
}

$navSections = [
    [
        'title' => '会员服务',
        'items' => [
            ['page' => 'favorites', 'label' => '我的收藏'],
            ['page' => 'reviews', 'label' => '我的评价'],
            ['page' => 'messages', 'label' => '站内消息'],
        ],
    ],
    [
        'title' => '账户管理',
        'items' => [
            ['page' => 'profile', 'label' => '个人资料'],
            ['page' => 'password', 'label' => '修改密码'],
        ],
    ],
    [
        'title' => '我的内容',
        'items' => [
            ['page' => 'guestbook', 'label' => '我的留言'],
            ['page' => 'mydownload', 'label' => '我的下载'],
        ],
    ],
    [
        'title' => '订单中心',
        'items' => [
            ['page' => 'myorder', 'label' => '我的订单'],
            ['page' => 'cart', 'label' => '购物车'],
            ['page' => 'finance', 'label' => '财务明细'],
            ['page' => 'refund', 'label' => '我的售后'],
            ['page' => 'recharge', 'label' => '账户充值'],
        ],
    ],
    [
        'title' => '投稿中心',
        'items' => [
            ['page' => 'contribute', 'label' => '投稿列表'],
            ['page' => 'contribute_add', 'label' => '我要投稿'],
        ],
    ],
    [
        'title' => '收货管理',
        'items' => [
            ['page' => 'address', 'label' => '收货地址'],
        ],
    ],
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员中心 - 芋头CMS</title>
    <link rel="stylesheet" href="/public/css/site.css">
    <link rel="stylesheet" href="/public/css/member.css">
    <style>
        .member-link-button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 10px 14px;
            border-radius: 10px;
            background: #10b981;
            color: #fff;
            text-decoration: none;
            font-size: 13px;
        }
        .member-summary {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 12px;
            margin-top: 16px;
        }
        .member-summary .item {
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            padding: 14px 12px;
            text-align: center;
        }
        .member-summary .value {
            font-size: 20px;
            font-weight: 700;
            color: #111827;
        }
        .member-summary .label {
            margin-top: 6px;
            color: #6b7280;
            font-size: 12px;
        }
        @media (max-width: 768px) {
            .member-summary {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }
    </style>
</head>
<body>
    <header class="member-topbar">
        <div class="topbar-inner">
            <div class="topbar-logo">
                <span class="logo-text">会员中心</span>
            </div>
            <nav class="topbar-nav">
                <a href="/" class="nav-link">网站首页</a>
                <a href="/member/logout.php" class="nav-link logout">退出登录</a>
            </nav>
        </div>
    </header>

    <div class="member-wrapper">
        <aside class="member-sidebar" id="sidebar">
            <div class="sidebar-header">
                <div class="user-card">
                    <div class="user-avatar">
                        <?php if (!empty($member['avatar'])): ?>
                            <img src="<?php echo htmlspecialchars($member['avatar']); ?>" alt="avatar">
                        <?php else: ?>
                            <span><?php echo htmlspecialchars(mb_substr((string) ($member['nickname'] ?: $member['username']), 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <div class="user-name"><?php echo htmlspecialchars($member['nickname'] ?: $member['username']); ?></div>
                        <div class="user-group"><?php echo htmlspecialchars($member['group_name'] ?? '普通会员'); ?></div>
                    </div>
                </div>
                <div class="member-summary">
                    <div class="item">
                        <div class="value"><?php echo intval($member['points'] ?? 0); ?></div>
                        <div class="label">积分</div>
                    </div>
                    <div class="item">
                        <div class="value">￥<?php echo number_format((float) ($member['balance'] ?? 0), 2); ?></div>
                        <div class="label">余额</div>
                    </div>
                    <div class="item">
                        <a href="?page=recharge" class="member-link-button">去充值</a>
                        <div class="label">账户充值</div>
                    </div>
                </div>
            </div>

            <nav class="sidebar-nav">
                <?php foreach ($navSections as $section): ?>
                    <div class="nav-section">
                        <div class="nav-section-title"><?php echo htmlspecialchars($section['title']); ?></div>
                        <?php foreach ($section['items'] as $item): ?>
                            <a href="?page=<?php echo urlencode($item['page']); ?>" class="nav-item <?php echo $page === $item['page'] ? 'active' : ''; ?>">
                                <span><?php echo htmlspecialchars($item['label']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </nav>
        </aside>

        <main class="member-main">
            <?php
            if (is_file($pageFile)) {
                include $pageFile;
            } else {
                echo '<div class="page-empty">页面不存在</div>';
            }
            ?>
        </main>
    </div>

    <script>
    document.getElementById('sidebar').addEventListener('click', function (event) {
        var target = event.target;
        if (target.classList && target.classList.contains('nav-section-title')) {
            target.parentNode.classList.toggle('collapsed');
        }
    });
    </script>
</body>
</html>
