<?php
/**
 * 炎酷CMS - 管理员工（列表/新增/删除/修改当前账号密码）
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';

$page_title = '管理员工';
$active = 'admin';
$T = DB_PREFIX . 'admin';
$me = admin_current();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $do = isset($_POST['do']) ? $_POST['do'] : '';

    // 修改当前账号密码
    if ($do === 'change_pwd') {
        $old = isset($_POST['old_pwd']) ? (string)$_POST['old_pwd'] : '';
        $new = isset($_POST['new_pwd']) ? (string)$_POST['new_pwd'] : '';
        $rep = isset($_POST['re_pwd']) ? (string)$_POST['re_pwd'] : '';
        $admin = db_one("SELECT * FROM $T WHERE id = ?", array((int)$_SESSION['yk_admin_id']));
        if (!$admin || $admin['password'] !== md5($old . PWD_SALT)) {
            flash_set('原密码错误', 'err');
        } elseif (strlen($new) < 6) {
            flash_set('新密码长度至少 6 位', 'err');
        } elseif ($new !== $rep) {
            flash_set('两次输入的新密码不一致', 'err');
        } else {
            db_exec("UPDATE $T SET password = ? WHERE id = ?", array(md5($new . PWD_SALT), $admin['id']));
            admin_log('修改密码', '账号:' . $admin['username']);
            flash_set('密码修改成功');
        }
        header('Location: admin.php');
        exit;
    }

    if ($do === 'add') {
        $username = trim(isset($_POST['username']) ? $_POST['username'] : '');
        $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
        $mobile   = trim(isset($_POST['mobile']) ? $_POST['mobile'] : '');
        if ($username === '' || !preg_match('/^[a-zA-Z0-9_]{3,30}$/', $username)) {
            flash_set('用户名需为 3-30 位字母、数字或下划线', 'err');
        } elseif (strlen($password) < 6) {
            flash_set('密码长度至少 6 位', 'err');
        } elseif (db_one("SELECT id FROM $T WHERE username = ?", array($username))) {
            flash_set('用户名已存在', 'err');
        } else {
            $id = db_insert("INSERT INTO $T (username, password, mobile, role, add_time) VALUES (?, ?, ?, 'admin', ?)",
                array($username, md5($password . PWD_SALT), $mobile, time()));
            admin_log('新增管理员', 'ID:' . $id . ' 账号:' . $username);
            flash_set('管理员已新增');
        }
        header('Location: admin.php');
        exit;
    }

    if ($do === 'delete') {
        $id = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
        $total = (int)db_val("SELECT COUNT(*) FROM $T");
        $row = db_one("SELECT username FROM $T WHERE id = ?", array($id));
        if (!$row) {
            flash_set('管理员不存在', 'err');
        } elseif ($id === (int)$me['id']) {
            flash_set('不能删除当前登录账号', 'err');
        } elseif ($total <= 1) {
            flash_set('至少需要保留一个管理员', 'err');
        } else {
            db_exec("DELETE FROM $T WHERE id = ?", array($id));
            admin_log('删除管理员', 'ID:' . $id . ' 账号:' . $row['username']);
            flash_set('管理员已删除');
        }
        header('Location: admin.php');
        exit;
    }
}

$list = db_all("SELECT * FROM $T ORDER BY id ASC");

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3>管理员列表</h3>
  <table class="yk-table">
    <tr><th width="60">ID</th><th>账号</th><th width="130">手机号</th><th width="80">角色</th><th width="150">添加时间</th><th width="80">操作</th></tr>
    <?php foreach ($list as $a): ?>
    <tr>
      <td><?php echo (int)$a['id']; ?></td>
      <td><?php echo e($a['username']); ?><?php echo (int)$a['id'] === (int)$me['id'] ? ' <span style="color:#1e6fff;font-size:12px">(当前)</span>' : ''; ?></td>
      <td><?php echo e($a['mobile']); ?></td>
      <td><?php echo e($a['role']); ?></td>
      <td><?php echo e(fdate($a['add_time'], 'Y-m-d H:i')); ?></td>
      <td>
        <?php if ((int)$a['id'] !== (int)$me['id']): ?>
        <form method="post" action="admin.php" style="display:inline" onsubmit="return confirm('确定删除该管理员？');">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="delete">
          <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
        <?php else: ?>-<?php endif; ?>
      </td>
    </tr>
    <?php endforeach; ?>
  </table>
</div>

<div class="yk-card" style="max-width:560px">
  <h3>新增管理员工</h3>
  <form class="yk-form" method="post" action="admin.php">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="do" value="add">
    <div class="row"><label>账号</label><div class="ipt"><input type="text" name="username" required><div class="tip">3-30 位字母、数字或下划线</div></div></div>
    <div class="row"><label>密码</label><div class="ipt"><input type="password" name="password" required><div class="tip">至少 6 位</div></div></div>
    <div class="row"><label>手机号</label><div class="ipt"><input type="text" name="mobile"></div></div>
    <div class="row"><label></label><div class="ipt"><button class="yk-btn" type="submit">新增</button></div></div>
  </form>
</div>

<div class="yk-card" style="max-width:560px">
  <h3>修改当前账号密码</h3>
  <form class="yk-form" method="post" action="admin.php">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="do" value="change_pwd">
    <div class="row"><label>原密码</label><div class="ipt"><input type="password" name="old_pwd" required></div></div>
    <div class="row"><label>新密码</label><div class="ipt"><input type="password" name="new_pwd" required><div class="tip">至少 6 位</div></div></div>
    <div class="row"><label>确认新密码</label><div class="ipt"><input type="password" name="re_pwd" required></div></div>
    <div class="row"><label></label><div class="ipt"><button class="yk-btn" type="submit">确认修改</button></div></div>
  </form>
</div>
<?php require dirname(__DIR__) . '/inc/footer.php'; ?>
