# 📞 3CX Phone System Integration

> **Modern phone system integration for Seraph3 Laravel Business Management System**

This module provides comprehensive integration with 3CX Phone System, replacing the legacy Asterisk integration with modern, API-based call management that's easier to maintain and more reliable.

## 🚀 Quick Start

**New to 3CX integration?** → See the **[Complete Setup Guide](SETUP_GUIDE.md)**

**Upgrading from Asterisk?** → See **[Migration Guide](#-migration-from-asterisk)**

**Just want to make calls?** → [Jump to Usage](#-usage)

## ✨ Key Features

### 📞 Call Management
- **Click-to-Call**: Direct calling from task detail views
- **Real-time Status**: Live call progress updates
- **Call Logging**: Automatic call records linked to tasks
- **Duration Tracking**: Precise call timing and billing

### 🔄 Automation
- **CDR Synchronization**: Real-time sync with 3CX Call Detail Records
- **Background Jobs**: Automated processing and data sync
- **Queue Integration**: Reliable background processing
- **Error Recovery**: Automatic retry mechanisms

### 🎛️ Administration
- **Admin Interface**: Complete configuration and testing interface
- **Connection Testing**: One-click verification
- **User Management**: Extension mapping and permissions
- **Monitoring**: Comprehensive logging and health checks

### 🔧 Technical
- **RESTful API**: Standard HTTP endpoints for integration
- **Service Architecture**: Clean, testable design patterns
- **Database Integration**: Proper Eloquent relationships
- **Error Handling**: Comprehensive exception management

## 🏗️ Architecture

This module follows the Laravel Module Pattern Template with:

- **Service Interface**: `ThreeCXServiceInterface` for dependency injection
- **Service Implementation**: `ThreeCXService` with core business logic
- **Authentication Service**: `ThreeCXAuthService` for API authentication
- **Controller**: `ThreeCXController` for HTTP endpoints
- **Model**: `TaskCallLog` for call record storage
- **Jobs**: Background CDR synchronization
- **Commands**: Artisan commands for maintenance

## 🚀 Installation Options

### Option 1: Quick Setup (5 minutes)
```bash
# 1. Run database migration
docker-compose exec app php artisan migrate

# 2. Add to .env file
echo "THREECX_BASE_URL=https://your-3cx-server:5001" >> .env
echo "THREECX_API_KEY=your_api_key_here" >> .env
echo "THREECX_DEFAULT_EXTENSION=1001" >> .env

# 3. Test connection
docker-compose exec app php artisan threecx:test-connection
```

### Option 2: Complete Setup (30 minutes)
👉 **Follow the comprehensive [Setup Guide](SETUP_GUIDE.md)** for:
- 3CX system configuration
- User extension mapping
- Queue worker setup
- Production deployment
- Troubleshooting guide

### Option 3: Development Setup (10 minutes)
```bash
# Quick development setup with Docker
git clone your-repo
cd seraph3
docker-compose up -d
docker-compose exec app php artisan migrate
# Configure .env with your 3CX details
# Start making calls!
```

## ⚙️ Configuration

### Essential Environment Variables
```env
# Required Settings
THREECX_BASE_URL=https://pbx.yourdomain.com:5001
THREECX_API_KEY=your_generated_api_key
THREECX_DEFAULT_EXTENSION=1001

# Optional Settings
THREECX_TIMEOUT=30
THREECX_RECORDING_PATH=/var/lib/3cx/Recordings/
THREECX_CDR_SYNC_INTERVAL=300
THREECX_LOG_LEVEL=info
```

### Admin Panel Setup
1. **Admin → Settings → Integrations**
2. **Enable 3CX Integration**
3. **Configure connection details**
4. **Click "Test Connection"** ✅
5. **Start making calls!** 📞

## 🔧 3CX Setup Requirements

### API Configuration

1. **Enable 3CX API**:
   - Login to 3CX Management Console
   - Go to **Advanced → API**
   - Enable **Call Control API**
   - Generate API Key

2. **API Permissions Required**:
   - Call Control
   - CDR Access
   - Extension Management

3. **Network Access**:
   - Ensure Laravel server can reach 3CX management interface
   - Configure firewall rules if necessary

## 📞 Usage

### Making Calls (User Guide)

**Step 1: Navigate to a Task**
- Go to any task with a customer phone number
- Look for the **📞 Call Customer** button next to phone numbers

**Step 2: Initiate Call** 
- Click **📞 Call Customer**
- Your 3CX phone/softphone will ring
- Answer your phone first, then customer call is connected

**Step 3: Call Management**
- Call status updates in real-time
- Call log is created automatically
- Duration and outcome are tracked

### Viewing Call History

**Task-Specific Calls:**
- Each task shows its call history
- Duration, timestamp, and status displayed
- Click to expand for call details

**Personal Call History:**
- **Profile → Call History**
- Filter by date, customer, duration
- Export for reporting

**Admin Reports:**
- **Admin → Reports → Call Activity**
- Department-wide call statistics
- Performance metrics and trends

### API Endpoints

```bash
# Start a call
POST /api/threecx/call/start
{
    "task_id": 123,
    "phone_number": "+1234567890",
    "extension": "1001"
}

# Stop a call
POST /api/threecx/call/stop
{
    "call_id": "3cx_call_id"
}

# Get task call logs
GET /api/threecx/logs/task?task_id=123

# Get user call logs
GET /api/threecx/logs/user
```

## 🔄 Background Processing

### CDR Synchronization

The system automatically syncs Call Detail Records (CDR) from 3CX:

```bash
# Manual sync
docker-compose exec app php artisan threecx:sync-cdr

# Schedule in crontab (every 5 minutes)
*/5 * * * * docker-compose exec app php artisan threecx:sync-cdr
```

### Background Job

For automatic processing, dispatch the sync job:

```php
// In your code
use App\Modules\ThreeCX\Jobs\SyncThreeCXCDR;

// Dispatch immediately
SyncThreeCXCDR::dispatch();

// Dispatch with delay
SyncThreeCXCDR::dispatch()->delay(now()->addMinutes(5));
```

## 🧪 Testing

### Connection Test

```bash
# Test via Artisan
docker-compose exec app php artisan threecx:test-connection

# Test via Admin Interface
# Go to Admin → Settings → Integrations → Test 3CX Connection
```

### Manual Call Test

```bash
# Using the service directly
docker-compose exec app php artisan tinker

$service = app('App\\Modules\\ThreeCX\\Services\\ThreeCXServiceInterface');
$result = $service->makeCall('1001', '+1234567890', 123);
dd($result);
```

## 📊 Database Schema

### task_call_logs Table

```sql
CREATE TABLE task_call_logs (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    task_id BIGINT NULL,
    user_id BIGINT NOT NULL,
    call_id VARCHAR(255) NULL,
    from_extension VARCHAR(20) NOT NULL,
    to_number VARCHAR(50) NOT NULL,
    called_at TIMESTAMP NOT NULL,
    answered_at TIMESTAMP NULL,
    ended_at TIMESTAMP NULL,
    duration INT NULL,
    status ENUM('initiated', 'ringing', 'answered', 'completed', 'failed', 'cancelled'),
    direction ENUM('outbound', 'inbound'),
    recording_filename VARCHAR(255) NULL,
    notes TEXT NULL,
    raw_cdr_data JSON NULL,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    
    INDEX(task_id),
    INDEX(user_id),
    INDEX(call_id),
    INDEX(called_at),
    FOREIGN KEY(task_id) REFERENCES tasks(id) ON DELETE SET NULL,
    FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
```

## 🔧 Configuration Reference

### config/threecx.php

```php
return [
    'base_url' => env('THREECX_BASE_URL'),
    'api_key' => env('THREECX_API_KEY'),
    'default_extension' => env('THREECX_DEFAULT_EXTENSION'),
    'timeout' => env('THREECX_TIMEOUT', 30),
    'endpoints' => [
        'make_call' => '/callcontrol/makecall',
        'hang_up' => '/callcontrol/hangup',
        'call_status' => '/callcontrol/status',
        'cdr' => '/cdr/get',
    ],
    'cdr' => [
        'sync_interval' => env('THREECX_CDR_SYNC_INTERVAL', 300),
        'recording_path' => env('THREECX_RECORDING_PATH'),
    ],
];
```

## 📝 Logging

All 3CX operations are logged with the `[3CX]` prefix:

```bash
# View logs
tail -f storage/logs/laravel.log | grep "\[3CX\]"

# Log levels:
[3CX] Call initiated successfully    # INFO
[3CX] CDR synchronization completed   # INFO
[3CX] API connection failed          # ERROR
[3CX] Invalid call parameters        # WARNING
```

## 🔄 Migration from Asterisk

### Data Migration

1. **Export Existing Calls**:
   ```sql
   SELECT * FROM calls WHERE created_at > '2024-01-01';
   ```

2. **Map to New Schema**:
   - `calls.uniqueid` → `task_call_logs.call_id`
   - `calls.extension` → `task_call_logs.from_extension`
   - `calls.number` → `task_call_logs.to_number`
   - `calls.task_id` → `task_call_logs.task_id`
   - `calls.user_id` → `task_call_logs.user_id`

3. **Update Frontend**:
   - Replace Asterisk API calls with 3CX endpoints
   - Update call status handling
   - Modify real-time updates (remove Socket.IO dependency)

### Parallel Operation

During migration, both systems can run simultaneously:

1. Keep Asterisk enabled in admin settings
2. Enable 3CX integration
3. Test 3CX functionality
4. Gradually migrate users to 3CX
5. Disable Asterisk when migration is complete

## 🐛 Troubleshooting

### Common Issues

1. **Connection Failed**:
   - Verify 3CX URL is accessible
   - Check API key validity
   - Ensure firewall allows connection

2. **Calls Not Logging**:
   - Check CDR sync job is running
   - Verify API permissions
   - Review Laravel logs for errors

3. **Extension Not Found**:
   - Ensure user has extension configured
   - Check default extension setting
   - Verify extension exists in 3CX

### Debug Mode

```bash
# Enable debug logging
THREECX_LOG_LEVEL=debug

# Test with verbose output
docker-compose exec app php artisan threecx:test-connection -v
```

## 🤝 Support

For issues or questions:
1. Check Laravel logs: `storage/logs/laravel.log`
2. Test API connection: `Admin → Settings → Integrations`
3. Review 3CX Management Console for API logs
4. Consult 3CX API documentation

## 📚 References

- [3CX API Documentation](https://www.3cx.com/docs/api/)
- [Laravel Module Pattern Template](../../../docs/MODULE_PATTERN_TEMPLATE.md)
- [Phone System Integration Setup Guide](../../../docs/PHONE_SMS_INTEGRATION_SETUP.md)
