# Pricing Type Feature Documentation

## Overview
This document describes the new **Pricing Type** feature added to the Addon Request Types system. This feature allows each request type to specify how pricing should be handled.

## Feature Details

### Pricing Types
Three pricing models are now available for each addon request type:

1. **Free** (`free`)
   - The service is provided at no cost to the traveler
   - No base_cost is required
   - Example use cases: Complimentary services, included benefits

2. **Fixed Price** (`fixed_price`)
   - The service has a predetermined, fixed cost
   - Uses the `base_cost` field for the price
   - Example use cases: Standard items like headphones, SIM cards, hotel meals

3. **Quotation Required** (`quotation_required`)
   - The department needs to provide a custom price quote
   - Price varies based on specific requirements
   - Example use cases: Flight tickets, seat upgrades, room upgrades

## Database Changes

### New Column
- **Table**: `addon_request_types`
- **Column**: `pricing_type`
- **Type**: `VARCHAR(30)`
- **Default**: `fixed_price`
- **Values**: `free`, `fixed_price`, `quotation_required`
- **Index**: Added for performance

### Migration File
- `database/migrations/2025_11_17_000001_add_pricing_type_to_addon_request_types_table.php`

To apply the migration:
```bash
php artisan migrate
```

To rollback:
```bash
php artisan migrate:rollback
```

## Code Changes

### 1. New Enum Class
**File**: `app/Enums/AddonRequest/PricingType.php`

```php
use App\Enums\AddonRequest\PricingType;

// Get all options
PricingType::toArray(); // ['free', 'fixed_price', 'quotation_required']

// Get options with labels for select dropdown
PricingType::toSelectArray();

// Check pricing type
$type->pricing_type === PricingType::FREE;
```

#### Enum Methods
- `label()`: Get Chinese label (免費, 固定價格, 需報價)
- `labelEn()`: Get English label (Free, Fixed Price, Quotation Required)
- `description()`: Get detailed description
- `requiresBaseCost()`: Check if base cost is required
- `allowsQuotation()`: Check if quotation is allowed
- `toArray()`: Get all values as array
- `toSelectArray()`: Get all values with labels for UI dropdowns

### 2. Model Updates
**File**: `app/Models/AddonRequestType.php`

#### New Fillable Field
```php
protected $fillable = [
    // ... other fields
    'pricing_type',
];
```

#### New Cast
```php
protected $casts = [
    // ... other casts
    'pricing_type' => PricingType::class,
];
```

#### New Scopes
```php
AddonRequestType::free()->get();              // Get all free types
AddonRequestType::fixedPrice()->get();        // Get all fixed price types
AddonRequestType::quotationRequired()->get(); // Get all quotation required types
```

#### New Helper Methods
```php
$type->isFree();                    // bool
$type->isFixedPrice();              // bool
$type->requiresQuotation();         // bool
$type->getPricingTypeLabel();       // Chinese label
$type->getPricingTypeLabelEn();     // English label
```

### 3. Controller Updates
**File**: `app/Http/Controllers/Api/AddonRequestTypeController.php`

#### Validation Rules (Create)
```php
'pricing_type' => 'required|string|in:free,fixed_price,quotation_required'
```

#### Validation Rules (Update)
```php
'pricing_type' => 'sometimes|required|string|in:free,fixed_price,quotation_required'
```

#### New Endpoint: Get Pricing Type Options
```
GET /api/addon-requests/types/pricing-types
```

Response:
```json
{
  "success": true,
  "data": [
    {
      "value": "free",
      "label": "免費",
      "label_en": "Free",
      "description": "此項目免費提供"
    },
    {
      "value": "fixed_price",
      "label": "固定價格",
      "label_en": "Fixed Price",
      "description": "此項目有固定價格"
    },
    {
      "value": "quotation_required",
      "label": "需報價",
      "label_en": "Quotation Required",
      "description": "此項目需由部門報價"
    }
  ]
}
```

#### Index Endpoint Enhancement
The `/api/addon-requests/types` endpoint now includes pricing type options in the metadata:

```json
{
  "success": true,
  "data": [...],
  "meta": {
    "pricing_types": [...]
  }
}
```

### 4. Updated Controllers
**File**: `app/Http/Controllers/Api/AddonRequestController.php`

The following endpoints now include `pricing_type` in the response:
- `GET /api/addon-requests` (index) - List view
- `GET /api/addon-requests/{id}` (show) - Detail view

### 5. Seeder Updates
**File**: `database/seeders/AddonRequestSeeder.php`

All request types now include appropriate pricing types:

| Type | Pricing Type | Reason |
|------|--------------|--------|
| Flight Ticket (機票) | quotation_required | Prices vary by route and date |
| In-flight Meal (飛機餐) | fixed_price | Standard meal price |
| Seat Upgrade (加價選位) | quotation_required | Varies by flight and seat class |
| Hotel Dining (酒店餐食) | fixed_price | Standard meal cost |
| Room Upgrade (房型升等) | quotation_required | Depends on hotel and room type |
| Headphones (耳機) | fixed_price | Fixed product price |
| SIM Card (SIM卡) | fixed_price | Fixed product price |
| Insurance (保險) | fixed_price | Standard insurance package |

## API Endpoints

### List All Request Types
```
GET /api/addon-requests/types
```

Response includes pricing_type for each type:
```json
{
  "success": true,
  "data": [
    {
      "id": 1,
      "category_id": 1,
      "name": "機票",
      "name_en": "Flight Ticket",
      "type_code": "FLIGHT_TICKET",
      "pricing_type": "quotation_required",
      "base_cost": null,
      "cost_currency": "TWD",
      ...
    }
  ],
  "meta": {
    "pricing_types": [...]
  }
}
```

### Get Specific Request Type
```
GET /api/addon-requests/types/{id}
```

Returns full type details including pricing_type.

### Create Request Type
```
POST /api/addon-requests/types
```

Request body:
```json
{
  "category_id": 1,
  "name": "新項目",
  "name_en": "New Item",
  "type_code": "NEW_ITEM",
  "pricing_type": "fixed_price",
  "base_cost": 500.00,
  "cost_currency": "TWD",
  "requires_approval": false,
  "processing_time_hours": 24,
  "is_active": true,
  "sort_order": 1
}
```

### Update Request Type
```
PUT /api/addon-requests/types/{id}
```

Request body (all fields optional):
```json
{
  "pricing_type": "quotation_required",
  "base_cost": null
}
```

### Get Pricing Type Options
```
GET /api/addon-requests/types/pricing-types
```

Returns all available pricing types with labels and descriptions.

## Frontend Integration

### Display Pricing Type
```javascript
// In listing/table
{type.pricing_type} // Displays: free, fixed_price, or quotation_required

// With label
{type.pricing_type === 'free' ? '免費' : 
 type.pricing_type === 'fixed_price' ? '固定價格' : '需報價'}
```

### Form Field
```html
<select name="pricing_type" required>
  <option value="free">免費 (Free)</option>
  <option value="fixed_price">固定價格 (Fixed Price)</option>
  <option value="quotation_required">需報價 (Quotation Required)</option>
</select>
```

### Conditional Logic
```javascript
// Show base_cost field only for fixed_price
if (pricing_type === 'fixed_price') {
  // Show base_cost input field
}

// Show quotation note for quotation_required
if (pricing_type === 'quotation_required') {
  // Display message: "This item requires a price quotation from the department"
}

// Hide price for free items
if (pricing_type === 'free') {
  // Display "Free" instead of showing price
}
```

## Business Logic Examples

### Example 1: Creating an Addon Request
When a user creates an addon request, the system should:
1. Load the selected request type including its pricing_type
2. If pricing_type is `free`, set estimated_cost to 0 or null
3. If pricing_type is `fixed_price`, use the type's base_cost as estimated_cost
4. If pricing_type is `quotation_required`, leave estimated_cost empty and notify the department

### Example 2: Filtering by Pricing Type
```php
// Get all free services
$freeServices = AddonRequestType::free()->active()->get();

// Get services that need quotations
$quotationServices = AddonRequestType::quotationRequired()->get();

// Get services with fixed pricing for a specific category
$fixedPriceServices = AddonRequestType::where('category_id', $categoryId)
    ->fixedPrice()
    ->get();
```

### Example 3: Pricing Logic
```php
$type = AddonRequestType::find($typeId);

if ($type->isFree()) {
    $estimatedCost = 0;
} elseif ($type->isFixedPrice()) {
    $estimatedCost = $type->base_cost;
} elseif ($type->requiresQuotation()) {
    // Leave cost null, department will provide quote
    $estimatedCost = null;
    // Send notification to department for quotation
}
```

## Testing

### Manual Testing Steps

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

2. **Seed Data** (if needed)
   ```bash
   php artisan db:seed --class=AddonRequestSeeder
   ```

3. **Test API Endpoints**
   ```bash
   # Get all types with pricing info
   curl -X GET "http://localhost/api/addon-requests/types"
   
   # Get pricing type options
   curl -X GET "http://localhost/api/addon-requests/types/pricing-types"
   
   # Create new type with pricing
   curl -X POST "http://localhost/api/addon-requests/types" \
     -H "Content-Type: application/json" \
     -d '{"category_id":1,"name":"Test","pricing_type":"fixed_price","base_cost":100}'
   ```

4. **Verify Database**
   ```sql
   SELECT id, name, pricing_type, base_cost FROM addon_request_types;
   ```

### Expected Results
- All existing types have pricing_type set to appropriate values
- Flight tickets and upgrades set to `quotation_required`
- Standard items (headphones, SIM cards) set to `fixed_price`
- API responses include pricing_type field
- Validation prevents invalid pricing_type values

## Migration Notes

### For Existing Data
The migration automatically:
1. Sets pricing_type to `free` for items with no base_cost or base_cost = 0
2. Sets pricing_type to `fixed_price` for items with base_cost > 0
3. Sets pricing_type to `quotation_required` for flight tickets

### Rollback Plan
```bash
php artisan migrate:rollback --step=1
```

This will:
- Remove the pricing_type column
- Drop the pricing_type index
- Restore the table to its previous state

## Support & Questions

If you encounter any issues:
1. Check the migration ran successfully: `php artisan migrate:status`
2. Verify seeder data matches expected pricing types
3. Check enum values in API responses match: `free`, `fixed_price`, `quotation_required`
4. Ensure validation rules are working on create/update operations

## Summary

The pricing_type feature provides a structured way to handle different pricing models for addon request types. This enables:
- Clear communication of pricing expectations to users
- Automatic cost calculation for fixed-price items
- Workflow triggers for items requiring quotations
- Proper handling of complimentary services

All existing APIs have been updated to support this field, and new endpoints provide easy access to pricing type options for frontend integration.

