<?php
/**
 * 用户编辑/添加
**/
include("../includes/common.php");
$title='用户管理';
include './head.php';

if($islogin==1){
}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

$action = isset($_GET['action']) ? $_GET['action'] : 'add';
$uid = isset($_GET['uid']) ? intval($_GET['uid']) : 0;

// 获取用户数据（编辑模式）
$user = null;
if($action == 'edit' && $uid > 0){
    $user = $DB->getRow("SELECT * FROM pre_user WHERE uid='{$uid}'");
    if(!$user){
        exit("<script language='javascript'>alert('用户不存在');history.go(-1);</script>");
    }
}

// 处理表单提交
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $username = trim($_POST['username']);
    $nickname = trim($_POST['nickname']);
    $password = $_POST['password'];
    $email = trim($_POST['email']);
    $level = intval($_POST['level']);
    $u_storage_quota = intval($_POST['u_storage_quota']);
    $u_traffic_quota = intval($_POST['u_traffic_quota']);
    $enable = isset($_POST['enable']) ? 1 : 0;
    
    if(empty($username)){
        exit("<script language='javascript'>alert('用户名不能为空');history.go(-1);</script>");
    }
    
    if($action == 'add'){
        // 检查用户名是否已存在
        $exists = $DB->getRow("SELECT uid FROM pre_user WHERE username='{$username}'");
        if($exists){
            exit("<script language='javascript'>alert('用户名已存在');history.go(-1);</script>");
        }
        
        if(empty($password)){
            exit("<script language='javascript'>alert('密码不能为空');history.go(-1);</script>");
        }
        
        $pwd = password_hash($password, PASSWORD_DEFAULT);
        $addtime = date("Y-m-d H:i:s");
        $lasttime = date("Y-m-d H:i:s");
        $regip = real_ip($conf['ip_type']?$conf['ip_type']:0);
        
        $sql = "INSERT INTO pre_user (username, nickname, password, email, level, u_storage_quota, u_traffic_quota, enable, addtime, lasttime, regip) 
                VALUES ('{$username}', '{$nickname}', '{$pwd}', '{$email}', '{$level}', '{$u_storage_quota}', '{$u_traffic_quota}', '{$enable}', '{$addtime}', '{$lasttime}', '{$regip}')";
        
        if($DB->exec($sql)){
            exit("<script language='javascript'>alert('添加用户成功');window.location.href='./user.php';</script>");
        }else{
            exit("<script language='javascript'>alert('添加用户失败');history.go(-1);</script>");
        }
    }else{
        // 编辑模式
        $sql = "UPDATE pre_user SET 
                nickname='{$nickname}', 
                email='{$email}', 
                level='{$level}', 
                u_storage_quota='{$u_storage_quota}', 
                u_traffic_quota='{$u_traffic_quota}', 
                enable='{$enable}'";
        
        // 如果填写了密码则更新密码
        if(!empty($password)){
            $pwd = password_hash($password, PASSWORD_DEFAULT);
            $sql .= ", password='{$pwd}'";
        }
        
        $sql .= " WHERE uid='{$uid}'";
        
        if($DB->exec($sql)){
            exit("<script language='javascript'>alert('修改用户成功');window.location.href='./user.php';</script>");
        }else{
            exit("<script language='javascript'>alert('修改用户失败或数据未变更');window.location.href='./user.php';</script>");
        }
    }
}

// 格式化字节数为MB/GB显示
function formatBytesToMB($bytes){
    if($bytes <= 0) return 0;
    return round($bytes / 1048576, 2);
}
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon">
                <i class="fa <?php echo $action=='add'?'fa-user-plus':'fa-user-edit'; ?>"></i>
            </div>
            <h1><?php echo $action=='add'?'添加用户':'编辑用户'; ?></h1>
        </div>
        <div class="page-actions">
            <a href="./user.php" class="btn btn-secondary"><i class="fa fa-arrow-left"></i> 返回列表</a>
        </div>
    </div>

    <!-- 编辑表单 -->
    <div class="form-section">
        <form method="post" action="" class="edit-form">
            <div class="form-grid">
                <!-- 基本信息 -->
                <div class="form-card">
                    <div class="form-card-header">
                        <i class="fa fa-user"></i>
                        <span>基本信息</span>
                    </div>
                    <div class="form-card-body">
                        <div class="form-group">
                            <label for="username">用户名 <span class="required">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" 
                                   value="<?php echo $user?$user['username']:''; ?>" 
                                   <?php echo $action=='edit'?'readonly':''; ?> required>
                            <?php if($action=='edit'): ?>
                            <small class="form-text text-muted">用户名不可修改</small>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group">
                            <label for="nickname">昵称</label>
                            <input type="text" class="form-control" id="nickname" name="nickname" 
                                   value="<?php echo $user?htmlspecialchars($user['nickname']):''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="email">邮箱</label>
                            <input type="email" class="form-control" id="email" name="email" 
                                   value="<?php echo $user?htmlspecialchars($user['email']):''; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="password">密码 <?php echo $action=='add'?'<span class="required">*</span>':'<small>(不填则不修改)</small>'; ?></label>
                            <input type="password" class="form-control" id="password" name="password" 
                                   <?php echo $action=='add'?'required':''; ?>>
                        </div>
                        
                        <div class="form-group">
                            <label class="checkbox-label">
                                <input type="checkbox" name="enable" value="1" 
                                       <?php echo ($user && $user['enable']==1) || !$user?'checked':''; ?>>
                                <span>账号状态正常</span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- 配额设置 -->
                <div class="form-card">
                    <div class="form-card-header">
                        <i class="fa fa-database"></i>
                        <span>配额设置</span>
                    </div>
                    <div class="form-card-body">
                        <div class="form-group">
                            <label for="level">用户等级</label>
                            <input type="number" class="form-control" id="level" name="level" 
                                   value="<?php echo $user?$user['level']:'0'; ?>" min="0">
                            <small class="form-text text-muted">0 为普通用户</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="u_storage_quota">额外存储配额 (MB)</label>
                            <input type="number" class="form-control" id="u_storage_quota" name="u_storage_quota" 
                                   value="<?php echo $user?formatBytesToMB($user['u_storage_quota']):'0'; ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label for="u_traffic_quota">额外流量配额 (MB)</label>
                            <input type="number" class="form-control" id="u_traffic_quota" name="u_traffic_quota" 
                                   value="<?php echo $user?formatBytesToMB($user['u_traffic_quota']):'0'; ?>" min="0">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 提交按钮 -->
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> <?php echo $action=='add'?'添加用户':'保存修改'; ?>
                </button>
                <a href="./user.php" class="btn btn-secondary">
                    <i class="fa fa-times"></i> 取消
                </a>
            </div>
        </form>
    </div>
</div>

<style>
.form-section {
    margin-top: 20px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
}

.form-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.form-card-header {
    padding: 15px 20px;
    border-bottom: 1px solid #e5e7eb;
    font-weight: 600;
    color: #374151;
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-card-header i {
    color: #3b82f6;
}

.form-card-body {
    padding: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #374151;
}

.form-group label .required {
    color: #ef4444;
}

.form-control {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s;
}

.form-control:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-control[readonly] {
    background-color: #f3f4f6;
    cursor: not-allowed;
}

.form-text {
    display: block;
    margin-top: 6px;
    font-size: 12px;
}

.text-muted {
    color: #6b7280;
}

.checkbox-label {
    display: flex !important;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.form-actions {
    margin-top: 30px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    display: flex;
    gap: 12px;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
}

.btn-primary {
    background: #3b82f6;
    color: #fff;
}

.btn-primary:hover {
    background: #2563eb;
}

.btn-secondary {
    background: #6b7280;
    color: #fff;
}

.btn-secondary:hover {
    background: #4b5563;
}

@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .btn {
        justify-content: center;
    }
}
</style>

</body>
</html>
