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

$currentAdminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;
$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$error = '';
$success = '';
if (!is_super_admin()) {
    redirect('/admin/dashboard/index.php');
}

$statusOptions = admin_status_options();
$roleOptions = admin_role_options();
$form = array('username' => '', 'display_name' => '', 'password' => '', 'password_confirm' => '', 'status' => 'enabled', 'role' => 'user');

if ($_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['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';

    if ($form['username'] === '' || $form['display_name'] === '' || $form['password'] === '') {
        $error = '请完整填写管理员账号、显示名称和密码。';
    } elseif (strlen($form['password']) < 6) {
        $error = '密码长度不能少于 6 位。';
    } elseif ($form['password'] !== $form['password_confirm']) {
        $error = '两次输入的密码不一致，请重新输入。';
    } elseif (!isset($statusOptions[$form['status']])) {
        $error = '状态值无效。';
    } else {
        try {
            $newAdminId = create_admin(array(
                'username' => $form['username'],
                'display_name' => $form['display_name'],
                'password' => $form['password'],
                'status' => $form['status'],
                'role' => $form['role']
            ));

            write_admin_operation_log($currentAdminId, $adminUsername, (int)$newAdminId, $form['username'], 'create_admin', '创建管理员账号，初始状态：' . $form['status']);

            $success = '管理员 ' . $form['username'] . ' 已创建成功。';
            $form = array('username' => '', 'display_name' => '', 'password' => '', 'password_confirm' => '', 'status' => 'enabled', 'role' => 'user');
        } 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>
                        <p style="margin:8px 0 0;"><a href="/admin/user/list.php">返回管理员列表</a></p>
                    </div>
                <?php endif; ?>
                <form class="form-stack" method="post" action="/admin/user/add.php">
                    <?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>登录密码</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>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
