# Admin User Management Module Usage Instructions

> The `feat/admin-sub/user-managment` branch introduces a fully functional, AJAX-powered CRUD system for managing system users. Built on the established base architecture, this module provides seamless user administration without full page reloads, including bulk actions, soft deletes, status toggling, and email invitations.

---

## Table of Contents

1. [Module Overview & Goals](#1-module-overview--goals)
2. [What You Inherit (Merge Context)](#2-what-you-inherit-merge-context)
3. [Deep Dive: Features & Functionality](#3-deep-dive-features--functionality)
4. [File Paths & Architecture](#4-file-paths--architecture)
5. [Step-by-Step Usage Guide](#5-step-by-step-usage-guide)
6. [Architectural Highlights](#6-architectural-highlights)

---

## 1. Module Overview & Goals

The goal of this module is to deliver a production-ready User Management system that acts as a blueprint for all future CRUD modules in the admin panel.

It demonstrates how to build a complex data table with filtering, sorting, pagination, and bulk actions entirely via AJAX. Administrators can create new users, edit existing ones, send invitations, force password resets, and manage soft-deleted (archived) accounts without ever triggering a full page refresh.

---

## 2. What You Inherit (Merge Context)

Because this branch is merged on top of `base` and `feat/admin`, you receive:

- **Base Components:** The robust `<x-common.table-server>`, `<x-ajax-pagination>`, form modals, and feedback toasts.
- **Admin Authentication:** The secure `/behindthescreen` login flow and middleware protection.
- **Service & Repository Pattern:** The established architectural pattern where logic is cleanly separated from controllers.

---

## 3. Deep Dive: Features & Functionality

This branch brings a massive suite of features strictly tailored for managing users:

- **AJAX Data Tables:**
  - The main `/admin/users` page loads a Blade shell, while Alpine.js requests the paginated table data from the `/admin/users/data` JSON endpoint.
  - Supports real-time search, sorting by columns (Name, Email, Status, Date), and filtering by role or status.
- **Comprehensive User Operations (CRUD):**
  - **Create & Edit:** Modals open to let admins add or modify user details (Name, Email, Phone, Role, Status).
  - **View:** A read-only modal to inspect user details quickly.
  - **Status Toggling:** A quick-action toggle to switch a user between `active` and `inactive` states directly from the table.

- **Advanced Administrative Actions:**
  - **Change Password:** Admins can securely set a new password for any user.
  - **Send Invitation:** Trigger an email invitation containing a secure link for the user to set their own password.
  - **Reset 2FA:** If a user is locked out, admins can clear their Two-Factor Authentication setup.

- **Archiving & Soft Deletes:**
  - Users are never permanently deleted; they are softly deleted and moved to the **Archived Users** view (`/admin/users/archived`).
  - Supports **Individual & Bulk Deletion** from the active list.
  - Supports **Individual & Bulk Restoration** from the archived list.

- **Real-Time Statistics:**
  - The `/admin/users/stats` endpoint feeds the metric cards at the top of the page (Total Users, Active, Inactive, Admins) which automatically update when mutations occur.

---

## 4. File Paths & Architecture

Here are the critical files added or modified in this module:

### Controllers

- **`app/Http/Controllers/Admin/User/UserManagementController.php`**: The powerhouse controller containing 15+ methods for handling the HTML views and all JSON/AJAX API endpoints (data, stats, bulkDelete, restore, etc.).

### Routes (`routes/admin.php`)

- A comprehensive suite of endpoints grouped under `prefix('users')`:
  - `GET /users/data` (Datatable JSON)
  - `GET /users/stats` (Metrics JSON)
  - `POST /users/bulk-delete` & `POST /users/bulk-restore`
  - `PATCH /users/{id}/status`
  - `PATCH /users/{id}/change-password`
  - `POST /users/{id}/send-invitation`
  - `POST /users/{id}/reset-two-factor`
  - Standard resource routes (index, show, create, store, edit, update, destroy).

### Views (`resources/views/pages/admin/users/`)

- **`index.blade.php`**: The primary user management interface housing the active data table, filter bars, stats cards, and Alpine.js logic.
- **`archived.blade.php`**: The dedicated view for managing and restoring soft-deleted users.
- **`partials/`**: Contains the Blade snippets for the Modals (Create, Edit, View, Change Password).

---

## 5. Step-by-Step Usage Guide

### 1. Navigating to the Module

Log in to the admin portal and navigate to `http://your-app-url/admin/users`.

### 2. Testing the AJAX Data Table

- Type a name in the search box; watch the table filter instantly without a page reload.
- Click the column headers (e.g., "Email" or "Date") to test ascending/descending sorting.
- Select the checkbox next to multiple users to reveal the "Bulk Actions" dropdown.

### 3. Testing Soft Deletes (Archiving)

- Click the trash can icon on a user row. Confirm the deletion.
- Notice the toast notification appears, the table updates, and the "Stats" at the top of the page reflect one less active user.
- Click the "Archived Users" button at the top of the page. You will see the deleted user there.
- Select the user and choose "Restore" to bring them back to the active list.

### 4. Testing Administrative Overrides

- Click the "Key" icon on a user row to open the Change Password modal. Enter a new password to override their credentials.
- Click the "Mail" icon to test the "Send Invitation" feature (ensure your `.env` `MAIL_MAILER` is configured, or set to `log` to view it in `storage/logs/laravel.log`).

---

## 6. Architectural Highlights

- **The Blueprint for Future CRUDs:** This module sets the gold standard for how subsequent modules (like Blogs, CMS, or Products) should be built. Whenever you need to build a new data management page, copy the structure of `UserManagementController` and `index.blade.php`.
- **Form Request Validation:** All data mutation endpoints are secured with dedicated FormRequests (e.g., `UserManagementRequest`, `AdminChangePasswordRequest`) ensuring clean data before hitting the controller.
- **Graceful Error Handling:** If an AJAX request fails (e.g., validation error or server error), the controller catches it and formats a standard JSON error response, which Alpine.js intercepts to display a red toast notification automatically.
