<?php require_once 'auth.php';
$pageTitle = $t['role_manage'];
// 新增/编辑角色提交
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('角色名称不能为空');history.back();</script>";
        exit;
    }
    // 新增角色
    if ($roleId == 0) {
        mysqli_query($connConfig, "INSERT INTO sys_role(role_name) VALUES('$roleName')");
        $roleId = mysqli_insert_id($connConfig);
    } else {
        // 更新角色名
        mysqli_query($connConfig, "UPDATE sys_role SET role_name='$roleName' WHERE id=$roleId");
        // 清空旧权限
        mysqli_query($connConfig, "DELETE FROM sys_role_permission WHERE role_id=$roleId");
    }
    // 写入新权限
    foreach ($pages as $page) {
        $page = mysqli_real_escape_string($connConfig, $page);
        mysqli_query($connConfig, "INSERT INTO sys_role_permission(role_id,page_key) VALUES($roleId,'$page')");
    }
    echo "<script>alert('保存成功');location.href='role_manage.php';</script>";
    exit;
}
// 删除角色
if ($_GET['del']) {
    $delId = intval($_GET['del']);
    mysqli_query($connConfig, "DELETE FROM sys_role_permission WHERE role_id=$delId");
    mysqli_query($connConfig, "DELETE FROM sys_role WHERE id=$delId");
    header("Location: role_manage.php");
    exit;
}
// 获取所有角色
$roleList = [];
$roleRes = mysqli_query($connConfig, "SELECT * FROM sys_role ORDER BY id DESC");
while ($r = mysqli_fetch_assoc($roleRes)) $roleList[] = $r;
// 全部页面权限列表
$allPages = [
    ['key'=>'dashboard','name'=>'告警总览'],
    ['key'=>'work_order','name'=>'工单系统'],
    ['key'=>'disk','name'=>'磁盘容量'],
    ['key'=>'history_query','name'=>'历史查询'],
    ['key'=>'smtp_config','name'=>'消息通知配置'],
    ['key'=>'role_manage','name'=>'角色管理'],
    ['key'=>'user_manage','name'=>'用户管理'],
];
// 编辑角色时读取已有权限
$editRole = ['id'=>0,'role_name'=>'','perms'=>[]];
if (!empty($_GET['edit'])) {
    $eid = intval($_GET['edit']);
    $er = mysqli_fetch_assoc(mysqli_query($connConfig, "SELECT * FROM sys_role WHERE id=$eid"));
    if ($er) {
        $editRole = $er;
        $permRes = mysqli_query($connConfig, "SELECT page_key FROM sys_role_permission WHERE role_id=$eid");
        while ($p = mysqli_fetch_assoc($permRes)) $editRole['perms'][] = $p['page_key'];
    }
}
mysqli_close($connConfig);
?>
<!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;margin-bottom:30px;}
        .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;}
        .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{width:360px;height:46px;padding:0 16px;border:1px solid #d6dce5;border-radius:10px;font-size:14px;}
        .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;}
    </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-user-secret"></i><span><?php echo $t['role_manage']; ?></span></div>
            <div class="menu-item" onclick="location.href='user_manage.php'"><i class="fa fa-users"></i><span><?php echo $t['user_manage']; ?></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-user-secret"></i>新增/编辑角色</div>
                <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 ($allPages 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>
            </div>
            <div class="base-card">
                <div class="title-wrap"><i class="fa fa-list"></i>角色列表</div>
                <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="?edit=<?php echo $r['id']; ?>">编辑</a>
                            <a href="?del=<?php echo $r['id']; ?>" class="del" onclick="return confirm('确认删除？')">删除</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>
    </div>
</div>
<script>
function updateNowTime(){const d=new Date();let Y=d.getFullYear(),M=String(d.getMonth()+1).padStart(2,'0'),D=String(d.getDate()).padStart(2,'0'),h=String(d.getHours()).padStart(2,'0'),m=String(d.getMinutes()).padStart(2,'0'),s=String(d.getSeconds()).padStart(2,'0');$("#nowTime").text(`${Y}-${M}-${D} ${h}:${m}:${s}`);}
setInterval(updateNowTime,1000);updateNowTime();
$("#langSwitch").change(function(){let l=$(this).val();$.post("role_manage.php",{action:"save_lang",lang:l},()=>location.reload());})
</script>
</body>
</html>
