<?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();
require_once dirname(__FILE__) . '/../core/db/db.php';

// 如果已登录，跳转到会员中心
if (isset($_SESSION['member_id']) && !empty($_SESSION['member_id'])) {
    header('Location: /member/index.php');
    exit;
}

$error = '';
$success = false;

// 处理注册提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $password2 = trim($_POST['password2'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $captcha = trim($_POST['captcha'] ?? '');
    
    // 验证验证码
    if (empty($captcha) || !isset($_SESSION['captcha']) || strtolower($captcha) !== strtolower($_SESSION['captcha'])) {
        $error = '验证码错误';
    } elseif (empty($username) || empty($password)) {
        $error = '用户名和密码不能为空';
    } elseif (strlen($username) < 4 || strlen($username) > 20) {
        $error = '用户名长度必须在4-20个字符之间';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $error = '用户名只能包含字母、数字和下划线';
    } elseif ($password !== $password2) {
        $error = '两次输入的密码不一致';
    } elseif (strlen($password) < 6) {
        $error = '密码长度不能少于6位';
    } else {
        try {
            $db = \Core\Db\DB::getInstance();
            
            // 检查用户名是否已存在
            $exists = $db->fetch("SELECT id FROM {$db->table('member')} WHERE username = ?", [$username]);
            if ($exists) {
                $error = '用户名已被注册';
            } else {
                // 获取默认会员组
                $defaultGroup = $db->fetch("SELECT id FROM {$db->table('member_group')} WHERE is_default = 1 LIMIT 1");
                $groupId = $defaultGroup ? $defaultGroup['id'] : 1;
                
                // 创建会员
                $db->insert('member', [
                    'username' => $username,
                    'password' => password_hash($password, PASSWORD_DEFAULT),
                    'email' => $email,
                    'phone' => $phone,
                    'group_id' => $groupId,
                    'reg_ip' => getClientIp(),
                    'reg_time' => time(),
                    'is_enabled' => 1
                ]);
                
                $success = true;
                
            }
        } catch (Exception $e) {
            $error = '系统错误，请稍后再试';
        }
    }
}

function getClientIp() {
    $ip = '0.0.0.0';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
?>
<!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">
    <style>
    body { background: linear-gradient(135deg, #0d3b66 0%, #1a5f8a 100%); }
    .member-register { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
    .register-box { background: #fff; border-radius: 12px; padding: 40px; width: 100%; max-width: 450px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); }
    .register-header { text-align: center; margin-bottom: 30px; }
    .register-header h1 { font-size: 24px; color: #0d3b66; margin-bottom: 5px; }
    .register-header p { color: #888; font-size: 13px; }
    .register-form .form-group { margin-bottom: 18px; }
    .register-form label { display: block; margin-bottom: 6px; color: #333; font-weight: 500; font-size: 14px; }
    .register-form input { width: 100%; padding: 12px 15px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
    .register-form input:focus { outline: none; border-color: #00d2d3; }
    .error-message { background: #f8d7da; color: #721c24; padding: 12px 15px; border-radius: 6px; margin-bottom: 20px; font-size: 13px; }
    .success-message { background: #d4edda; color: #155724; padding: 12px 15px; border-radius: 6px; margin-bottom: 20px; font-size: 13px; }
    .btn-register { width: 100%; padding: 14px; background: linear-gradient(135deg, #00d2d3, #007991); color: #fff; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: background 0.3s; }
    .btn-register:hover { background: linear-gradient(135deg, #00b8b9, #006070); }
    .register-footer { margin-top: 20px; text-align: center; font-size: 13px; color: #999; }
    .register-footer a { color: #00d2d3; text-decoration: none; margin: 0 10px; }
    .agreement { font-size: 12px; color: #999; margin-top: 15px; text-align: center; }
    .agreement a { color: #00d2d3; }
    </style>
</head>
<body>
    <div class="member-register">
        <div class="register-box">
            <div class="register-header">
                <h1>会员注册</h1>
                <p>加入企业CMS会员中心</p>
            </div>
            
            <?php if ($error): ?>
            <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <div class="success-message">
                <p>✓ 注册成功！</p>
                <p style="margin-top:10px;font-size:13px;">请牢记您的用户名和密码</p>
            </div>
            <div class="register-footer">
                <a href="/member/login.php">立即登录</a>
                <a href="/">返回首页</a>
            </div>
            <?php else: ?>
            
            <form method="post" class="register-form">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" name="username" placeholder="4-20位字母、数字或下划线" required>
                </div>
                
                <div class="form-group">
                    <label>密码</label>
                    <input type="password" name="password" placeholder="至少6位" required>
                </div>
                
                <div class="form-group">
                    <label>确认密码</label>
                    <input type="password" name="password2" placeholder="再次输入密码" required>
                </div>
                
                <div class="form-group">
                    <label>邮箱（选填）</label>
                    <input type="email" name="email" placeholder="用于找回密码">
                </div>
                
                <div class="form-group">
                    <label>手机号（选填）</label>
                    <input type="text" name="phone" placeholder="用于联系">
                </div>
                
                <div class="form-group">
                    <label>验证码</label>
                    <div style="display:flex;gap:10px;">
                        <input type="text" name="captcha" placeholder="验证码" required style="flex:1;">
                        <img src="/admin/captcha.php" alt="验证码" style="height:42px;border-radius:6px;cursor:pointer;" onclick="this.src='/admin/captcha.php?'+Math.random();">
                    </div>
                </div>
                
                <button type="submit" class="btn-register">注 册</button>
            </form>
            
            <div class="register-footer">
                <a href="/member/login.php">已有账号？立即登录</a>
                <a href="/">返回首页</a>
            </div>
            
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
