<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$currentAdminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
if (!is_super_admin()) {
    redirect('/admin/dashboard/index.php');
}

$statusOptions = admin_status_options();
$roleOptions = admin_role_options();
$error = '';
$success = '';
$recordExists = false;
$adminId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$form = array(
    'username' => '',
    'display_name' => '',
    'current_password' => '',
    'password' => '',
    'password_confirm' => '',
    'status' => 'enabled',
    'role' => 'user'
);

if ($adminId <= 0) {
    $error = '缺少有效的管理员ID。';
} else {
    try {
        $row = find_admin_by_id($adminId);
        if (!$row) {
            $error = '未找到对应的管理员记录。';
        } else {
            $recordExists = true;
            $form['username'] = isset($row['username']) ? $row['username'] : '';
            $form['display_name'] = isset($row['display_name']) ? $row['display_name'] : '';
            $form['status'] = isset($row['status']) ? $row['status'] : 'enabled';
            $form['role'] = isset($row['role']) ? $row['role'] : 'user';
        }
    } catch (Exception $e) {
        $error = '数据库读取失败：' . $e->getMessage();
    }
}

if ($recordExists && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $form['username'] = isset($_POST['username']) ? trim((string)$_POST['username']) : '';
    $form['display_name'] = isset($_POST['display_name']) ? trim((string)$_POST['display_name']) : '';
    $form['current_password'] = isset($_POST['current_password']) ? (string)$_POST['current_password'] : '';
    $form['password'] = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $form['password_confirm'] = isset($_POST['password_confirm']) ? (string)$_POST['password_confirm'] : '';
    $form['status'] = isset($_POST['status']) ? trim((string)$_POST['status']) : 'enabled';
    $form['role'] = isset($_POST['role']) ? trim((string)$_POST['role']) : 'user';
    $isChangingPassword = $form['password'] !== '' || $form['password_confirm'] !== '';
    $isEditingSelf = $adminId === $currentAdminId;

    if ($form['username'] === '' || $form['display_name'] === '') {
        $error = '请完整填写管理员账号和显示名称。';
    } elseif (!isset($statusOptions[$form['status']])) {
        $error = '状态值无效。';
    } elseif ($isChangingPassword && $form['current_password'] === '') {
        $error = $isEditingSelf ? '修改自己的密码时，必须输入旧密码。' : '修改他人密码时，必须输入当前登录管理员密码进行验证。';
    } elseif ($isChangingPassword && !verify_admin_identity_by_id($currentAdminId, $form['current_password'])) {
        $error = $isEditingSelf ? '旧密码错误，请重新输入。' : '当前登录管理员密码验证失败，不能重置他人密码。';
    } elseif ($form['password'] !== '' && strlen($form['password']) < 6) {
        $error = '新密码长度不能少于 6 位。';
    } elseif ($form['password'] !== $form['password_confirm']) {
        $error = '两次输入的新密码不一致，请重新输入。';
    } else {
        try {
            update_admin($adminId, array(
                'username' => $form['username'],
                'display_name' => $form['display_name'],
                'password' => $form['password'],
                'status' => $form['status'],
                'role' => $form['role']
            ), $currentAdminId);
            write_admin_operation_log($currentAdminId, $adminUsername, $adminId, $form['username'], 'update_admin', '更新管理员资料，状态：' . $form['status'] . ($form['password'] !== '' ? '，并修改密码' : ''));
            $success = '管理员 ' . $form['username'] . ' 已更新成功。';
            $form['current_password'] = '';
            $form['password'] = '';
            $form['password_confirm'] = '';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 编辑管理员</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('admins', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>编辑管理员</h1><p>统一修改管理员账号、显示名称、状态与密码；改密时需通过二次验证。</p></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/user/list.php">返回列表</a></div>
            </header>
            <section class="page-card">
                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">处理失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($success !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">更新成功</strong>
                        <p style="margin:0; color:#166534;"><?php echo e($success); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($recordExists): ?>
                    <form class="form-stack" method="post" action="/admin/user/edit.php?id=<?php echo (int)$adminId; ?>">
                        <?php echo csrf_field(); ?>
                        <div class="input-group">
                            <span>管理员账号</span>
                            <input class="input" type="text" name="username" value="<?php echo e($form['username']); ?>" placeholder="请输入管理员账号（唯一）">
                        </div>
                        <div class="input-group">
                            <span>显示名称</span>
                            <input class="input" type="text" name="display_name" value="<?php echo e($form['display_name']); ?>" placeholder="请输入显示名称">
                        </div>
                        <div class="input-group">
                            <span><?php echo $adminId === $currentAdminId ? '旧密码' : '当前登录管理员密码'; ?></span>
                            <input class="input" type="password" name="current_password" placeholder="<?php echo $adminId === $currentAdminId ? '如需改密，请先输入旧密码' : '如需改密，请输入当前登录管理员密码'; ?>">
                        </div>
                        <div class="input-group">
                            <span>新密码</span>
                            <input class="input" type="password" name="password" placeholder="不修改密码可留空，至少 6 位">
                        </div>
                        <div class="input-group">
                            <span>确认新密码</span>
                            <input class="input" type="password" name="password_confirm" placeholder="请再次输入新密码">
                        </div>
                        <div class="input-group">
                            <span>角色</span>
                            <select class="select" name="role">
                                <?php foreach ($roleOptions as $val => $label): ?>
                                    <option value="<?php echo e($val); ?>" <?php echo $form['role'] === $val ? 'selected' : ''; ?>><?php echo e($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group">
                            <span>状态</span>
                            <select class="select" name="status">
                                <?php foreach ($statusOptions as $val => $label): ?>
                                    <option value="<?php echo e($val); ?>" <?php echo $form['status'] === $val ? 'selected' : ''; ?>><?php echo e($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="filter-row">
                            <button class="btn-primary" type="submit">保存修改</button>
                            <a class="btn-ghost" href="/admin/user/list.php">取消</a>
                        </div>
                    </form>
                <?php endif; ?>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
