<?php
$db = getDB();
$message = '';

if (!hasPermission('users')) {
    header('Location: /admin');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        $action = $_POST['action'] ?? '';

        if ($action === 'add_user') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $role = $_POST['role'] ?? 'editor';
            $fullName = trim($_POST['full_name'] ?? '');
            $email = trim($_POST['email'] ?? '');

            if ($username && $password) {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("INSERT INTO admin_users (username, password_hash, role, full_name, email) VALUES (?, ?, ?, ?, ?) ON CONFLICT (username) DO NOTHING");
                $stmt->execute([$username, $hash, $role, $fullName, $email]);
                $message = 'User added successfully.';
                logAudit('create', 'admin_users', null, "Added user: $username");
            }
        }

        if ($action === 'update_user') {
            $id = (int)($_POST['id'] ?? 0);
            $role = $_POST['role'] ?? 'editor';
            $fullName = trim($_POST['full_name'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $active = isset($_POST['active']) ? true : false;
            $newPassword = $_POST['new_password'] ?? '';

            if ($id) {
                $stmt = $db->prepare("UPDATE admin_users SET role=?, full_name=?, email=?, active=? WHERE id=?");
                $stmt->execute([$role, $fullName, $email, $active, $id]);

                if ($newPassword) {
                    $hash = password_hash($newPassword, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("UPDATE admin_users SET password_hash=? WHERE id=?");
                    $stmt->execute([$hash, $id]);
                }
                $message = 'User updated successfully.';
                logAudit('update', 'admin_users', $id, "Updated user #$id");
            }
        }

        if ($action === 'delete_user') {
            $id = (int)($_POST['delete_id'] ?? 0);
            if ($id && $id != ($_SESSION['admin_id'] ?? 0)) {
                $db->prepare("DELETE FROM admin_users WHERE id = ?")->execute([$id]);
                $message = 'User deleted.';
                logAudit('delete', 'admin_users', $id, "Deleted user #$id");
            } else {
                $message = 'Cannot delete your own account.';
            }
        }
    }
}

$users = getAllAdminUsers();
$roles = getAllRoles();
$editUser = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM admin_users WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editUser = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Users & Roles</h2>
    <a href="/admin">← Back to Dashboard</a>
</div>

<?php if ($message): ?>
    <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3><?= $editUser ? 'Edit User' : 'Add New User' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="<?= $editUser ? 'update_user' : 'add_user' ?>">
        <?php if ($editUser): ?>
            <input type="hidden" name="id" value="<?= $editUser['id'] ?>">
        <?php endif; ?>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" value="<?= htmlspecialchars($editUser['username'] ?? '') ?>" <?= $editUser ? 'readonly' : 'required' ?>>
            </div>
            <div class="form-group">
                <label><?= $editUser ? 'New Password (leave blank to keep)' : 'Password' ?></label>
                <input type="password" name="<?= $editUser ? 'new_password' : 'password' ?>" <?= $editUser ? '' : 'required' ?>>
            </div>
            <div class="form-group">
                <label>Full Name</label>
                <input type="text" name="full_name" value="<?= htmlspecialchars($editUser['full_name'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" name="email" value="<?= htmlspecialchars($editUser['email'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Role</label>
                <select name="role">
                    <?php foreach ($roles as $role): ?>
                        <option value="<?= htmlspecialchars($role['name']) ?>" <?= ($editUser['role'] ?? '') === $role['name'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($role['description']) ?> (<?= htmlspecialchars($role['name']) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if ($editUser): ?>
            <div class="form-group">
                <label>Status</label>
                <label style="display: flex; align-items: center; gap: 8px; font-weight: normal; margin-top: 8px;">
                    <input type="checkbox" name="active" <?= ($editUser['active'] ?? true) ? 'checked' : '' ?>> Active
                </label>
            </div>
            <?php endif; ?>
        </div>

        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn-sm btn-sm-primary"><?= $editUser ? 'Update User' : 'Add User' ?></button>
            <?php if ($editUser): ?>
                <a href="/admin/users" class="btn-sm btn-sm-danger">Cancel</a>
            <?php endif; ?>
        </div>
    </form>
</div>

<div class="admin-card">
    <h3>All Users</h3>
    <table>
        <thead>
            <tr>
                <th>Username</th>
                <th>Full Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Last Login</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td><?= htmlspecialchars($u['username']) ?></td>
                <td><?= htmlspecialchars($u['full_name'] ?? '') ?></td>
                <td><?= htmlspecialchars($u['email'] ?? '') ?></td>
                <td><?= htmlspecialchars($u['role'] ?? 'admin') ?></td>
                <td><?= ($u['active'] ?? true) ? '<span style="color:#198754;">Active</span>' : '<span style="color:#dc3545;">Inactive</span>' ?></td>
                <td><?= $u['last_login'] ? date('M j, Y g:i A', strtotime($u['last_login'])) : 'Never' ?></td>
                <td class="actions">
                    <a href="/admin/users?edit=<?= $u['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <?php if ($u['id'] != ($_SESSION['admin_id'] ?? 0)): ?>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete this user?');">
                        <?= csrfField() ?>
                        <input type="hidden" name="action" value="delete_user">
                        <input type="hidden" name="delete_id" value="<?= $u['id'] ?>">
                        <button type="submit" class="btn-sm btn-sm-danger">Delete</button>
                    </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
