# Corporate Account Management API Documentation

## Overview
The Corporate Account Management system allows operators to create corporate accounts with automatically generated admin user credentials. This enables seamless onboarding of corporate clients with immediate dashboard access.

## System Features

✓ **Automatic Account Creation**: Both corporate account and admin user created simultaneously
✓ **Secure Credentials**: Temporary passwords generated and assigned automatically  
✓ **User-Account Linking**: Admin user automatically linked to corporate account
✓ **Relationship Management**: Full relationships between users and corporate accounts
✓ **Status Tracking**: Account status management (active, inactive, suspended)

## Database Schema

### Migration Applied
- **File**: `database/migrations/2026_02_17_000001_add_corporate_account_id_to_users.php`
- **Change**: Added `corporate_account_id` column to users table with FK to corporate_accounts

### Table Structure

**corporate_accounts Table**
- `id` (PK)
- `tenant_id` (FK)
- `user_id` (FK) - Created by user
- `company_name`
- `industry`
- `phone`
- `address`, `city`, `state`, `country`, `postal_code`
- `website`
- `status` (active|inactive|suspended)
- `total_employees`, `total_travelers`, `monthly_budget`
- `contract_start_date`, `contract_end_date`
- `created_at`, `updated_at`

**users Table** (Updated)
- Added: `corporate_account_id` (FK, nullable)

## API Endpoints

### 1. Create Corporate Account with Admin User
**POST** `/api/corporate-accounts/create-with-user`

**Purpose**: Create a new corporate account and automatically generate an admin user

**Authorization**: `auth:api` (Operator Admin required)

**Request Body**:
```json
{
    "company_name": "Acme Corporation",
    "industry": "Transportation",
    "admin_email": "admin@acme.com",
    "admin_name": "John Doe",
    "phone": "+1-555-0100",
    "address": "123 Main St",
    "city": "New York",
    "state": "NY",
    "country": "USA",
    "postal_code": "10001",
    "website": "https://acme.com"
}
```

**Response**:
```json
{
    "success": true,
    "message": "Corporate account created successfully",
    "data": {
        "corporate_account": {
            "id": 6,
            "company_name": "Acme Corporation",
            "industry": "Transportation",
            "status": "active"
        },
        "admin_user": {
            "id": 42,
            "email": "admin@acme.com",
            "name": "John Doe",
            "role": "Corporate Admin"
        }
    },
    "credentials": {
        "email": "admin@acme.com",
        "temporary_password": "EL8wXaszyxI3",
        "note": "Password should be changed on first login"
    }
}
```

### 2. List Corporate Accounts
**GET** `/api/corporate-accounts`

**Query Parameters**:
- `status`: Filter by status (active|inactive|suspended)
- `search`: Search by company name

**Response**:
```json
{
    "success": true,
    "data": [
        {
            "id": 6,
            "company_name": "Acme Corporation",
            "industry": "Transportation",
            "status": "active",
            ...
        }
    ],
    "total": 15,
    "per_page": 20,
    "current_page": 1
}
```

### 3. Get Corporate Account Details
**GET** `/api/corporate-accounts/{id}`

**Response**:
```json
{
    "success": true,
    "data": {
        "id": 6,
        "company_name": "Acme Corporation",
        "users": [
            {
                "id": 42,
                "email": "admin@acme.com",
                "name": "John Doe",
                "role": "Corporate Admin"
            }
        ],
        "adminUser": {
            "id": 42,
            "email": "admin@acme.com",
            "name": "John Doe",
            "role": "Corporate Admin"
        },
        ...
    }
}
```

### 4. Update Corporate Account
**PUT** `/api/corporate-accounts/{id}`

**Request Body**:
```json
{
    "company_name": "Acme Corporation Updated",
    "phone": "+1-555-0101",
    "status": "active"
}
```

### 5. Delete Corporate Account
**DELETE** `/api/corporate-accounts/{id}`

**Note**: Deletes the account and dissociates all linked users

## Model Relationships

### User Model
```php
public function corporateAccount(): BelongsTo
{
    return $this->belongsTo(CorporateAccount::class);
}
```

### CorporateAccount Model
```php
public function users(): HasMany
{
    return $this->hasMany(User::class);
}

public function adminUser()
{
    return $this->hasOne(User::class)->where('role', 'Corporate Admin');
}
```

## Usage Flow

### Creating a Corporate Account

1. **Operator Admin** calls the `createWithUser` endpoint with company details
2. **System automatically**:
   - Creates CorporateAccount record
   - Generates temporary password
   - Creates User record as "Corporate Admin"
   - Links user to corporate account via `corporate_account_id`
3. **Response** includes credentials for admin login
4. **Admin** logs in and changes password on first login

### Integration with LQC

When converting a Quote to Contract from a corporate client:

1. Quote is linked to corporate_account_id
2. Contract inherits corporate_account_id from quote
3. All financial reporting tied to corporate account

## Example Implementation

### Backend (Laravel)
```php
// In your controller or service
$response = Http::post('/api/corporate-accounts/create-with-user', [
    'company_name' => 'New Client Corp',
    'admin_email' => 'client-admin@newclient.com',
    'admin_name' => 'Client Manager',
    ...
]);

$credentials = $response['credentials'];
// Send email with: $credentials['email'] and $credentials['temporary_password']
```

### Frontend (Angular)
```typescript
// In CorporateAccountService
createWithUser(data: any) {
    return this.http.post('/api/corporate-accounts/create-with-user', data);
}

// In component
createCorporateAccount() {
    this.corporateAccountService.createWithUser({
        company_name: this.form.company_name,
        admin_email: this.form.admin_email,
        admin_name: this.form.admin_name,
        ...
    }).subscribe(response => {
        console.log('Account created:', response.data);
        // Show credentials to operator
        this.showCredentials(response.credentials);
    });
}
```

## Security Considerations

✓ **Temporary Passwords**: Operators don't see plaintext passwords
✓ **Password Hashing**: All passwords hashed using Laravel's Hash facade
✓ **Email Verification**: Send credentials via secure email (implement Mailable)
✓ **Role-Based Access**: Only Corporate Admins can access dashboard
✓ **Tenant Isolation**: Each admin bound to specific tenant

## Next Steps

1. **Implement Email Notification**:
   - Create a Mailable for sending credentials
   - Add to createWithUser method

2. **Add Password Reset Flow**:
   - Implement forgot-password for corporate admin reset

3. **Add Corporate Admin Dashboard**:
   - Route to `/corporate-admin` for account management

4. **Implement SLA Management**:
   - Link contracts to corporate accounts
   - Track SLA metrics per account

## Testing

To test the implementation:
```bash
php test_corporate_account_creation.php
```

This creates a test corporate account and admin user, then verifies relationships.
