# StripeConnectService

A dedicated service class for handling all Stripe Connect operations in the Laravel application.

## Overview

The `StripeConnectService` class encapsulates all Stripe Connect functionality, providing a clean separation of concerns and making the code more maintainable and testable.

## Features

- **Account Creation**: Create Stripe Connect accounts with prefilled user information
- **Onboarding Management**: Generate and manage onboarding links
- **Account Status**: Retrieve and monitor account status
- **Data Validation**: Validate prefilled data before account creation
- **Error Handling**: Comprehensive error handling for all operations
- **Country Support**: Get list of supported countries for Stripe Connect

## Service Methods

### `createConnectAccount(User $user): array`

Creates a basic Stripe Connect account using existing user information.

**Parameters:**
- `$user` - The authenticated user

**Returns:**
```php
[
    'success' => true/false,
    'message' => 'Success or error message',
    'account_id' => 'acct_1234567890', // Only on success
    'account' => { /* Stripe account object */ } // Only on success
]
```

### `createConnectAccountWithPrefill(User $user, array $data): array`

Creates a Connect account with detailed prefilled information.

**Parameters:**
- `$user` - The authenticated user
- `$data` - Array containing account information

**Data Structure:**
```php
[
    'business_type' => 'individual|company',
    'country' => 'US', // 2-letter country code
    'email' => 'user@example.com',
    'first_name' => 'John',
    'last_name' => 'Doe',
    'phone' => '+1234567890', // Optional
    'address_line1' => '123 Main St', // Optional
    'address_city' => 'New York', // Optional
    'address_state' => 'NY', // Optional
    'address_postal_code' => '10001' // Optional
]
```

### `createAccountLink(User $user, string $refreshUrl, string $returnUrl): array`

Generates an onboarding link for the user to complete their account setup.

**Parameters:**
- `$user` - The authenticated user
- `$refreshUrl` - URL to redirect to if onboarding needs to be refreshed
- `$returnUrl` - URL to redirect to after onboarding completion

**Returns:**
```php
[
    'success' => true/false,
    'onboarding_url' => 'https://connect.stripe.com/setup/c/...', // Only on success
    'expires_at' => 1234567890, // Only on success
    'message' => 'Success or error message'
]
```

### `getAccountStatus(User $user): array`

Retrieves the current status of the user's Connect account.

**Returns:**
```php
[
    'success' => true/false,
    'account' => [
        'id' => 'acct_1234567890',
        'charges_enabled' => true/false,
        'payouts_enabled' => true/false,
        'details_submitted' => true/false,
        'requirements' => { /* Stripe requirements object */ }
    ],
    'message' => 'Success or error message'
]
```

### `refreshAccountLink(User $user, string $refreshUrl, string $returnUrl): array`

Handles refresh requests from Stripe Connect onboarding flow.

### `handleOnboardingReturn(User $user): array`

Handles return from Stripe Connect onboarding and updates user status.

**Returns:**
```php
[
    'success' => true/false,
    'completed' => true/false, // Whether onboarding was completed
    'message' => 'Success or error message'
]
```

### `validatePrefillData(array $data): array`

Validates prefilled data for Connect account creation.

**Returns:**
```php
[
    // Array of validation error messages, empty if valid
]
```

### `getSupportedCountries(): array`

Returns a list of countries supported by Stripe Connect.

**Returns:**
```php
[
    'US' => 'United States',
    'CA' => 'Canada',
    'GB' => 'United Kingdom',
    // ... more countries
]
```

## Usage Examples

### In Controller

```php
use App\Services\StripeConnectService;

class StripeController extends Controller
{
    protected $stripeConnectService;

    public function __construct(StripeConnectService $stripeConnectService)
    {
        $this->stripeConnectService = $stripeConnectService;
    }

    public function createAccount(Request $request)
    {
        $user = Auth::user();
        $result = $this->stripeConnectService->createConnectAccount($user);
        
        $statusCode = $result['success'] ? 200 : 400;
        return response()->json($result, $statusCode);
    }
}
```

### Direct Service Usage

```php
use App\Services\StripeConnectService;

$stripeService = app(StripeConnectService::class);
$result = $stripeService->createConnectAccount($user);

if ($result['success']) {
    // Handle success
    $accountId = $result['account_id'];
} else {
    // Handle error
    $errorMessage = $result['message'];
}
```

## Error Handling

The service provides comprehensive error handling for:

- **Stripe API Errors**: Caught and returned with descriptive messages
- **Validation Errors**: Data validation with specific error messages
- **Authentication Errors**: User authentication checks
- **Account State Errors**: Checks for existing accounts, etc.

## Configuration

The service automatically handles environment-specific API keys:

- **Local Environment**: Uses test API keys
- **Production Environment**: Uses live API keys

## Benefits

1. **Separation of Concerns**: Business logic separated from controller logic
2. **Reusability**: Service can be used across multiple controllers
3. **Testability**: Easy to unit test service methods
4. **Maintainability**: Centralized Stripe Connect logic
5. **Error Handling**: Consistent error handling across all operations
6. **Type Safety**: Strong typing with return arrays and parameter types

## Testing

The service can be easily tested by mocking Stripe API calls:

```php
use App\Services\StripeConnectService;
use App\Models\User;

class StripeConnectServiceTest extends TestCase
{
    public function test_create_connect_account()
    {
        $user = User::factory()->create();
        $service = new StripeConnectService();
        
        // Mock Stripe API calls
        // Test service methods
    }
}
```

## Dependencies

- Laravel Framework
- Stripe PHP SDK
- User Model (with Stripe Connect fields)

## Future Enhancements

- Webhook handling for account updates
- Payment processing with Connect accounts
- Account verification workflows
- Comprehensive logging
- Rate limiting
- Caching for supported countries
