# Per-User Pricing System

## Overview

The per-user pricing system allows packages to have dynamic pricing based on the number of users. Instead of a fixed price, packages can charge a base amount per user, making them scalable for different organization sizes.

## Example Scenario

- **Package Price**: $100 per user
- **9 Users**: Total cost = $100 × 9 = $900
- **15 Users**: Total cost = $100 × 15 = $1,500

## Database Changes

### Packages Table (New Fields)

```php
$table->boolean('is_per_user_pricing')->default(false);     // Enable per-user pricing
$table->decimal('base_price_per_user', 8, 2)->default(0);   // Price per user ($100.00)
$table->integer('min_users')->default(1);                   // Minimum users required
$table->integer('max_users')->nullable();                   // Maximum users allowed (null = unlimited)
```

### User Package Subscriptions Table (New Fields)

```php
$table->integer('user_count')->default(1);                  // Number of users in subscription
$table->decimal('price_per_user', 8, 2)->default(0);       // Snapshot of price per user at time of subscription
```

## Usage Examples

### 1. Creating a Per-User Pricing Package

```php
$package = Package::create([
    'name' => 'Business Plan',
    'slug' => 'business-plan',
    'type' => 'standard',
    'tier' => 2,
    'price' => 0, // Not used for per-user pricing
    'is_per_user_pricing' => true,
    'base_price_per_user' => 100.00, // $100 per user
    'min_users' => 1,
    'max_users' => 50, // Maximum 50 users
    'description' => 'Scalable business plan',
    'is_active' => true,
]);
```

### 2. Calculating Pricing

```php
// Calculate total price for 9 users
$totalPrice = $package->calculateTotalPrice(9); // Returns 900.00

// Get price per user
$pricePerUser = $package->getPricePerUser(); // Returns 100.00

// Validate user count
$isValid = $package->validateUserCount(9); // Returns true
```

### 3. Creating a Subscription

```php
$subscription = UserPackageSubscription::create([
    'user_id' => $user->id,
    'package_id' => $package->id,
    'subscription_type' => 'standard',
    'subscription_name' => $package->name,
    'total_price' => $package->calculateTotalPrice(9), // $900
    'user_count' => 9,
    'price_per_user' => $package->getPricePerUser(), // $100
    'started_at' => now(),
    'expires_at' => now()->addYear(),
    'status' => 'active',
]);
```

### 4. Updating User Count

```php
// Update subscription to 15 users
$success = $subscription->updateUserCount(15);
// This will recalculate: total_price = $100 × 15 = $1,500
```

## API Endpoints

### Calculate Package Pricing

```bash
POST /api/packages/{package}/calculate-pricing
Content-Type: application/json

{
    "user_count": 9
}
```

**Response:**
```json
{
    "package": {
        "id": 1,
        "name": "Business Plan",
        "is_per_user_pricing": true
    },
    "pricing": {
        "user_count": 9,
        "price_per_user": 100.00,
        "total_price": 900.00,
        "currency": "USD"
    }
}
```

### Update Subscription User Count

```bash
PATCH /api/packages/subscriptions/{subscription}/users
Content-Type: application/json

{
    "user_count": 15
}
```

**Response:**
```json
{
    "message": "Subscription updated successfully",
    "subscription": {
        "id": 1,
        "old_user_count": 9,
        "new_user_count": 15,
        "old_total_price": 900.00,
        "new_total_price": 1500.00,
        "price_difference": 600.00,
        "price_per_user": 100.00
    }
}
```

### Get All Packages with Pricing

```bash
GET /api/packages?user_count=10
```

## Model Methods

### Package Model

- `calculateTotalPrice(int $userCount)` - Calculate total price for given user count
- `getPricePerUser()` - Get price per user
- `validateUserCount(int $userCount)` - Check if user count is within limits
- `scopePerUserPricing($query)` - Get packages with per-user pricing
- `scopeFixedPricing($query)` - Get packages with fixed pricing

### UserPackageSubscription Model

- `updateUserCount(int $userCount)` - Update user count and recalculate pricing
- `getEffectivePricePerUser()` - Get effective price per user
- `hasPerUserPricing()` - Check if subscription uses per-user pricing

## Installation Steps

1. **Run Migration**
   ```bash
   php artisan migrate
   ```

2. **Seed Example Data**
   ```bash
   php artisan db:seed --class=PerUserPricingExampleSeeder
   ```

3. **Test API Endpoints**
   ```bash
   # Get packages with pricing for 10 users
   curl -X GET "http://localhost/api/packages?user_count=10" \
        -H "Authorization: Bearer YOUR_TOKEN"
   ```

## Benefits

1. **Scalable Pricing**: Organizations pay only for what they use
2. **Flexible Growth**: Easy to add or remove users
3. **Fair Pricing**: Small teams pay less, larger teams pay more
4. **Predictable Costs**: Clear per-user pricing model
5. **Revenue Optimization**: Better revenue scaling with customer growth

## Comparison: Fixed vs Per-User Pricing

| Scenario | Fixed Price ($2,500) | Per-User ($100/user) | Savings |
|----------|---------------------|---------------------|---------|
| 5 users  | $2,500             | $500                | $2,000  |
| 10 users | $2,500             | $1,000              | $1,500  |
| 15 users | $2,500             | $1,500              | $1,000  |
| 25 users | $2,500             | $2,500              | $0      |
| 30 users | $2,500             | $3,000              | -$500   |

Per-user pricing is more cost-effective for smaller teams, while fixed pricing becomes better for larger organizations beyond the break-even point.
