# Architecture Overview

This document provides a high-level overview of the Clip Redirect plugin architecture, including its components, design patterns, and how they interact.

## Plugin Structure

```
redirect/
├── clip-for-woocommerce.php          # Main plugin file
├── hooks.php                          # WordPress hooks registration
├── README.txt                         # WordPress.org plugin readme
├── assets/                            # Frontend and admin assets
│   ├── css/
│   │   └── settings.css              # Admin settings styles
│   ├── img/                          # Images and logos
│   │   ├── banners/                  # Checkout banners (Spanish/English)
│   │   └── brands/                   # Card brand logos
│   └── js/
│       ├── admin-settings.js         # Admin settings JavaScript
│       ├── checkout-blocks.js        # WooCommerce Blocks integration
│       └── gateway.js                # Frontend payment handling
├── i18n/                             # Internationalization
│   └── languages/                    # Translation files (.po, .mo, .pot)
├── src/                              # PHP source code
│   ├── api/                          # API communication layer
│   │   ├── class-api-connector.php
│   │   ├── class-api-interface.php
│   │   └── class-clip-redirect-api.php
│   ├── blocks/                       # WooCommerce Blocks support
│   │   └── checkout_blocks.js
│   ├── gateway/                      # Payment gateway implementation
│   │   ├── class-clip-redirect-blocks.php
│   │   ├── class-post-checkout.php
│   │   ├── class-request-deposit-action.php
│   │   ├── class-settings.php
│   │   └── class-wc-clip-redirect.php
│   ├── helper/                       # Helper classes with traits
│   │   ├── class-assets-trait.php
│   │   ├── class-country-currency-trait.php
│   │   ├── class-database-trait.php
│   │   ├── class-debug-trait.php
│   │   ├── class-handle-payment-trait.php
│   │   ├── class-helper.php
│   │   ├── class-logger-trait.php
│   │   ├── class-migration-trait.php
│   │   ├── class-settings-trait.php
│   │   ├── class-templates-trait.php
│   │   └── class-validations-trait.php
│   ├── onboarding/                   # Onboarding flow
│   │   ├── class-main.php
│   │   └── class-save-settings-action.php
│   ├── orders/                       # Order-related functionality
│   │   └── class-webhooks.php
│   └── sdk/                          # Clip SDK wrapper
│       └── class-clip-redirect-sdk.php
└── templates/                        # PHP templates
    ├── page-onboarding.php
    ├── setting-payment-card-brands.php
    ├── setting-payment-installments.php
    └── setting-payment-type.php
```

## Architecture Diagram

```mermaid
graph TB
    subgraph "WordPress/WooCommerce Layer"
        WP[WordPress Core]
        WC[WooCommerce]
        Hooks[WordPress Hooks System]
    end
    
    subgraph "Clip Redirect Plugin"
        Main[ClipRedirect<br/>Main Plugin Class]
        
        subgraph "Gateway Layer"
            Gateway[WC_ClipRedirect<br/>Payment Gateway]
            Settings[Settings<br/>Configuration]
            PostCheckout[PostCheckout<br/>Order Receipt Page]
            RequestDeposit[RequestDepositAction<br/>AJAX Handler]
            Blocks[ClipRedirectBlocks<br/>Blocks Integration]
        end
        
        subgraph "Helper Layer"
            Helper[Helper<br/>Utility Class]
            AssetsTrait[Assets Trait]
            LoggerTrait[Logger Trait]
            SettingsTrait[Settings Trait]
            ValidationsTrait[Validations Trait]
            HandlePaymentTrait[Handle Payment Trait]
            TemplatesTrait[Templates Trait]
            DatabaseTrait[Database Trait]
            DebugTrait[Debug Trait]
        end
        
        subgraph "Business Logic Layer"
            SDK[ClipRedirectSdk<br/>API Wrapper]
            Onboarding[Onboarding Main<br/>Initial Setup]
            SaveSettings[SaveSettingsAction<br/>Credential Handler]
            Webhooks[Webhooks<br/>Payment Notifications]
        end
        
        subgraph "API Layer"
            APIConnector[API Connector]
            APIInterface[API Interface]
            ClipAPI[ClipRedirectApi<br/>HTTP Client]
        end
    end
    
    subgraph "External Services"
        ClipAPIService[Clip API<br/>api.payclip.com]
        ClipOnboarding[Clip Onboarding<br/>plugin-onboarding.payclip.com]
        ClipCheckout[Clip Hosted Checkout]
    end
    
    subgraph "Data Storage"
        DB[(WordPress Database)]
        Options[wp_options table]
        OrderMeta[wp_postmeta table]
        Logs[wp-content/uploads/wc-logs/]
    end
    
    %% WordPress Integration
    WP --> Hooks
    WC --> Hooks
    Hooks --> Main
    Main --> Gateway
    WC --> Gateway
    
    %% Gateway Connections
    Gateway --> Settings
    Gateway --> PostCheckout
    Gateway --> RequestDeposit
    Gateway --> Helper
    Gateway --> SDK
    Gateway --> Blocks
    
    %% Helper Connections
    Helper --> AssetsTrait
    Helper --> LoggerTrait
    Helper --> SettingsTrait
    Helper --> ValidationsTrait
    Helper --> HandlePaymentTrait
    Helper --> TemplatesTrait
    Helper --> DatabaseTrait
    Helper --> DebugTrait
    
    %% Business Logic Connections
    Onboarding --> SaveSettings
    SaveSettings --> SDK
    RequestDeposit --> SDK
    PostCheckout --> Helper
    Webhooks --> Helper
    HandlePaymentTrait --> SDK
    ValidationsTrait --> SDK
    
    %% SDK Connections
    SDK --> APIConnector
    APIConnector --> APIInterface
    APIInterface --> ClipAPI
    ClipAPI --> ClipAPIService
    
    %% External Services
    Onboarding -.-> ClipOnboarding
    PostCheckout -.-> ClipCheckout
    Webhooks <-. HTTP POST .-> ClipAPIService
    
    %% Data Storage
    SettingsTrait --> Options
    DatabaseTrait --> OrderMeta
    Gateway --> OrderMeta
    LoggerTrait --> Logs
    DebugTrait --> Logs
    
    style Main fill:#4a90e2
    style Gateway fill:#50c878
    style SDK fill:#f39c12
    style Helper fill:#9b59b6
    style ClipAPIService fill:#e74c3c
```

## Component Descriptions

### Core Components

#### 1. ClipRedirect (Main Class)
**File**: `clip-for-woocommerce.php`

The main plugin class that handles:
- Plugin initialization and autoloading
- System requirements checking
- Plugin activation/deactivation
- Hook registration
- Constants definition

**Key Constants**:
```php
const GATEWAY_ID = 'wc_clipredirect';
const META_ORDER_PAYMENT_ID = '_CLIPREDIRECT_PAYMENT_ID';
const META_CLIPREDIRECT_PAYMENT_STATUS = '_CLIPREDIRECT_PAYMENT_STATUS';
const META_CLIPREDIRECT_RECEIPT_NO = '_CLIPREDIRECT_RECEIPT_NO';
const CLIPREDIRECT_ENVIRONMENT = 'dev'; // or 'prod'
```

**Autoloader**:
```php
spl_autoload_register(function ( $class ) {
    if ( strpos( $class, 'ClipRedirect' ) === false ) {
        return;
    }
    // Convert class name to file path
    // Example: Conexa\ClipRedirect\Gateway\WC_ClipRedirect
    //       -> src/gateway/class-wc-clip-redirect.php
});
```

#### 2. WC_ClipRedirect (Payment Gateway)
**File**: `src/gateway/class-wc-clip-redirect.php`

Extends `WC_Payment_Gateway` to integrate with WooCommerce:
- Gateway configuration and settings
- Payment processing
- Refund handling
- Custom field rendering
- Banner display logic

**Key Methods**:
- `__construct()` - Initialize gateway
- `init_form_fields()` - Define settings fields
- `payment_fields()` - Display payment method UI
- `process_payment()` - Handle order submission
- `process_refund()` - Handle refund requests
- `thankyou_page()` - Order received page actions

#### 3. Helper (Utility Class)
**File**: `src/helper/class-helper.php`

Central utility class that uses traits for organization:

```php
class Helper {
    use TemplatesTrait;         // Template loading
    use LoggerTrait;            // Logging functionality
    use DebugTrait;             // Debug utilities
    use SettingsTrait;          // Settings management
    use AssetsTrait;            // Asset URL helpers
    use DatabaseTrait;          // Database queries
    use HandlePaymentTrait;     // Payment processing
    use CountryCurrencyTrait;   // Currency validation
    use ValidationsTrait;       // Credential validation
    use MigrationTrait;         // Version migrations
}
```

#### 4. ClipRedirectSdk (API Wrapper)
**File**: `src/sdk/class-clip-redirect-sdk.php`

Handles all communication with Clip API:
- Authentication (Basic Auth)
- Checkout creation
- Payment status retrieval
- Refund requests
- Credential validation

**Key Methods**:
```php
__construct( $api_key, $api_secret, $debug = false )
request_deposit( $order_id )           // Create checkout
get_payment_data( $payment_request_id ) // Get payment status
request_refund( $id, $amount, $reason ) // Request refund
validate_receipt()                      // Validate credentials
```

### Gateway Layer Components

#### 5. PostCheckout
**File**: `src/gateway/class-post-checkout.php`

Renders the "Pay with Clip" button on order received page:
- Button HTML generation
- JavaScript configuration
- Auto-trigger on redirect from checkout

#### 6. RequestDepositAction
**File**: `src/gateway/class-request-deposit-action.php`

AJAX handler for creating payment checkouts:
- Request validation (nonce, order ID)
- SDK integration
- Payment link creation
- Order meta update

#### 7. Settings
**File**: `src/gateway/class-settings.php`

Defines all gateway settings fields:
- Credentials section
- Checkout configuration
- Payment customization
- Advanced options

### Business Logic Components

#### 8. Onboarding\Main
**File**: `src/onboarding/class-main.php`

Handles initial plugin setup:
- Onboarding page registration
- iframe embedding
- URL parameter generation
- Language detection

#### 9. SaveSettingsAction
**File**: `src/onboarding/class-save-settings-action.php`

AJAX handler for saving credentials from onboarding:
- Nonce verification
- Credential sanitization
- Validation via SDK
- Option storage

#### 10. Webhooks
**File**: `src/orders/class-webhooks.php`

Processes payment status webhooks:
- Webhook validation
- Order lookup by payment ID
- Status update handling
- HTTP response management

### API Layer Components

#### 11. ClipRedirectApi
**File**: `src/api/class-clip-redirect-api.php`

HTTP client for Clip API:
- GET/POST request handling
- Authentication header injection
- Response parsing
- Error handling

**Connection Pattern**:
```php
$api = new ClipRedirectApi([
    'api_key' => $api_key,
    'api_secret' => $api_secret,
    'debug' => $debug,
]);

$response = $api->post('/v2/checkout', $data, $headers);
```

## Design Patterns

### 1. Trait-Based Architecture

The plugin uses PHP traits to organize helper functionality:

**Benefits**:
- Code reusability
- Single Responsibility Principle
- Easy to test individual traits
- Clear separation of concerns

**Example**:
```php
trait LoggerTrait {
    public static function log( $message ) {
        if ( Helper::get_option( 'log_enabled' ) === 'yes' ) {
            $logger = wc_get_logger();
            $logger->info( $message, array( 'source' => 'clip-for-woocommerce' ) );
        }
    }
}
```

### 2. Abstract Base Classes

RequestDepositAction uses an abstract base class pattern:

```php
abstract class RequestDepositAction {
    abstract public static function run( $order_id );
    abstract public static function validate_ajax_request();
    public static function ajax_callback_wp() { /* shared implementation */ }
}
```

### 3. Singleton Pattern (Implicit)

The Helper class uses static methods, acting as a singleton:

```php
Helper::log( 'Message' );
Helper::get_option( 'api_key' );
Helper::validate_credentials();
```

### 4. Template Method Pattern

Settings generation uses template methods for custom field types:

```php
// Gateway class
public function generate_{field_type}_html( $key, $settings ) {
    // Custom HTML generation
}

public function validate_{field_type}_field( $key, $value ) {
    // Custom validation
}
```

### 5. Dependency Injection

SDK is injected into gateway:

```php
public function __construct() {
    $this->api_key = $this->get_option( 'wc_clipredirect_api_key' );
    $this->api_secret = $this->get_option( 'wc_clipredirect_api_secret' );
    $this->sdk = new ClipRedirectSdk( $this->api_key, $this->api_secret );
}
```

## Data Flow

### 1. Order Creation Flow

```
Customer → WooCommerce → Gateway → Order (Pending) → Order Receipt Page
```

### 2. Payment Link Creation Flow

```
Button Click → AJAX Request → RequestDepositAction → SDK → Clip API
    ↓
Order Meta Update ← Payment Link ← SDK Response
    ↓
Customer Redirect to Clip Checkout
```

### 3. Webhook Flow

```
Clip API → Webhook Endpoint → Webhooks::listener()
    ↓
Validation → Order Lookup → Helper::handle_payment()
    ↓
SDK::get_payment_data() → Status Update → Order Meta Update
    ↓
HTTP 200 OK → Clip API
```

### 4. Configuration Flow

```
Admin → Settings Page → Form Submit → Gateway::process_admin_options()
    ↓
Validation → Options Update → Credential Validation
    ↓
Success/Error Notice → Admin
```

## Database Schema

### WordPress Options

| Option Key | Type | Description |
|-----------|------|-------------|
| `woocommerce_wc_clipredirect_settings` | Serialized Array | All plugin settings |
| `clip_first_onboarding` | Boolean | First-time setup flag |
| `clipredirect_migration_v2_done` | Boolean | Migration completion flag |

### Order Meta

| Meta Key | Type | Description |
|----------|------|-------------|
| `_CLIPREDIRECT_PAYMENT_ID` | String | Clip payment request ID |
| `_CLIPREDIRECT_PAYMENT_STATUS` | String | Current payment status |
| `_CLIPREDIRECT_RECEIPT_NO` | String | Clip receipt number |

## API Endpoints

### WordPress Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/wc-api/wc-clip` | POST | Webhook listener |
| `/wp-admin/admin-ajax.php?action=clip_save_settings` | POST | Save onboarding credentials |
| `/wp-admin/admin-ajax.php?action=clip_request_deposit_action` | POST | Create payment checkout |

### Clip API Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/v2/checkout` | POST | Create payment checkout |
| `/v2/checkout/{id}` | GET | Get payment status |
| `/refunds/` | POST | Request refund |
| `/payments/receipt-no/{receipt}` | GET | Validate receipt (credentials) |

## Security Measures

### 1. Nonce Verification

All AJAX requests verify WordPress nonces:

```php
if ( ! wp_verify_nonce( $_POST['nonce'], \ClipRedirect::GATEWAY_ID ) ) {
    wp_send_json_error( 'Invalid nonce' );
}
```

### 2. Data Sanitization

All user inputs are sanitized:

```php
$api_key = sanitize_text_field( wp_unslash( $_POST['apiKey'] ) );
$order_id = filter_var( wp_unslash( $_POST['order_id'] ), FILTER_SANITIZE_NUMBER_INT );
```

### 3. Capability Checks

Admin pages require proper capabilities:

```php
add_submenu_page(
    'woocommerce',
    __( 'Clip', 'clip-for-woocommerce' ),
    __( 'Clip', 'clip-for-woocommerce' ),
    'manage_woocommerce', // Required capability
    'wc-clipredirect-onboarding',
    array( __CLASS__, 'content' )
);
```

### 4. Basic Authentication

API requests use Basic Auth:

```php
$this->api_token = 'Basic ' . base64_encode( $api_key . ':' . $api_secret );

$headers = array(
    'Authorization' => $this->api_token,
    'Content-Type' => 'application/json',
);
```

## Internationalization (i18n)

### Text Domain

```php
'clip-for-woocommerce'
```

### Translation Files

Located in: `i18n/languages/`

- `clip-es_MX.po/mo` - Spanish (Mexico)
- `clip-es_ES.po/mo` - Spanish (Spain)
- `clip-es_AR.po/mo` - Spanish (Argentina)
- `woo-clip.pot` - Translation template

### Loading Translations

```php
public static function load_textdomain() {
    load_plugin_textdomain( 
        'clip-for-woocommerce', 
        false, 
        basename( __DIR__ ) . '/i18n/languages' 
    );
}
```

## WooCommerce Integration

### Payment Gateway Registration

```php
add_filter( 'woocommerce_payment_gateways', function( $gateways ) {
    $gateways[] = '\Conexa\ClipRedirect\Gateway\WC_ClipRedirect';
    return $gateways;
});
```

### HPOS Compatibility

```php
add_action( 'before_woocommerce_init', function() {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 
            'custom_order_tables', 
            __FILE__, 
            true 
        );
    }
});
```

### Blocks Compatibility

```php
add_action( 'woocommerce_blocks_loaded', function() {
    if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
        add_action(
            'woocommerce_blocks_payment_method_type_registration',
            function( $payment_method_registry ) {
                $payment_method_registry->register( new ClipRedirectBlocks() );
            }
        );
    }
});
```

## Error Handling

### Logging

All errors are logged if debug mode is enabled:

```php
Helper::log_error( __FUNCTION__ . ': ' . $e->getMessage() );
```

**Log file**: `wp-content/uploads/wc-logs/clip-for-woocommerce-{date}.log`

### User-Facing Errors

Errors are displayed via WooCommerce notices:

```php
wc_add_notice( __( 'Payment failed. Please try again.', 'clip-for-woocommerce' ), 'error' );
```

### Admin Notices

Configuration errors shown in admin:

```php
echo '<div class="notice notice-error"><p>' . esc_html( $error_message ) . '</p></div>';
```

## Performance Considerations

### 1. Conditional Asset Loading

Assets are only loaded when needed:

```php
global $current_section;
if ( \ClipRedirect::GATEWAY_ID === $current_section ) {
    $this->enqueue_settings_css();
    $this->enqueue_settings_js();
}
```

### 2. Lazy Initialization

SDK is only initialized when credentials exist:

```php
if ( ! empty( $this->api_key ) && ! empty( $this->api_secret ) ) {
    $this->sdk = new ClipRedirectSdk( $this->api_key, $this->api_secret );
}
```

### 3. Caching

First onboarding validation is cached:

```php
$firstOnboarding = get_option( 'clip_first_onboarding', false );
if ( ! $firstOnboarding ) {
    $ret = $sdk->request_first_deposit();
    update_option( 'clip_first_onboarding', $ret );
}
```

## Testing Considerations

### Testable Components

- **SDK Methods**: Can be tested with mock API responses
- **Helper Traits**: Isolated functionality easy to unit test
- **Validation Logic**: Pure functions testable without WordPress
- **Webhook Processing**: Can be tested with sample payloads

### Test Mode Detection

```php
if ( defined( 'TEST_CLIP_RUNNING' ) && TEST_CLIP_RUNNING ) {
    return $result; // Don't send JSON response in tests
}
```

## Extension Points

### Filters

- `wc_clipredirect_form_fields` - Modify settings fields
- `woocommerce_payment_gateways` - Add/remove payment gateways
- `woocommerce_available_payment_gateways` - Control gateway availability

### Actions

- `activated_plugin` - Plugin activation
- `deactivated_plugin` - Plugin deactivation
- `woocommerce_update_options_payment_gateways_wc_clipredirect` - Settings save
- `woocommerce_thankyou_wc_clipredirect` - Order received page
- `woocommerce_receipt_wc_clipredirect` - Payment receipt page

## Related Documentation

- [Onboarding Flow](./onboarding-flow.md)
- [Checkout and Payment Flow](./checkout-payment-flow.md)
- [Configuration Flow](./configuration-flow.md)
- [Webhook Flow](./webhook-flow.md)
