# Configuration Flow

The configuration flow allows merchants to customize the Clip payment gateway settings, including credentials, payment methods, card brands, installments, and checkout behavior.

## Overview

Merchants can configure the Clip gateway through the WooCommerce settings interface. The configuration includes credential validation, payment method customization, and advanced options for checkout behavior.

## Configuration Interface Diagram

```mermaid
graph TB
    Start([Merchant Access Settings]) --> SettingsPage[WooCommerce Settings Page<br/>Payments > Clip]
    
    SettingsPage --> CredentialsSection[Credentials Section]
    SettingsPage --> CheckoutSection[Checkout Section]
    SettingsPage --> AdvancedSection[Advanced Settings Section]
    SettingsPage --> LinkSection[Link Settings Section]
    
    subgraph Credentials["Credentials Configuration"]
        CredentialsSection --> APIKey[API Key Field]
        CredentialsSection --> APISecret[API Secret Field]
        APIKey --> Validate[Auto-Validation]
        APISecret --> Validate
        Validate --> ValidIcon[✓ Valid credentials]
        Validate --> InvalidIcon[✗ Invalid credentials]
    end
    
    subgraph Checkout["Checkout Configuration"]
        CheckoutSection --> BannerToggle[Enable/Disable Banner]
        CheckoutSection --> ExpirationTime[Expiration Time<br/>0-72 hours]
        BannerToggle --> BannerDisplay[Dynamic Banner Display<br/>Based on enabled methods]
    end
    
    subgraph Advanced["Advanced Settings"]
        AdvancedSection --> DebugLogs[Enable Debug Logs]
        DebugLogs --> LogFile[WooCommerce Logs<br/>wp-content/uploads/wc-logs/]
    end
    
    subgraph LinkCustomization["Link Settings (Payment Customization)"]
        LinkSection --> CustomizeToggle{Customize Link?}
        CustomizeToggle -->|Yes| PaymentTypes[Payment Types]
        CustomizeToggle -->|Yes| CardBrands[Card Brands]
        CustomizeToggle -->|Yes| InstallmentsToggle{Enable Installments?}
        
        PaymentTypes --> Cards[Cards Credit/Debit]
        PaymentTypes --> Cash[Cash OXXO]
        
        CardBrands --> Visa[Visa]
        CardBrands --> Mastercard[Mastercard]
        CardBrands --> Amex[American Express]
        CardBrands --> Carnet[Carnet]
        CardBrands --> Discover[Discover]
        CardBrands --> Diners[Diners Club]
        
        InstallmentsToggle -->|Yes| MSI[Months Without Interest]
        MSI --> MSI3[3 months - Min amount]
        MSI --> MSI6[6 months - Min amount]
        MSI --> MSI9[9 months - Min amount]
        MSI --> MSI12[12 months - Min amount]
        MSI --> MSI18[18 months - Min amount]
        MSI --> MSI21[21 months - Min amount]
        MSI --> MSI24[24 months - Min amount]
    end
    
    ValidIcon --> SaveSettings[Save Settings]
    InvalidIcon --> SaveSettings
    BannerDisplay --> SaveSettings
    ExpirationTime --> SaveSettings
    LogFile --> SaveSettings
    Cards --> SaveSettings
    Cash --> SaveSettings
    Visa --> SaveSettings
    Mastercard --> SaveSettings
    Amex --> SaveSettings
    Carnet --> SaveSettings
    Discover --> SaveSettings
    Diners --> SaveSettings
    MSI3 --> SaveSettings
    MSI6 --> SaveSettings
    MSI9 --> SaveSettings
    MSI12 --> SaveSettings
    MSI18 --> SaveSettings
    MSI21 --> SaveSettings
    MSI24 --> SaveSettings
    
    SaveSettings --> UpdateOptions[Update WordPress Options]
    UpdateOptions --> End([Configuration Complete])
    
    style Credentials fill:#e1f5ff
    style Checkout fill:#fff4e1
    style Advanced fill:#ffe1e1
    style LinkCustomization fill:#e1ffe1
```

## Settings Page Access

### Navigation Path

1. WordPress Admin → **WooCommerce** → **Settings**
2. Click **Payments** tab
3. Click **Clip** (or **Manage** button)

### URL
```
/wp-admin/admin.php?page=wc-settings&tab=checkout&section=wc_clipredirect
```

### Required Capability
```php
manage_woocommerce
```

## Settings Registration Flow

```mermaid
sequenceDiagram
    participant Admin as WordPress Admin
    participant WC as WooCommerce
    participant Gateway as WC_ClipRedirect
    participant Settings as Settings Class
    participant Helper as Helper Trait
    participant SDK as ClipRedirectSdk
    participant ClipAPI as Clip API

    Note over Admin,ClipAPI: Page Load
    Admin->>WC: Access Payments Settings
    WC->>Gateway: Load gateway instance
    Gateway->>Gateway: __construct()
    Gateway->>Gateway: init_form_fields()
    Gateway->>Settings: get_settings()
    Settings-->>Gateway: Return form fields array
    Gateway->>Gateway: init_settings()
    Note right of Gateway: Load saved options from DB
    
    Gateway->>Helper: validate_credentials()
    Helper->>SDK: Initialize SDK
    SDK->>ClipAPI: Validate credentials
    ClipAPI-->>SDK: Return validation result
    SDK-->>Helper: Return result
    Helper->>Gateway: Display validation icon
    
    Gateway->>Admin: Render settings form
    
    Note over Admin,ClipAPI: Save Settings
    Admin->>Admin: Modify settings
    Admin->>Gateway: Submit form
    Gateway->>Gateway: validate_*_field() methods
    Gateway->>Gateway: process_admin_options()
    Gateway->>Gateway: Update WordPress options
    Gateway->>Helper: validate_credentials()
    Helper->>SDK: Test credentials
    SDK->>ClipAPI: API request
    ClipAPI-->>SDK: Response
    SDK-->>Helper: Validation result
    Gateway->>Admin: Display success/error notice
```

## Settings Structure

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

### Settings Sections

The settings are organized into logical sections:

1. **Gateway Section** - Enable/disable gateway
2. **Credentials Section** - API Key and Secret
3. **Validations Section** - Credential validation status
4. **Checkout Section** - Banner and expiration settings
5. **Advanced Section** - Debug logs
6. **Link Section** - Payment customization options

### Settings Array Structure

```php
public static function get_settings() {
    return apply_filters(
        'wc_clipredirect_form_fields',
        array(
            'enabled' => array(
                'title' => __( 'Enable/Disable', 'clip-for-woocommerce' ),
                'type' => 'checkbox',
                'label' => __( 'Enable Clip Payment Gateway', 'clip-for-woocommerce' ),
                'default' => 'yes',
            ),
            
            'wc_clipredirect_credentials_section' => array(
                'title' => __( 'Credentials', 'clip-for-woocommerce' ),
                'type' => 'title',
                'description' => __( "If you still do not have your credentials...", 'clip-for-woocommerce' ),
            ),
            
            'wc_clipredirect_api_key' => array(
                'title' => __( 'Client Api Key', 'clip-for-woocommerce' ),
                'type' => 'text',
            ),
            
            'wc_clipredirect_api_secret' => array(
                'title' => __( 'Client Api Secret', 'clip-for-woocommerce' ),
                'type' => 'password',
            ),
            
            'wc_clipredirect_validations_section' => array(
                'title' => '',
                'type' => 'title',
                'description' => Helper::validate_all_html(),
            ),
            
            // ... more settings
        )
    );
}
```

## Field Types and Handlers

### 1. Standard Fields

#### Text Field
```php
'wc_clipredirect_api_key' => array(
    'title' => __( 'Client Api Key', 'clip-for-woocommerce' ),
    'type' => 'text',
)
```

#### Password Field
```php
'wc_clipredirect_api_secret' => array(
    'title' => __( 'Client Api Secret', 'clip-for-woocommerce' ),
    'type' => 'password',
)
```

#### Checkbox Field
```php
'enabled' => array(
    'title' => __( 'Enable/Disable', 'clip-for-woocommerce' ),
    'type' => 'checkbox',
    'label' => __( 'Enable Clip Payment Gateway', 'clip-for-woocommerce' ),
    'default' => 'yes',
)
```

#### Number Field
```php
'wc_clipredirect_expiration_hours' => array(
    'title' => __( 'Checkout expiration time (hours)', 'clip-for-woocommerce' ),
    'type' => 'number',
    'description' => __( 'Maximum checkout time (0-72 hours)', 'clip-for-woocommerce' ),
    'sanitize_callback' => function ( $input ) {
        $input = intval( $input );
        $input = max( 0, min( 72, $input ) );
        return $input;
    },
)
```

### 2. Custom Field Types

#### Payment Types Field
**File**: `src/gateway/class-wc-clip-redirect.php`

```php
'wc_clipredirect_payment_type' => array(
    'title' => __( 'Payment Types', 'clip-for-woocommerce' ),
    'type' => 'payment_types',
    'label' => ' ',
)
```

**Custom Generator**:
```php
public function generate_payment_types_html( $key, $settings ) {
    $html = '';
    $data = array(
        'key' => $key,
        'settings' => $settings,
        'payment_type' => $this->payment_type,
        'types' => array(
            array(
                'value' => 'cards',
                'label' => __( 'Cards (Credit/Debit)', 'clip-for-woocommerce' ),
                'sub_options' => array(
                    'credit' => __( 'Credit', 'clip-for-woocommerce' ),
                    'debit' => __( 'Debit', 'clip-for-woocommerce' ),
                ),
            ),
            array(
                'value' => 'cash',
                'label' => __( 'Cash (OXXO)', 'clip-for-woocommerce' ),
            ),
        ),
    );
    
    ob_start();
    $html .= Helper::get_template_part( 'setting', 'payment-type', $data );
    $html .= ob_get_clean();
    return $html;
}
```

**Custom Validator**:
```php
public function validate_payment_types_field( $key, $value ) {
    if ( is_null( $value ) || ! is_array( $value ) ) {
        $value = $this->payment_types_default;
    } else {
        // Ensure cards is enabled if credit or debit is enabled
        if ( ( isset( $value['credit'] ) && 'yes' === $value['credit'] ) ||
             ( isset( $value['debit'] ) && 'yes' === $value['debit'] ) ) {
            $value['cards'] = 'yes';
        }
    }
    return $value;
}
```

#### Payment Card Brands Field

**Custom Generator**:
```php
public function generate_payment_card_brands_html( $key, $settings ) {
    $data = array(
        'key' => $key,
        'settings' => $settings,
        'payment_card_brands' => $this->payment_card_brands,
        'brands' => array(
            array(
                'value' => 'visa',
                'label' => 'Visa',
                'icon' => Helper::get_assets_folder_url() . '/img/brands/visa.png',
            ),
            array(
                'value' => 'mastercard',
                'label' => 'MasterCard',
                'icon' => Helper::get_assets_folder_url() . '/img/brands/mastercard.png',
            ),
            // ... more brands
        ),
    );
    
    ob_start();
    Helper::get_template_part( 'setting', 'payment-card-brands', $data );
    return ob_get_clean();
}
```

#### Payment Installments Field

**Custom Generator**:
```php
public function generate_payment_installments_html( $key, $settings ) {
    $data = array(
        'key' => $key,
        'settings' => $settings,
        'payment_installments' => $this->payment_installments,
        'labels' => array(
            '3' => __( '3 months without interest', 'clip-for-woocommerce' ),
            '6' => __( '6 months without interest', 'clip-for-woocommerce' ),
            '9' => __( '9 months without interest', 'clip-for-woocommerce' ),
            '12' => __( '12 months without interest', 'clip-for-woocommerce' ),
            '18' => __( '18 months without interest', 'clip-for-woocommerce' ),
            '21' => __( '21 months without interest', 'clip-for-woocommerce' ),
            '24' => __( '24 months without interest', 'clip-for-woocommerce' ),
        ),
    );
    
    ob_start();
    Helper::get_template_part( 'setting', 'payment-installments', $data );
    return ob_get_clean();
}
```

**Custom Validator**:
```php
public function validate_payment_installments_field( $key, $value ) {
    if ( is_null( $value ) || ! is_array( $value ) ) {
        $value = $this->payment_installments_default;
    } else {
        foreach ( $value as $key => $item ) {
            $value[ $key ]['enabled'] = isset( $item['enabled'] ) ? $item['enabled'] : 'no';
        }
    }
    return $value;
}
```

## Credential Validation

**File**: `src/helper/class-validations-trait.php`

### Validation Display

```php
public static function validate_all_html() {
    global $current_section;
    if ( 'wc_clipredirect' === $current_section ) {
        return '<p>' . self::validate_credentials_html() . '</p>';
    }
    return '';
}

public static function validate_credentials_html() {
    return self::validate_html(
        self::validate_credentials(),
        __( 'Valid credentials.', 'clip-for-woocommerce' ),
        __( 'Invalid credentials.', 'clip-for-woocommerce' )
    );
}

public static function validate_html( $bool, $message_ok, $message_error ) {
    return $bool
        ? self::VALIDATION_OK_ICON . $message_ok
        : self::VALIDATION_ERROR_ICON . $message_error;
}
```

### Validation Icons

```php
const VALIDATION_OK_ICON = '<span class="dashicons dashicons-saved" style="color:green;"></span>';
const VALIDATION_ERROR_ICON = '<span class="dashicons dashicons-no-alt" style="color:red;"></span>';
```

### Validation Logic

```php
public static function validate_credentials() {
    $sdk = new ClipRedirectSdk(
        self::get_option( 'api_key' ),
        self::get_option( 'api_secret' )
    );
    
    $firstOnboarding = get_option( 'clip_first_onboarding', false );
    
    if ( ! $firstOnboarding ) {
        // First time: create dummy payment
        $ret = $sdk->request_first_deposit();
        update_option( 'clip_first_onboarding', $ret );
        return $ret;
    } else {
        // Subsequent: validate with receipt check
        return $sdk->validate_receipt();
    }
}
```

## Default Values

### Payment Types Default

```php
$this->payment_types_default = array(
    'cards' => 'yes',
    'credit' => 'yes',
    'debit' => 'yes',
    'cash' => 'yes',
);
```

### Card Brands Default

```php
$this->payment_card_brands_default = array(
    'visa' => 'yes',
    'mastercard' => 'yes',
    'amex' => 'yes',
    'carnet' => 'yes',
    'discover' => 'yes',
    'diners' => 'yes',
);
```

### Installments Default

```php
$this->payment_installments_default = array(
    array( 'installment' => 3, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 6, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 9, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 12, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 18, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 21, 'enabled' => 'no', 'value' => '' ),
    array( 'installment' => 24, 'enabled' => 'no', 'value' => '' ),
);
```

## Settings Storage

### WordPress Options Table

All settings are stored in a single serialized array:

**Option Name**: `woocommerce_wc_clipredirect_settings`

**Example Structure**:
```php
array(
    'enabled' => 'yes',
    'wc_clipredirect_api_key' => 'clip_key_abc123',
    'wc_clipredirect_api_secret' => 'clip_secret_xyz789',
    'wc_clipredirect_banner_enabled' => 'yes',
    'wc_clipredirect_expiration_hours' => '72',
    'wc_clipredirect_log_enabled' => 'yes',
    'wc_clipredirect_payment_override' => 'yes',
    'wc_clipredirect_payment_type' => array(
        'cards' => 'yes',
        'credit' => 'yes',
        'debit' => 'yes',
        'cash' => 'yes',
    ),
    'wc_clipredirect_payment_card_brands' => array(
        'visa' => 'yes',
        'mastercard' => 'yes',
        'amex' => 'no',
        'carnet' => 'no',
        'discover' => 'no',
        'diners' => 'no',
    ),
    'wc_clipredirect_payment_installments_enabled' => 'yes',
    'wc_clipredirect_payment_installments' => array(
        array( 'installment' => 3, 'enabled' => 'yes', 'value' => '500' ),
        array( 'installment' => 6, 'enabled' => 'yes', 'value' => '1000' ),
        // ... more installments
    ),
    'wc_clipredirect_payment_tips' => 'no',
)
```

### Helper Methods

**File**: `src/helper/class-settings-trait.php`

```php
trait SettingsTrait {
    public static function get_options( $gateway_id ) {
        $options_key = 'woocommerce_' . $gateway_id . '_settings';
        $options = get_option( $options_key, array() );
        
        return array(
            'api_key' => $options['wc_clipredirect_api_key'] ?? '',
            'api_secret' => $options['wc_clipredirect_api_secret'] ?? '',
            // ... more options
        );
    }
    
    public static function get_option( $key, $default = false ) {
        $options = get_option( 'woocommerce_wc_clipredirect_settings', array() );
        return isset( $options[ $key ] ) ? $options[ $key ] : $default;
    }
    
    public static function set_option( $key, $value ) {
        $options = get_option( 'woocommerce_wc_clipredirect_settings', array() );
        $options[ $key ] = $value;
        update_option( 'woocommerce_wc_clipredirect_settings', $options );
    }
}
```

## Admin Assets

### CSS Enqueue

**File**: `src/gateway/class-wc-clip-redirect.php`

```php
private function enqueue_settings_css() {
    wp_enqueue_style( 'clipredirect-settings' );
}
```

**Registered in**: `clip-for-woocommerce.php`
```php
public static function register_admin_css_styles() {
    wp_register_style(
        'clipredirect-settings',
        Helper::get_assets_folder_url() . '/css/settings.css',
        array(),
        self::VERSION,
        'all'
    );
}
```

### JavaScript Enqueue

```php
private function enqueue_settings_js() {
    wp_register_script(
        'my-clip-admin-js',
        Helper::get_assets_folder_url() . '/js/admin-settings.js',
        array( 'jquery' ),
        \ClipRedirect::VERSION,
        true
    );
    wp_enqueue_script( 'my-clip-admin-js' );
    
    wp_localize_script(
        'my-clip-admin-js',
        'ClipSettings',
        array(
            'logotypeUrl' => esc_url( Helper::get_assets_folder_url() . '/img/logotype_clip_primary.svg' ),
        )
    );
}
```

## Settings Templates

### Template Location
```
templates/
├── setting-payment-type.php
├── setting-payment-card-brands.php
└── setting-payment-installments.php
```

### Template Usage

**File**: `src/helper/class-templates-trait.php`

```php
public static function get_template_part( $slug, $name = null, $args = array() ) {
    $template = '';
    
    if ( $name ) {
        $template = locate_template( "{$slug}-{$name}.php" );
    }
    
    if ( ! $template && $name && file_exists( \ClipRedirect::MAIN_DIR . "/templates/{$slug}-{$name}.php" ) ) {
        $template = \ClipRedirect::MAIN_DIR . "/templates/{$slug}-{$name}.php";
    }
    
    if ( $template ) {
        load_template( $template, false, $args );
    }
}
```

## Filters and Hooks

### Settings Filter

Allows modification of settings fields:

```php
$settings = apply_filters( 'wc_clipredirect_form_fields', $default_settings );
```

**Example usage**:
```php
add_filter( 'wc_clipredirect_form_fields', function( $fields ) {
    // Add custom field
    $fields['my_custom_field'] = array(
        'title' => 'My Custom Setting',
        'type' => 'text',
        'default' => '',
    );
    
    return $fields;
});
```

### Save Options Hook

```php
add_action(
    'woocommerce_update_options_payment_gateways_' . $this->id,
    array( $this, 'process_admin_options' )
);
```

## Configuration Best Practices

### 1. Credential Security

- API Secret is stored as password type (masked in UI)
- Credentials are validated before saving
- Invalid credentials trigger error notices

### 2. Payment Method Logic

- If Credit OR Debit is enabled, Cards must be enabled
- Validation enforces this relationship
- Prevents configuration errors

### 3. Installments Configuration

- Each installment has minimum order amount
- Installments are only offered if order total >= minimum
- Supports 3, 6, 9, 12, 18, 21, 24 months

### 4. Expiration Time

- Range: 0-72 hours
- Sanitized to enforce limits
- Default: 72 hours if not configured

## Related Files

- `src/gateway/class-wc-clip-redirect.php` - Main gateway class with form field generators
- `src/gateway/class-settings.php` - Settings structure definition
- `src/helper/class-settings-trait.php` - Helper methods for getting/setting options
- `src/helper/class-validations-trait.php` - Credential validation logic
- `templates/setting-payment-type.php` - Payment types template
- `templates/setting-payment-card-brands.php` - Card brands template
- `templates/setting-payment-installments.php` - Installments template
- `assets/css/settings.css` - Admin settings styles
- `assets/js/admin-settings.js` - Admin settings JavaScript
