<?php require_once 'auth.php';
$pageTitle = "系统权限管理";
$activeTab = $_GET['tab'] ?? 'role';
$conn = $connMonitor;

// ========== 角色操作逻辑 ==========
// 保存角色
if ($_POST['act'] == "save_role") {
    $roleName = trim($_POST['role_name']);
    $roleId = intval($_POST['role_id'] ?? 0);
    $pages = $_POST['page_perm'] ?? [];
    if (empty($roleName)) {
        echo "<script>alert('角色名称不能为空');location.href='system_manage.php?tab=role';</script>";
        exit;
    }
    if ($roleId == 0) {
        mysqli_query($conn, "INSERT INTO sys_role(role_name) VALUES('$roleName')");
        $roleId = mysqli_insert_id($conn);
    } else {
        mysqli_query($conn, "UPDATE sys_role SET role_name='$roleName' WHERE id=$roleId");
        mysqli_query($conn, "DELETE FROM sys_role_permission WHERE role_id=$roleId");
    }
    foreach ($pages as $page) {
        $page = mysqli_real_escape_string($conn, $page);
        mysqli_query($conn, "INSERT INTO sys_role_permission(role_id,page_key) VALUES($roleId,'$page')");
    }
    echo "<script>alert('角色保存成功');location.href='system_manage.php?tab=role';</script>";
    exit;
}
// 删除角色
if (!empty($_GET['del_role'])) {
    $delId = intval($_GET['del_role']);
    mysqli_query($conn, "DELETE FROM sys_role_permission WHERE role_id=$delId");
    mysqli_query($conn, "DELETE FROM sys_role WHERE id=$delId");
    header("Location: system_manage.php?tab=role");
    exit;
}
// 编辑角色数据
$editRole = ['id'=>0,'role_name'=>'','perms'=>[]];
if (!empty($_GET['edit_role'])) {
    $eid = intval($_GET['edit_role']);
    $er = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM sys_role WHERE id=$eid"));
    if ($er) {
        $editRole = $er;
        $permRes = mysqli_query($conn, "SELECT page_key FROM sys_role_permission WHERE role_id=$eid");
        while ($p = mysqli_fetch_assoc($permRes)) $editRole['perms'][] = $p['page_key'];
    }
}
// 角色列表
$roleList = [];
$roleRes = mysqli_query($conn, "SELECT * FROM sys_role ORDER BY id DESC");
while ($r = mysqli_fetch_assoc($roleRes)) $roleList[] = $r;

// ========== 用户操作逻辑 ==========
// 保存用户
if ($_POST['act'] == "save_user") {
    $uid = intval($_POST['user_id'] ?? 0);
    $username = trim($_POST['username']);
    $realName = trim($_POST['real_name']);
    $roleId = intval($_POST['role_id']);
    $pwd = trim($_POST['password']);
    $status = intval($_POST['status']);
    if (empty($username) || empty($realName) || $roleId == 0) {
        echo "<script>alert('账号、姓名、角色不能为空');location.href='system_manage.php?tab=user';</script>";
        exit;
    }
    if ($uid == 0) {
        if (empty($pwd)) {
            echo "<script>alert('新建用户必须填写密码');location.href='system_manage.php?tab=user';</script>";
            exit;
        }
        $pwdMd5 = md5($pwd);
        mysqli_query($conn, "INSERT INTO sys_user(username,password,real_name,role_id,status,is_admin) VALUES('$username','$pwdMd5','$realName',$roleId,$status,0)");
    } else {
        $updateSql = "UPDATE sys_user SET username='$username',real_name='$realName',role_id=$roleId,status=$status WHERE id=$uid";
        if (!empty($pwd)) {
            $pwdMd5 = md5($pwd);
            $updateSql .= ",password='$pwdMd5'";
        }
        mysqli_query($conn, $updateSql);
    }
    echo "<script>alert('用户保存成功');location.href='system_manage.php?tab=user';</script>";
    exit;
}
// 删除用户
if (!empty($_GET['del_user'])) {
    $delId = intval($_GET['del_user']);
    mysqli_query($conn, "DELETE FROM sys_user_msg WHERE user_id=$delId");
    mysqli_query($conn, "DELETE FROM sys_user WHERE id=$delId");
    header("Location: system_manage.php?tab=user");
    exit;
}
// 用户下拉角色选项
$roleOptionHtml = "";
$roleDropRes = mysqli_query($conn, "SELECT id,role_name FROM sys_role");
while ($r = mysqli_fetch_assoc($roleDropRes)) {
    $roleOptionHtml .= "<option value='{$r['id']}'>{$r['role_name']}</option>";
}
// 用户列表
$userList = [];
$uRes = mysqli_query($conn, "SELECT u.*,r.role_name FROM sys_user u LEFT JOIN sys_role r ON u.role_id=r.id ORDER BY u.id DESC");
while ($u = mysqli_fetch_assoc($uRes)) $userList[] = $u;
// 编辑用户数据
$editUser = ['id'=>0,'username'=>'','real_name'=>'','role_id'=>0,'status'=>1];
if (!empty($_GET['edit_user'])) {
    $eid = intval($_GET['edit_user']);
    $eu = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM sys_user WHERE id=$eid"));
    if ($eu) $editUser = $eu;
}

// 全部页面权限清单
$allPagePerms = [
    ['key'=>'dashboard','name'=>'告警总览'],
    ['key'=>'work_order','name'=>'工单系统'],
    ['key'=>'disk','name'=>'磁盘容量'],
    ['key'=>'history_query','name'=>'历史查询'],
    ['key'=>'smtp_config','name'=>'消息通知配置'],
    ['key'=>'system_manage','name'=>'系统权限管理'],
];
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="<?php echo $t['html_lang']; ?>">
<head>
    <meta charset="utf-8">
    <title><?php echo $pageTitle; ?></title>
    <link rel="stylesheet" href="/static/css/font-awesome.min.css">
    <script src="/static/js/jquery.min.js"></script>
    <style>
        *{box-sizing:border-box;margin:0;padding:0}
        body{ background:#f8fafc; font-family:"Inter","PingFang SC","Microsoft YaHei",system-ui,sans-serif; color:#1e293b; line-height:1.55; display:flex; flex-direction:column; height:100vh; overflow:hidden; }
        .wrap-main{display:flex;flex:1;overflow:hidden;}
        /* 侧边栏 */
        .sidebar{ width:240px; background:#152c5b; color:#e2e8f0; flex-shrink:0; overflow-y:auto; }
        .sidebar-brand{ padding:30px 24px; border-bottom:1px solid rgba(255,255,255,0.06); }
        .sidebar-brand-en{ font-size:20px; font-weight:600; color:#fff; }
        .sidebar-brand-cn{ font-size:12px; color:#a5b4fc; margin-top:6px; }
        .sidebar-menu{padding:20px 0;}
        .menu-title{ padding:10px 24px 6px; font-size:11px; color:#94a3b8; text-transform:uppercase; }
        .menu-item{ display:flex; align-items:center; gap:12px; padding:13px 24px; cursor:pointer; font-size:14px; color:#cbd5e1; }
        .menu-item i{ width:20px; text-align:center; }
        .menu-item.active{ background:rgba(59,130,246,0.15); color:#fff; border-left:4px solid #3b82f6; }
        .menu-item:hover:not(.active){ background:rgba(255,255,255,0.06); color:#fff; }
        /* 顶部头部 */
        .main-content{ flex:1; overflow-y:auto; display:flex; flex-direction:column; }
        .header{ background:#fff; border-bottom:1px solid #e2e8f0; padding:20px 40px; display:flex; justify-content:space-between; align-items:center; }
        .header-left{display:flex;align-items:center;gap:14px;}
        .header-brand-en{ font-size:24px; font-weight:700; color:#152c5b; }
        .header-brand-cn{font-size:13px;color:#64748b;}
        .header-right{display:flex;align-items:center;gap:20px;font-size:14px;}
        .user-info,.time-info,.lang-box{display:flex;align-items:center;gap:6px;color:#475569;}
        .lang-box select{padding:4px 8px;border:1px solid #cbd5e1;border-radius:6px;}
        .msg-badge{ position:relative; cursor:pointer; }
        .msg-badge span{ position:absolute; top:-6px; right:-6px; background:#ef4444; color:#fff; font-size:10px; border-radius:99px; min-width:16px; height:16px; text-align:center; line-height:16px; padding:0 4px; }
        /* 按钮通用 */
        .btn-base{ border:none; padding:10px 24px; border-radius:999px; cursor:pointer; font-size:14px; font-weight:500; display:flex; align-items:center; gap:8px; transition:all 0.2s ease; }
        .btn-outline{background:#fff;color:#152c5b;border:1px solid #cbd5e1;}
        .btn-outline:hover{background:#f7f8fc;}
        .btn-primary{background:linear-gradient(135deg,#1d4ed8,#2563eb);color:#fff;box-shadow:0 6px 18px rgba(37,99,235,.25);}
        .btn-primary:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(37,99,235,.32);}
        .container{padding:36px 40px;flex:1;}
        /* 卡片 */
        .base-card{background:#fff;border-radius:18px;padding:36px;border:1px solid #e5e7eb;box-shadow:0 1px 3px rgba(0,0,0,.04),0 8px 24px rgba(15,23,42,.04);max-width:900px;}
        .title-wrap{display:flex;align-items:center;gap:12px;font-size:17px;font-weight:600;color:#152c5b;margin-bottom:26px;padding-bottom:16px;border-bottom:1px solid #f1f5f9;}
        .title-wrap i{color:#2563eb;}
        /* Tab切换栏 */
        .tab-wrap{display:flex;gap:4px;margin-bottom:24px;border-bottom:1px solid #e2e8f0;}
        .tab-item{padding:12px 24px;cursor:pointer;border-bottom:3px solid transparent;color:#64748b;font-weight:500;}
        .tab-item.active{color:#2563eb;border-bottom-color:#2563eb;}
        .tab-content{display:none;}
        .tab-content.show{display:block;}
        /* 表单统一样式 */
        .form-row{margin-bottom:22px;}
        .form-row label{display:block;margin-bottom:8px;font-size:13px;font-weight:600;color:#334155;letter-spacing:.2px;}
        .form-row input,.form-row select{width:360px;height:46px;padding:0 16px;border:1px solid #d6dce5;border-radius:10px;font-size:14px;transition:all .2s ease;}
        .form-row input:hover,.form-row select:hover{border-color:#94a3b8;}
        .form-row input:focus,.form-row select:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.12);}
        /* 权限多选组 */
        .check-group{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:10px;}
        .check-item{display:flex;align-items:center;gap:8px;padding:10px 12px;border:1px solid #e2e8f0;border-radius:10px;}
        /* 表格 */
        table{width:100%;border-collapse:collapse;margin-top:20px;}
        th,td{border:1px solid #e2e8f0;padding:14px;text-align:left;}
        th{background:#f8fafc;font-weight:600;}
        .operate a{margin-right:12px;color:#2563eb;}
        .operate a.del{color:#ef4444;}
        /* 数字输入框去除箭头 */
        input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}
        input[type="number"]{-moz-appearance:textfield;}
    </style>
</head>
<body>
<div class="wrap-main">
    <div class="sidebar">
        <div class="sidebar-brand">
            <div class="sidebar-brand-en">Advantest</div>
            <div class="sidebar-brand-cn"><?php echo $pageTitle; ?></div>
        </div>
        <div class="sidebar-menu">
            <div class="menu-title"><?php echo $t['monitor_panel']; ?></div>
            <div class="menu-item" onclick="location.href='dashboard.php'"><i class="fa fa-line-chart"></i><span><?php echo $t['alert_overview']; ?></span></div>
            <div class="menu-item" onclick="location.href='work_order.php'"><i class="fa fa-ticket"></i><span><?php echo $t['work_order_mgr']; ?></span></div>
            <div class="menu-title"><?php echo $t['quick_link']; ?></div>
            <?php foreach ($sidebarLinkList as $link): ?>
            <div class="menu-item" onclick="window.open('<?php echo htmlspecialchars($link['url']); ?>','_blank')"><i class="fa fa-external-link"></i><span><?php echo htmlspecialchars($link['name']); ?></span></div>
            <?php endforeach; ?>
            <div class="menu-title"><?php echo $t['system_manage']; ?></div>
            <div class="menu-item" onclick="location.href='smtp_config.php'"><i class="fa fa-bell"></i><span><?php echo $t['notify_config']; ?></span></div>
            <div class="menu-item active"><i class="fa fa-cogs"></i><span><?php echo $pageTitle; ?></span></div>
        </div>
    </div>
    <div class="main-content">
        <div class="header">
            <div class="header-left">
                <div>
                    <div class="header-brand-en">Advantest</div>
                    <div class="header-brand-cn"><?php echo $pageTitle; ?></div>
                </div>
            </div>
            <div class="header-right">
                <span class="msg-badge" onclick="location.href='work_order.php'">
                    <i class="fa fa-bell-o"></i>
                    <?php if($unreadMsgCount>0):?><span><?php echo $unreadMsgCount; ?></span><?php endif;?>
                </span>
                <span class="user-info"><i class="fa fa-user-circle"></i><?php echo $t['current_user']; ?><?php echo $userName; ?></span>
                <span class="time-info"><i class="fa fa-clock-o"></i><span id="nowTime">--</span></span>
                <div class="lang-box">
                    <span><?php echo $t['lang_text']; ?></span>
                    <select id="langSwitch">
                        <option value="zh" <?php echo $currentLang=='zh'?'selected':''; ?>>中文</option>
                        <option value="en" <?php echo $currentLang=='en'?'selected':''; ?>>EN</option>
                    </select>
                </div>
                <button class="btn-base btn-outline" onclick="location.reload()"><i class="fa fa-refresh"></i><?php echo $t['refresh_all']; ?></button>
                <button class="btn-base btn-primary" onclick="location.href='logout.php'"><i class="fa fa-sign-out"></i><?php echo $t['logout']; ?></button>
            </div>
        </div>
        <div class="container">
            <div class="base-card">
                <div class="title-wrap"><i class="fa fa-cogs"></i><?php echo $pageTitle; ?></div>
                <!-- Tab切换栏 -->
                <div class="tab-wrap">
                    <div class="tab-item <?php echo $activeTab=='role'?'active':''; ?>" data-tab="role">角色管理</div>
                    <div class="tab-item <?php echo $activeTab=='user'?'active':''; ?>" data-tab="user">用户管理</div>
                </div>

                <!-- 模块1：角色管理 -->
                <div class="tab-content <?php echo $activeTab=='role'?'show':''; ?>" id="tab-role">
                    <form method="post">
                        <input type="hidden" name="act" value="save_role">
                        <input type="hidden" name="role_id" value="<?php echo $editRole['id']; ?>">
                        <div class="form-row">
                            <label>角色名称</label>
                            <input name="role_name" value="<?php echo htmlspecialchars($editRole['role_name']); ?>" placeholder="如：运维人员">
                        </div>
                        <div class="form-row">
                            <label>页面权限（勾选可访问页面）</label>
                            <div class="check-group">
                                <?php foreach ($allPagePerms as $p): ?>
                                <div class="check-item">
                                    <input type="checkbox" name="page_perm[]" value="<?php echo $p['key']; ?>" id="p_<?php echo $p['key']; ?>"
                                    <?php echo in_array($p['key'],$editRole['perms'])?'checked':''; ?>>
                                    <label for="p_<?php echo $p['key']; ?>"><?php echo $p['name']; ?></label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <button class="btn-base btn-primary" type="submit"><i class="fa fa-save"></i>保存角色</button>
                    </form>
                    <table>
                        <tr>
                            <th>ID</th>
                            <th>角色名称</th>
                            <th>操作</th>
                        </tr>
                        <?php foreach ($roleList as $r): ?>
                        <tr>
                            <td><?php echo $r['id']; ?></td>
                            <td><?php echo htmlspecialchars($r['role_name']); ?></td>
                            <td class="operate">
                                <a href="?tab=role&edit_role=<?php echo $r['id']; ?>">编辑</a>
                                <a href="?tab=role&del_role=<?php echo $r['id']; ?>" class="del" onclick="return confirm('确认删除该角色？')">删除</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>

                <!-- 模块2：用户管理 -->
                <div class="tab-content <?php echo $activeTab=='user'?'show':''; ?>" id="tab-user">
                    <form method="post">
                        <input type="hidden" name="act" value="save_user">
                        <input type="hidden" name="user_id" value="<?php echo $editUser['id']; ?>">
                        <div class="form-row">
                            <label>登录账号</label>
                            <input name="username" value="<?php echo htmlspecialchars($editUser['username']); ?>">
                        </div>
                        <div class="form-row">
                            <label>真实姓名</label>
                            <input name="real_name" value="<?php echo htmlspecialchars($editUser['real_name']); ?>">
                        </div>
                        <div class="form-row">
                            <label>所属角色</label>
                            <select name="role_id">
                                <option value="">请选择角色</option>
                                <?php echo $roleOptionHtml; ?>
                            </select>
                            <script>$("select[name=role_id]").val(<?php echo $editUser['role_id']; ?>)</script>
                        </div>
                        <div class="form-row">
                            <label>登录密码（编辑留空不修改）</label>
                            <input name="password" type="password">
                        </div>
                        <div class="form-row">
                            <label>账号状态</label>
                            <select name="status">
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                            <script>$("select[name=status]").val(<?php echo $editUser['status']; ?>)</script>
                        </div>
                        <button class="btn-base btn-primary" type="submit"><i class="fa fa-save"></i>保存用户</button>
                    </form>
                    <table>
                        <tr>
                            <th>ID</th>
                            <th>登录账号</th>
                            <th>姓名</th>
                            <th>所属角色</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        <?php foreach ($userList as $u): ?>
                        <tr>
                            <td><?php echo $u['id']; ?></td>
                            <td><?php echo htmlspecialchars($u['username']); ?></td>
                            <td><?php echo htmlspecialchars($u['real_name']); ?></td>
                            <td><?php echo htmlspecialchars($u['role_name'] ?? '无'); ?></td>
                            <td><?php echo $u['status']==1?'启用':'禁用'; ?></td>
                            <td class="operate">
                                <a href="?tab=user&edit_user=<?php echo $u['id']; ?>">编辑</a>
                                <a href="?tab=user&del_user=<?php echo $u['id']; ?>" class="del" onclick="return confirm('确认删除该用户？')">删除</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
// Tab切换逻辑
$(".tab-item").click(function(){
    const tab = $(this).data("tab");
    location.href = "system_manage.php?tab="+tab;
})
// 实时时间
function updateNowTime(){
    const d=new Date();
    const Y=d.getFullYear();
    const M=String(d.getMonth()+1).padStart(2,'0');
    const D=String(d.getDate()).padStart(2,'0');
    const h=String(d.getHours()).padStart(2,'0');
    const m=String(d.getMinutes()).padStart(2,'0');
    const s=String(d.getSeconds()).padStart(2,'0');
    $("#nowTime").text(`${Y}-${M}-${D} ${h}:${m}:${s}`);
}
setInterval(updateNowTime,1000);
updateNowTime();
// 语言切换
$("#langSwitch").change(function(){
    const lang = $(this).val();
    $.post("system_manage.php",{action:"save_lang",lang:lang},()=>location.reload());
})
</script>
</body>
</html>
