# 3CX WebSocket Integration Setup Guide

This guide explains how to set up the enhanced 3CX integration with real-time WebSocket monitoring and step-by-step call status updates.

## Features

✅ **Step-by-step call progression:**
- "Calling reception extension..."
- "Reception answered. Dialing customer..."
- "Customer phone is ringing..."
- "Connected to customer" (with timer)
- "Call ended"

✅ **Real-time updates via Laravel Broadcasting**
✅ **WebSocket monitoring with polling fallback**
✅ **Simplified integration (Auth + API + Monitor only)**

## Configuration

### 1. Environment Variables

Add these to your `.env` file:

```env
# 3CX Integration Settings
THREE_CX_API_URL=https://your-3cx-server:5001
THREE_CX_WS_URL=wss://your-3cx-server:5001/callcontrol/ws
THREE_CX_API_TOKEN=your_oauth_bearer_token

# Laravel Broadcasting (choose one)
BROADCAST_DRIVER=pusher
# OR for local development:
# BROADCAST_DRIVER=log

# If using Pusher
PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=mt1

# If using Laravel WebSockets (alternative to Pusher)
# BROADCAST_DRIVER=pusher
# PUSHER_APP_ID=local
# PUSHER_APP_KEY=local
# PUSHER_APP_SECRET=local
# PUSHER_HOST=127.0.0.1
# PUSHER_PORT=6001
# PUSHER_SCHEME=http
```

### 2. Laravel Settings

Configure these in your Laravel admin or directly in the database:

```php
Setting::set('integrations.threecx.base_url', 'https://your-3cx-server:5001');
Setting::set('integrations.threecx.client_id', 'your_client_id');
Setting::set('integrations.threecx.client_secret', 'your_client_secret');
Setting::set('integrations.threecx.call_using_extension', '324'); // Extension for outbound calls
Setting::set('integrations.threecx.timeout', 30);
```

## Usage

### 1. Start the WebSocket Listener (Optional)

For real-time status updates, run the WebSocket listener command:

```bash
# Start the listener (runs indefinitely)
php artisan threecx:listen-websocket

# With timeout (stops after 1 hour)
php artisan threecx:listen-websocket --timeout=3600

# Run in background
nohup php artisan threecx:listen-websocket > storage/logs/threecx-websocket.log 2>&1 &
```

### 2. Frontend Integration (CDN Approach - Laravel Elixir Compatible)

#### Include Pusher via CDN (no npm dependencies):

```html
<!-- Include Pusher JS via CDN -->
<script src="https://js.pusher.com/8.2/pusher.min.js"></script>

<!-- Configure Pusher globally -->
<script>
    window.pusherConfig = {
        key: '{{ env('PUSHER_APP_KEY') }}',
        cluster: '{{ env('PUSHER_APP_CLUSTER', 'mt1') }}',
        forceTLS: true
    };
    
    window.threecxDebug = {{ env('APP_DEBUG', false) ? 'true' : 'false' }};
</script>

<!-- Include the 3CX WebSocket client -->
<script src="{{ asset('js/threecx-websocket-client.js') }}"></script>
```

#### Alternative: Use the provided Blade template:

```blade
@include('threecx::templates.websocket-setup')
```

#### No npm installation required!

This approach:
- ✅ Works with Laravel Elixir
- ✅ No package.json changes needed
- ✅ No build pipeline conflicts
- ✅ Auto-initializes WebSocket connection

### 3. Making Calls

Use the existing call modal system:

```javascript
// Make a call (will show step-by-step progression)
window.ThreeCXCallModal.makeCall('07776668338');

// The modal will now show:
// 1. "Calling reception extension..."
// 2. "Reception answered. Dialing customer..."
// 3. "Customer phone is ringing..."
// 4. "Connected to customer" + timer
// 5. "Call ended"
```

## Call Flow Details

### Backend Status Detection

The system detects call progression by analyzing 3CX API responses:

- `dialing_reception`: Initial call to reception extension
- `dialing_customer`: Reception answered, now dialing customer
- `ringing_customer`: Customer phone is ringing
- `connected`: Both parties connected
- `ended`: Call finished

### Frontend Status Mapping

The frontend receives these detailed statuses and maps them to UI states:

```javascript
switch (status) {
    case 'dialing_reception':
    case 'ringing_reception':
        showCallState('dialing');
        subtitle = 'Calling reception extension...';
        break;
    
    case 'dialing_customer':
        showCallState('ringing');
        subtitle = 'Reception answered. Dialing customer...';
        break;
    
    case 'ringing_customer':
        showCallState('ringing');
        subtitle = 'Customer phone is ringing...';
        break;
    
    case 'connected':
        showCallState('connected');
        subtitle = 'Connected to customer';
        startTimer(); // Starts call duration timer
        break;
    
    case 'ended':
        showCallState('ended');
        subtitle = 'Call ended';
        break;
}
```

## Troubleshooting

### Laravel Elixir Compatibility

1. **Build Pipeline Issues:**
   - ✅ **Solution**: Use CDN approach - no npm changes needed
   - ❌ **Avoid**: Installing Laravel Echo or Pusher via npm
   - ✅ **Safe**: Include scripts via `<script src="https://...">` tags

2. **Dependency Conflicts:**
   ```bash
   # If you see Elixir errors, DON'T run:
   # npm install laravel-echo pusher-js
   
   # Instead, use CDN approach in your Blade templates
   ```

3. **Existing Build Process:**
   ```bash
   # Your existing Elixir commands should still work:
   gulp watch
   gulp --production
   
   # The CDN scripts load separately from your compiled assets
   ```

### WebSocket Issues

1. **Check Laravel Broadcasting Config:**
   ```bash
   php artisan config:cache
   php artisan queue:restart
   ```

2. **Test Broadcasting:**
   ```php
   // Test in Tinker
   broadcast(new \App\Events\ThreeCXCallStatusUpdated([
       'participant_id' => 12345,
       'status' => 'connected',
       'message' => 'Test message'
   ]));
   ```

3. **Debug Pusher Connection:**
   ```javascript
   // In browser console
   console.log(window.ThreeCXWebSocket.getStatus());
   // Should show: { connected: true, pusher_available: true, ... }
   ```

4. **Monitor Logs:**
   ```bash
   tail -f storage/logs/laravel.log | grep "3CX"
   ```

### Call Status Issues

1. **Check 3CX API Connection:**
   ```bash
   curl -H "Authorization: Bearer YOUR_TOKEN" \
        https://your-3cx-server:5001/callcontrol/324/participants/PARTICIPANT_ID
   ```

2. **Verify Extension Configuration:**
   - Make sure extension 324 (or your configured extension) exists in 3CX
   - Extension should be configured to automatically dial external numbers

3. **Debug Status Detection:**
   Enable debug logging in the JavaScript:
   ```javascript
   window.threecxDebug = true;
   ```

## Architecture

```
[3CX PBX] → [Laravel WebSocket Listener] → [Laravel Broadcasting] → [Frontend]
     ↓
[3CX REST API] ← [Laravel Polling] ← [Frontend Modal]
```

- **WebSocket Listener**: Monitors call status changes and broadcasts to frontend
- **Polling Fallback**: Frontend polls status if WebSocket unavailable
- **Broadcasting**: Laravel Echo delivers real-time updates to UI
- **Status Detection**: Backend analyzes 3CX API responses for call progression

## Files Modified

### Backend:
- `app/Console/Commands/ThreeCXWebSocketListener.php` - WebSocket monitoring
- `app/Events/ThreeCXCallStatusUpdated.php` - Broadcasting event
- `app/Modules/ThreeCX/Services/ThreeCXCallTrackingService.php` - Enhanced status detection

### Frontend:
- `public/js/threecx-websocket-client.js` - WebSocket client
- `app/Modules/ThreeCX/assets/js/threecx-call-modal.js` - Enhanced modal

### Configuration:
- `app/Console/Kernel.php` - Registered WebSocket command
