<?php
require_once __DIR__ . '/header.php';
$pdo = db();

$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;

// Handle Delete
if ($action === 'delete' && $id) {
    // Prevent deleting self
    if ($id == $_SESSION['admin_user']['id']) {
        header('Location: admins.php?msg=err_self');
        exit;
    }
    $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: admins.php?msg=deleted');
    exit;
}

// Handle Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $nickname = $_POST['nickname'];
    $password = $_POST['password'];

    if ($id) {
        if (!empty($password)) {
            $stmt = $pdo->prepare("UPDATE admin_users SET username=?, nickname=?, password=? WHERE id=?");
            $stmt->execute([$username, $nickname, password_hash($password, PASSWORD_DEFAULT), $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE admin_users SET username=?, nickname=? WHERE id=?");
            $stmt->execute([$username, $nickname, $id]);
        }
    } else {
        $stmt = $pdo->prepare("INSERT INTO admin_users (username, nickname, password) VALUES (?, ?, ?)");
        $stmt->execute([$username, $nickname, password_hash($password, PASSWORD_DEFAULT)]);
    }
    header('Location: admins.php?msg=saved');
    exit;
}

// Fetch list
$admins = $pdo->query("SELECT * FROM admin_users ORDER BY id DESC")->fetchAll();

// Fetch for edit
$item = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = ?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
}
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><?= $action === 'edit' ? '编辑管理员' : ($action === 'add' ? '新增管理员' : '管理员列表') ?></span>
        <?php if ($action === 'list'): ?>
            <a href="admins.php?action=add" class="btn btn-sm btn-primary">新增管理员</a>
        <?php else: ?>
            <a href="admins.php" class="btn btn-sm btn-secondary">返回列表</a>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <?php if ($action === 'list'): ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>昵称</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($admins as $a): ?>
                        <tr>
                            <td><?= $a['id'] ?></td>
                            <td><strong><?= htmlspecialchars($a['username']) ?></strong></td>
                            <td><?= htmlspecialchars($a['nickname']) ?></td>
                            <td><?= $a['created_at'] ?></td>
                            <td>
                                <a href="admins.php?action=edit&id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i></a>
                                <?php if ($a['id'] != $_SESSION['admin_user']['id']): ?>
                                    <a href="admins.php?action=delete&id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定删除吗？')"><i class="fas fa-trash"></i></a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <form method="POST">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($item['username'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">昵称</label>
                        <input type="text" name="nickname" class="form-control" value="<?= htmlspecialchars($item['nickname'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">密码 <?= $id ? '(留空不修改)' : '' ?></label>
                        <input type="password" name="password" class="form-control" <?= $id ? '' : 'required' ?>>
                    </div>
                </div>
                <div class="mt-4">
                    <button type="submit" class="btn btn-primary">保存修改</button>
                    <a href="admins.php" class="btn btn-light ms-2">取消</a>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
