# MSG91 for WooCommerce - Plugin Architecture Overview

## Core Classes & Flow

### 1. Plugin Initialization
```
MSG91_WooCommerce_Plugin_Loader
├── load_core() - Loads core classes
├── load_services() - Loads service classes
└── init() - Initializes admin menu
```

### 2. Key Classes

**Core Classes:**
- `MSG91_WooCommerce_Automation` - CRUD operations for automation rules
- `MSG91_WooCommerce_Settings` - Plugin settings management
- `MSG91_WooCommerce_Database_Handler` - Database table management
- `MSG91_WooCommerce_Admin_Menu` - WordPress admin interface

**Service Classes:**
- `MSG91_WooCommerce_WebhookService` - **Main event handler & campaign trigger**
- `MSG91_WooCommerce_CampaignService` - MSG91 API communication
- `MSG91_WooCommerce_UserService` - User info & logging
- `MSG91_WooCommerce_OTPService` - OTP functionality

**Model Classes:**
- `MSG91_WooCommerce_Model` - Event definitions & variable mappings

### 3. Event Flow (Runtime)

```
WooCommerce Event → WebhookService → Campaign API Call
```

**Step-by-step:**

1. **WooCommerce Event Occurs** (order placed, customer registered, etc.)
2. **WebhookService Hooks** - Listens to WooCommerce events via WordPress hooks
3. **Event Processing** - `executeTriggers()` finds matching automation rules
4. **Payload Generation** - `generatePayload()` maps WooCommerce data to campaign variables
5. **Campaign Execution** - `runCampaign()` calls MSG91 API
6. **Logging** - `logTrigger()` stores request/response for debugging

### 4. Event Definitions

**Location:** `includes/models/class-woocommerce-model.php`

**Supported Events:**
```php
'woocommerce_created_customer'     // New Customer
'woocommerce_update_customer'      // Update Customer  
'woocommerce_new_order'           // New Order
'woocommerce_payment_complete'    // Payment Complete
'woocommerce_order_status_*'      // Order status changes
'woocommerce_add_to_cart'         // Cart events
```

**Hook Registration:** `WebhookService.__construct()`
```php
add_action('woocommerce_created_customer', [$this, 'handleCustomerEvent']);
add_action('woocommerce_new_order', [$this, 'handleOrderEvent']);
// ... etc
```

### 5. Campaign API Flow

**Runtime Execution:**
```php
// WebhookService.runTrigger()
$campaignService = new MSG91_WooCommerce_CampaignService();
$payload = $this->generatePayload($trigger, $data);
$response = $campaignService->runCampaign($trigger['campaign_slug'], $payload);
```

**API Call:**
```php
// CampaignService.runCampaign()
$url = "https://test.msg91.com/api/v5/campaign/api/campaigns/{$campaignSlug}/run";
$response = msg91_woocommerce_api_call($url, $payload, 'POST');
```

**Yes, Campaign API is triggered at runtime** - immediately when WooCommerce events occur.

### 6. Data Flow

```
WooCommerce Data → Variable Mapping → Campaign Payload → MSG91 API
```

**Variable Mapping Example:**
```php
// From WebhookService.mapVariable()
$mapping = [
    'customer_name' => $data['billing']['first_name'] . ' ' . $data['billing']['last_name'],
    'order_total' => $data['total'],
    'customer_phone' => $data['billing_mobile']
];
```

**Campaign Payload Structure:**
```json
{
    "data": {
        "sendTo": [{
            "to": [{"email": "customer@email.com", "mobiles": "+919876543210"}],
            "variables": {
                "customer_name": "John Doe",
                "order_total": "1500",
                "order_id": "12345"
            }
        }]
    }
}
```

### 7. Database Schema

**Automation Rules Table:** `wp_msg91_automations`
```sql
- id (Primary Key)
- name (Automation name)
- campaign_id, campaign_slug, campaign_name (MSG91 campaign info)
- woocommerce_event (Event trigger)
- status (active/inactive)
- configurations (JSON - field mappings & variables)
- created_at, updated_at
```

**Error Logs Table:** `wp_msg91_error_logs`
```sql
- id, trigger_id, trigger_name
- request_body, response_body (API call logs)
- created_at
```

### 8. Admin Interface Flow

1. **Create Automation** → Select WooCommerce event → Choose MSG91 campaign
2. **Field Mapping** → Map WooCommerce data to campaign variables via AJAX
3. **Save Configuration** → Store in `wp_msg91_automations` table
4. **Runtime** → WebhookService automatically executes when events occur

### 9. Key Files

```
msg91-for-woocommerce.php              # Main plugin file
includes/core/class-plugin-loader.php   # Plugin initialization
includes/services/WebhookService.php    # Event handling & campaign triggers
includes/services/CampaignService.php   # MSG91 API communication
includes/core/class-automation.php      # Automation CRUD operations
includes/models/class-woocommerce-model.php # Event & variable definitions
config/external-urls.php               # API endpoints
```

### 10. Caching Strategy

- **Automation Rules:** Cached for 10 minutes (`msg91_automations_all`)
- **Campaign Triggers:** Cached per event type (`msg91_automation_triggers_*`)
- **API Responses:** No caching (real-time execution)

---

**Key Takeaway:** The plugin is event-driven. WooCommerce events trigger automation rules in real-time, which immediately call MSG91 campaign APIs with mapped data. All configuration is done via admin interface, but execution is fully automated.
