# Bongo Profile Package - Cursor AI Rules

## Overview
This package provides user profile management functionality within the admin area of Bongo applications. It allows authenticated users to view and update their personal details, including contact information, password, and avatar image.

## Project Structure

```
default/profile/
├── src/
│   ├── Http/
│   │   └── Controllers/
│   │       └── Backend/
│   │           ├── ProfileController.php       # Main profile CRUD operations
│   │           └── ProfileImageController.php  # Avatar image upload handling
│   ├── Routes/
│   │   └── backend.php                         # Admin routes (prefix: /admin/profile)
│   ├── Translations/
│   │   └── en/
│   │       └── backend.php                     # Translation strings
│   ├── Views/
│   │   └── backend/
│   │       ├── index.blade.php                 # Profile view page
│   │       ├── edit.blade.php                  # Profile edit page
│   │       └── partials/
│   │           ├── form/
│   │           │   └── details.blade.php       # Edit form fields
│   │           └── tab_detail.blade.php        # View tab content
│   └── ProfileServiceProvider.php              # Service provider
├── tests/
│   └── TestCase.php                            # Base test class
├── composer.json                               # Package dependencies
└── phpunit.xml                                 # PHPUnit configuration
```

## Architecture & Design Patterns

### Service Provider Pattern
The package uses `ProfileServiceProvider` which extends `Bongo\Framework\Providers\AbstractServiceProvider`. This provides automatic bootstrapping:

- **Module Name**: `profile`
- **Routes**: Auto-registered from `src/Routes/backend.php` with `backend.*` prefix
- **Views**: Auto-registered from `src/Views/profile/` namespace
- **Translations**: Auto-registered from `src/Translations/` with `profile::` namespace
- **Middleware**: Backend routes automatically receive `auth` and `employee` middleware

### Controller Pattern
All controllers extend `Bongo\Framework\Http\Controllers\AbstractController`:

- `ProfileController`: Handles view, edit, and update operations
- `ProfileImageController`: Handles avatar image uploads via JSON API

### Dependencies
- **bongo/framework**: Core framework functionality and base classes
- **bongo/user**: User model (`Bongo\User\Models\User`)
- **bongo/image**: Image handling services (`Bongo\Image\Services\AvatarImage`, `StoreImageRequest`)

## Coding Conventions

### Namespace
- Root namespace: `Bongo\Profile`
- Controllers: `Bongo\Profile\Http\Controllers\Backend`

### Method Signatures
Controllers use type hints and return types:

```php
public function index()                         // Returns view
public function edit()                          // Returns view
public function update(Request $request)        // Returns redirect
public function upload(StoreImageRequest $request): JsonResponse  // Returns JSON
```

### Validation
Password validation enforces strong passwords:
```php
'password' => 'sometimes|nullable|string|min:8|confirmed|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/'
```

Requirements:
- Minimum 8 characters
- At least 1 uppercase letter
- At least 1 lowercase letter
- At least 1 number
- At least 1 special character (#?!@$%^&*-)

### Helper Functions
- `user()`: Returns the currently authenticated user instance

### View Conventions
- Views extend `framework::backend.layouts.app` layout
- Use Blade components from `bongo/blade` package:
  - `@component('blade::content_header')` - Page header with actions
  - `@component('blade::content_body')` - Main content wrapper
  - `@component('blade::card')` - Card container
  - `@input()` - Input field directive
  - `@static()` - Static field display directive
  - `@label()` - Label directive
  - `@backButton()` - Back button directive
  - `@editButton()` - Edit button directive
  - `@saveButton()` - Save button directive
  - `<file-uploader>` - Vue.js file upload component

### Route Naming
Routes follow the pattern `backend.profile.{action}`:
- `backend.profile.index` - View profile (GET /admin/profile)
- `backend.profile.edit` - Edit form (GET /admin/profile/edit)
- `backend.profile.update` - Update profile (POST /admin/profile/update)
- `backend.profile.image` - Upload avatar (POST /admin/profile/image)

### Translation Keys
Format: `profile::backend.{key}`
- Use `trans('profile::backend.update_success')` for flash messages
- Available keys: `index`, `show`, `edit`, `update`, `update_success`, `update_failed`, `delete`, `delete_success`, `delete_failed`

## Common Tasks

### Adding a New Field to Profile

1. **Add to edit form** (`src/Views/backend/partials/form/details.blade.php`):
```php
@input(['name' => 'new_field', 'value' => $user->new_field])
```

2. **Add to view tab** (`src/Views/backend/partials/tab_detail.blade.php`):
```php
@static(['name' => 'New Field', 'value' => $user->new_field])
```

3. **Add validation** in `ProfileController::update()`:
```php
$request->validate([
    'new_field' => 'nullable|max:100',
    // ... existing rules
]);
```

4. **Add translation** (`src/Translations/en/backend.php`):
```php
'new_field' => 'New Field',
```

### Modifying Password Requirements

Edit the validation rule in `ProfileController::update()`:
```php
'password' => 'sometimes|nullable|string|min:8|confirmed|regex:/your-regex-here/'
```

### Customising Avatar Upload

Modify `ProfileImageController::upload()` to change image processing:
```php
$user = (new AvatarImage(user(), $files[0]))
    ->setWidth(200)  // Example customisation
    ->save();
```

### Adding Email Validation

The package already includes DNS validation for emails:
```php
'email' => "required|string|email:rfc,dns|unique:{$userTable},email,".user()->id.',id,deleted_at,NULL|max:50'
```

## Testing

### Running Tests
```bash
vendor/bin/phpunit
```

### Test Base Class
Extend `Bongo\Profile\Tests\TestCase` which:
- Loads `ProfileServiceProvider`
- Uses Orchestra Testbench for Laravel package testing
- Configures test database connection

### Writing Tests
```php
namespace Bongo\Profile\Tests;

class ProfileControllerTest extends TestCase
{
    public function test_user_can_view_profile()
    {
        // Test implementation
    }
}
```

## Available Commands

From package root:

```bash
# Run tests
vendor/bin/phpunit

# Check code style (Laravel Pint)
vendor/bin/pint --test

# Fix code style
vendor/bin/pint

# Static analysis (Larastan)
vendor/bin/phpstan analyse

# Install dependencies
composer install

# Update dependencies
rm -f composer.lock && composer update -W
```

## Integration Points

### User Model
The package relies on `Bongo\User\Models\User` having these methods/properties:
- `first_name`, `last_name`, `title`, `status`
- `telephone`, `mobile`, `email`
- `password` (hashed)
- `getAvatar()` method

### Image Service
Uses `Bongo\Image\Services\AvatarImage` for avatar processing:
```php
$user = (new AvatarImage($user, $uploadedFile))->save();
```

### Authentication
Routes require authenticated employee users (via middleware):
- `auth` - User must be authenticated
- `employee` - User must have employee role

### Flash Messages
Uses Laravel flash messages with custom `success()` macro:
```php
return redirect()
    ->route('backend.profile.index')
    ->success(trans('profile::backend.update_success'));
```

## Security Considerations

- **CSRF Protection**: All forms use `{{ csrf_field() }}`
- **Password Hashing**: Uses `Hash::make()` for password storage
- **Email Uniqueness**: Validates email uniqueness excluding current user
- **Soft Deletes**: Email validation considers `deleted_at` column
- **Strong Passwords**: Enforces complexity requirements
- **Authentication Required**: All routes protected by auth middleware
- **Role-Based Access**: Employee middleware restricts to staff users

## Extending AbstractServiceProvider

The package extends `Bongo\Framework\Providers\AbstractServiceProvider` which automatically:

1. **Registers routes** from `src/Routes/backend.php` with:
   - Prefix: `backend.profile`
   - Middleware: `['web', 'auth', 'employee']`
   - Name prefix: `backend.`

2. **Registers views** with namespace `profile::`:
   - View directory: `src/Views/`
   - Access via: `view('profile::backend.index')`

3. **Registers translations** with namespace `profile::`:
   - Translation directory: `src/Translations/`
   - Access via: `trans('profile::backend.edit')`

No additional configuration is required beyond setting `protected string $module = 'profile';`

## Common Issues

### Email Validation Fails
Ensure the user table name is correct in validation:
```php
$userTable = (new User())->getTable();
```

### Avatar Upload Fails
Check that:
- The `bongo/image` package is installed
- The user model has `getAvatar()` method
- File upload permissions are correct
- The `StoreImageRequest` validation passes

### Routes Not Registered
Verify that:
- `ProfileServiceProvider` is registered in the application
- The `$module` property is set to `'profile'`
- Routes file is at `src/Routes/backend.php`
