<?php
requireAdmin();

$action = $_GET['action'] ?? 'list';
$employee_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 定义可用权限
$permissions_list = [
    'apps.view' => '查看应用',
    'apps.manage' => '管理应用',
    'users.view' => '查看用户',
    'users.manage' => '管理用户',
    'orders.view' => '查看订单',
    'orders.manage' => '管理订单',
    'licenses.view' => '查看授权',
    'licenses.manage' => '管理授权',
    'tickets.handle' => '处理工单',
    'config.view' => '查看配置',
    'config.manage' => '管理配置'
];

// 处理删除
if ($action == 'delete' && $employee_id > 0) {
    $db->query("DELETE FROM users WHERE id = $employee_id AND role = 'employee'");
    redirect('?page=employees');
}

// 处理编辑/添加
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $permissions = isset($_POST['permissions']) ? json_encode($_POST['permissions']) : '[]';
    $status = intval($_POST['status'] ?? 1);
    
    if (empty($username) || empty($email)) {
        $error = '用户名和邮箱不能为空';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } else {
        if ($action == 'edit' && $employee_id > 0) {
            // 编辑时检查邮箱是否被其他用户占用
            $check = $db->fetchOne("SELECT id FROM users WHERE email = '$email' AND id != $employee_id");
            if ($check) {
                $error = '邮箱已被其他用户使用';
            } elseif (!empty($password)) {
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                $db->query("UPDATE users SET username='$username', email='$email', password='$hashed', permissions='$permissions', status=$status WHERE id=$employee_id");
                redirect('?page=employees');
            } else {
                $db->query("UPDATE users SET username='$username', email='$email', permissions='$permissions', status=$status WHERE id=$employee_id");
                redirect('?page=employees');
            }
        } elseif ($action == 'add') {
            // 添加时检查邮箱是否已存在
            $check = $db->fetchOne("SELECT id FROM users WHERE email = '$email'");
            if ($check) {
                $error = '邮箱已被使用，请使用其他邮箱';
            } elseif (empty($password)) {
                $error = '请设置密码';
            } else {
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                $db->query("INSERT INTO users (username, password, email, role, permissions, status) VALUES ('$username', '$hashed', '$email', 'employee', '$permissions', $status)");
                redirect('?page=employees');
            }
        }
    }
}

// 获取员工列表
$employees = $db->fetchAll("SELECT * FROM users WHERE role = 'employee' ORDER BY id DESC");

// 编辑模式获取数据
$edit_employee = null;
if ($action == 'edit' && $employee_id > 0) {
    $edit_employee = $db->fetchOne("SELECT * FROM users WHERE id = $employee_id AND role = 'employee'");
    if ($edit_employee && $edit_employee['permissions']) {
        $edit_employee['permissions'] = json_decode($edit_employee['permissions'], true);
    }
}

// 处理状态切换
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'toggle_status') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->query("UPDATE users SET status = $status WHERE id = $id AND role = 'employee'");
    echo json_encode(['success' => true]);
    exit;
}
?>

<?php if ($action == 'add' || ($action == 'edit' && $edit_employee)): ?>
    <!-- 添加/编辑表单 -->
    <div class="form-container">
        <div class="page-header">
            <h2><?php echo $action == 'add' ? '添加员工' : '编辑员工'; ?></h2>
            <a href="?page=employees" class="btn btn-secondary">返回列表</a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label>用户名 *</label>
                    <input type="text" name="username" required value="<?php echo htmlspecialchars($edit_employee['username'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>邮箱 *</label>
                    <input type="email" name="email" required value="<?php echo htmlspecialchars($edit_employee['email'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>密码 <?php if ($action == 'edit'): ?><small>(留空则不修改)</small><?php endif; ?></label>
                    <input type="password" name="password" <?php echo $action == 'add' ? 'required' : ''; ?>>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status">
                        <option value="1" <?php echo (isset($edit_employee['status']) && $edit_employee['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                        <option value="0" <?php echo (isset($edit_employee['status']) && $edit_employee['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>权限设置</label>
                    <div class="permissions-grid">
                        <?php foreach ($permissions_list as $key => $label): ?>
                            <label class="checkbox-label">
                                <input type="checkbox" name="permissions[]" value="<?php echo $key; ?>"
                                    <?php echo isset($edit_employee['permissions']) && in_array($key, $edit_employee['permissions']) ? 'checked' : ''; ?>>
                                <?php echo $label; ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <a href="?page=employees" class="btn btn-secondary">取消</a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 员工列表 -->
    <div class="employees-manager">
        <div class="page-header">
            <h2>员工管理</h2>
            <a href="?page=employees&action=add" class="btn btn-primary">+ 添加员工</a>
        </div>
        
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>权限数量</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </thead>
                <tbody>
                    <?php if (empty($employees)): ?>
                        <tr><td colspan="7" style="text-align: center;">暂无员工</td></tr>
                    <?php else: ?>
                        <?php foreach ($employees as $emp): ?>
                            <tr>
                                <td><?php echo $emp['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($emp['username']); ?></strong></td>
                                <td><?php echo htmlspecialchars($emp['email']); ?></td>
                                <td>
                                    <?php 
                                    $perms = json_decode($emp['permissions'] ?? '[]', true);
                                    echo count($perms);
                                    ?>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $emp['status'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $emp['status'] ? '启用' : '禁用'; ?>
                                    </span>
                                </td>
                                <td><?php echo $emp['created_at']; ?></td>
                                <td>
                                    <a href="?page=employees&action=edit&id=<?php echo $emp['id']; ?>" class="btn-icon" title="编辑">✏️</a>
                                    <a href="?page=employees&action=delete&id=<?php echo $emp['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此员工吗？')" title="删除">🗑️</a>
                                    <button class="btn-icon" onclick="toggleStatus(<?php echo $emp['id']; ?>, <?php echo $emp['status'] ? 0 : 1; ?>)" title="切换状态">🔄</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
    function toggleStatus(id, status) {
        fetch('?page=employees&action=toggle_status', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${status}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast('状态更新成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
        });
    }
    </script>
<?php endif; ?>

<style>
.form-container {
    max-width: 600px;
}
.form-card {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.permissions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 10px;
    padding: 15px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
    max-height: 300px;
    overflow-y: auto;
}
.checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}
.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
    padding: 4px 8px;
    border-radius: 4px;
}
.btn-icon:hover {
    background: var(--bg-secondary);
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
</style>