# Bongo User Package - Cursor Rules

You are working on the `bongo/user` package, a Laravel package that provides user authentication, authorization, and management functionality for the Bongo framework.

## Project Structure

```
src/
├── Commands/
│   └── ResetPasswordCommand.php          # CLI: user:reset_password
├── Events/
│   └── UserEventHandler.php              # Cache invalidation on user save
├── Factories/
│   └── UserFactory.php                   # User model factory
├── Http/
│   ├── Controllers/
│   │   ├── Api/
│   │   │   └── UserController.php        # API endpoints
│   │   ├── Auth/                         # Authentication controllers
│   │   │   ├── AuthenticatedSessionController.php
│   │   │   ├── ConfirmablePasswordController.php
│   │   │   ├── EmailVerificationNotificationController.php
│   │   │   ├── EmailVerificationPromptController.php
│   │   │   ├── NewPasswordController.php
│   │   │   ├── PasswordController.php
│   │   │   ├── PasswordResetLinkController.php
│   │   │   ├── RegisteredUserController.php
│   │   │   └── VerifyEmailController.php
│   │   └── Backend/                      # Admin user management
│   │       ├── UserController.php
│   │       ├── UserDatatableController.php
│   │       ├── UserImageController.php
│   │       └── UserImpersonationController.php
│   ├── Middleware/
│   │   ├── Developer.php                 # Developer-only routes
│   │   ├── Employee.php                  # Employee+ access
│   │   └── Manager.php                   # Manager+ access
│   ├── Requests/
│   │   ├── LoginRequest.php
│   │   ├── StoreUserRequest.php
│   │   └── UpdateUserRequest.php
│   ├── Resources/
│   │   └── UserResource.php              # API resource transformer
│   └── ViewComposers/
│       └── UserComposer.php              # Injects cached users list
├── Mailables/
│   └── ResetPasswordMailable.php
├── Migrations/
│   ├── 2018_01_02_000001_create_users_table.php
│   └── 2018_01_02_000002_create_password_reset_tokens_table.php
├── Models/
│   └── User.php                          # Main user model
├── Notifications/
│   └── ResetPasswordNotification.php     # Queued email notification
├── Routes/
│   ├── api.php                           # API routes (auth:sanctum)
│   ├── backend.php                       # Admin routes (auth + manager)
│   └── web.php                           # Public auth routes
├── Traits/
│   ├── HasAvatar.php                     # Avatar image support
│   ├── HasImpersonate.php                # User impersonation
│   ├── HasName.php                       # Name helper methods
│   ├── HasPhone.php                      # Phone number helpers
│   └── HasType.php                       # User type scopes
├── Translations/
│   └── en/                               # English translations
├── Views/
│   ├── auth/                             # Authentication views
│   ├── backend/                          # Admin user management views
│   └── mail/                             # Email templates
└── UserServiceProvider.php               # Package service provider
```

## Architecture & Extends Bongo Framework

This package **extends** `Bongo\Framework\Providers\AbstractServiceProvider`, which provides automatic bootstrapping:

- **Auto-registers routes** from `src/Routes/`:
  - `api.php` → `api.user.*` with `auth:sanctum` middleware
  - `backend.php` → `backend.user.*` with `auth` + `manager` middleware (restricts to managers+)
  - `web.php` → Standard web authentication routes

- **Auto-loads** config, views (`user::`), migrations, and translations
- **Registers middleware** via `$middlewares` array: `developer`, `manager`, `employee`
- **Registers commands** via `$commands` array: `ResetPasswordCommand`
- **Registers event subscribers** via `$subscribers` array: `UserEventHandler`
- **Registers view composers** via `$composers` array: `UserComposer`

## User Model Architecture

The `User` model extends `Illuminate\Foundation\Auth\User` and uses multiple traits:

### User Types (Hierarchical)
- `DEVELOPER` - Full system access
- `MANAGER` - Can manage users and content
- `EMPLOYEE` - Standard backend access

### User Status
- `PENDING` - Awaiting activation
- `ACTIVE` - Active user
- `INACTIVE` - Disabled user

### Traits Used
1. **From bongo/framework:**
   - `HasStatus` - Status management (active/inactive/pending)
   - `HasUUID` - UUID generation

2. **From bongo/image:**
   - `HasImages` - Image attachment support

3. **From Laravel:**
   - `HasApiTokens` - Sanctum API authentication
   - `Notifiable` - Email/SMS notifications
   - `SoftDeletes` - Soft delete support

4. **From this package:**
   - `HasAvatar` - Get user avatar (first image or default)
   - `HasImpersonate` - User impersonation functionality
   - `HasName` - Name helper methods
   - `HasPhone` - Phone number helpers
   - `HasType` - Type scopes (scopeDeveloper, scopeManager, scopeEmployee)

## User Type Middleware Hierarchy

```
developer     → isDeveloper() only
manager       → isManager() or isDeveloper()
employee      → isEmployee() or isManager() or isDeveloper()
```

All middleware redirect to `/login` if not authenticated, and `abort(404)` if insufficient permissions. The `employee` middleware is the most permissive, allowing any staff member access.

## Routing Patterns

### Web Routes (src/Routes/web.php)
Public authentication routes with no prefix:
- Guest routes: `/register`, `/login`, `/forgot-password`, `/reset-password/{token}`
- Authenticated routes: `/verify-email`, `/confirm-password`, `/logout`

### Backend Routes (src/Routes/backend.php)
Admin user management with `admin/users` prefix + `manager` middleware:
- List/CRUD: `GET /admin/users`, `GET /admin/users/create`, etc.
- Datatable: `GET /admin/users/datatable`
- Impersonation: `GET /admin/users/{user}/start-impersonating`, `GET /admin/users/stop-impersonating`
- Image upload: `POST /admin/users/{user}/image`

### API Routes (src/Routes/api.php)
RESTful API with `api/users` prefix + `auth:sanctum` middleware:
- `GET /api/users` - List users (returns UserResource collection)

## User Impersonation

Admins can impersonate users to test permissions and see the system as another user:

1. **Start impersonating**: Stores original user in `session('impersonator')`, stores target user in `session('impersonating')`, logs in as target
2. **Stop impersonating**: Restores original user session
3. **Check status**: `isImpersonating()` returns true if currently impersonating

Used in: `HasImpersonate` trait, `UserImpersonationController`, middleware exceptions for stop-impersonating routes

## Key Controllers

### Backend\UserController (src/Http/Controllers/Backend/UserController.php)
- Extends `Bongo\Framework\Http\Controllers\AbstractController`
- CRUD operations for users
- **Security rule**: Non-developers cannot view/edit/delete developer accounts (see lines 47-49, 56-58, 80)
- **Self-protection**: Users cannot delete themselves (line 80)
- Password hashing with `Hash::make()`
- Flash messages via `->success()` and `->error()` macros

### Auth\AuthenticatedSessionController
- Login/logout functionality
- Session regeneration on login
- Redirects to `RouteServiceProvider::HOME` after login

## Form Requests

All form requests should validate input:

1. **LoginRequest** - Email/password validation with throttling
2. **StoreUserRequest** - Validates new user creation (required: email, password, first_name, last_name)
3. **UpdateUserRequest** - Validates user updates (password optional)

## Database Schema

### users table
- Primary: `id` (int), `uuid` (string, indexed)
- Contact: `first_name`, `last_name`, `telephone`, `mobile`
- Auth: `email` (indexed), `password`, `remember_token`, `email_verified_at`
- Type & Status: `type` (enum), `status` (enum)
- Audit: `created_by`, `updated_by`, `deleted_by`, `created_at`, `updated_at`, `deleted_at`

### password_reset_tokens table
- `email` (primary), `token`, `created_at`

## Common Tasks

### Creating a New User
```php
$user = new User();
$user->fill($request->except('password'));
$user->password = Hash::make($request->get('password'));
$user->save();
```

### Querying by Type
```php
User::developer()->get();           // Get all developers
User::manager()->get();             // Get all managers
User::notDeveloper()->get();        // Exclude developers
```

### Checking User Type
```php
if ($user->isDeveloper()) { /* ... */ }
if ($user->isManager()) { /* ... */ }
if ($user->isEmployee()) { /* ... */ }
```

### Getting User Avatar
```php
$avatarUrl = $user->getAvatar(); // Returns image preset or '/images/default-avatar.png'
```

### Starting Impersonation
```php
$admin->startImpersonating($targetUser);
// Check if impersonating
if ($user->isImpersonating()) { /* ... */ }
// Stop impersonating
$admin->stopImpersonating();
```

## Coding Conventions

### Naming
- Controllers: `{Entity}Controller` (e.g., `UserController`)
- Backend controllers: `Backend\{Entity}Controller`
- Auth controllers: `Auth\{Action}Controller`
- Middleware: Single word (e.g., `Developer`, `Employee`)
- Traits: `Has{Feature}` (e.g., `HasAvatar`, `HasType`)

### Return Types
- Always declare return types on public methods
- Use explicit types: `string`, `bool`, `void`, `array`, etc.
- Example: `public function getAvatar(): string`

### Route Naming
- API routes: `api.user.{action}` (e.g., `api.user.index`)
- Backend routes: `backend.user.{action}` (e.g., `backend.user.show`)
- Web auth routes: Standard Laravel auth naming (e.g., `password.reset`)

### Views
- Use `user::` namespace
- Backend views: `user::backend.{view}`
- Auth views: `user::auth.{view}`

## Testing

Run tests from package root:
```bash
vendor/bin/phpunit
```

## Artisan Commands

### user:reset_password
Resets the developer account password (uses `config('developer.email')`):
```bash
php artisan user:reset_password
```
Outputs a random 32-character password.

## Code Style

Run Laravel Pint for code formatting:
```bash
vendor/bin/pint --test  # Check only
vendor/bin/pint         # Fix
```

## Dependencies

- `bongo/framework` - Provides AbstractServiceProvider, AbstractController, AbstractEventHandler, traits
- Laravel 10+
- PHP 8.2+
- Laravel Sanctum (API authentication)

## Important Notes

1. **Developer Protection**: Non-developer users cannot access developer accounts in the backend (404 error)
2. **Middleware Hierarchy**: `employee` is most permissive, `developer` is most restrictive
3. **Cache Management**: `UserEventHandler` clears `packages` cache on user save
4. **View Composer**: `UserComposer` injects cached user list into `user::backend.partials.dropdowns.users`
5. **Password Security**: Always use `Hash::make()` when setting passwords
6. **Soft Deletes**: Users are soft-deleted, not hard-deleted
7. **Audit Fields**: Tracks `created_by`, `updated_by`, `deleted_by` (requires framework support)
8. **User Alias**: Service provider creates `'User'` alias for `Bongo\User\Models\User`
