# 🚀 DizzCall AI - Dialer Integration Guide

## 📋 Overview
This guide provides the API endpoints and integration details for connecting your dialer system with the DizzCall AI phone system.

## 🎯 What This API Does
- **Handles incoming calls** from your dialer
- **Processes speech input** from callers
- **Generates AI responses** using Gemini AI
- **Returns TwiML** for Twilio integration
- **Logs all interactions** for monitoring

---

## 🔗 API Endpoints

### Base URL
```
https://princedevops.live/dizzcall-ai-dialer-api/
```

### 1. Incoming Call Webhook
**POST** `/webhook/incoming`

**Purpose:** Handle incoming calls from your dialer system

**Request Body:**
```json
{
  "From": "+1234567890",
  "To": "+16084969211",
  "CallSid": "CA1234567890abcdef",
  "CallStatus": "in-progress",
  "Direction": "inbound"
}
```

**Response:** TwiML XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">Hi there! This is Alex from Dizaart Systems. I'm excited to help you today. What can I assist you with?</Say>
    <Gather input="speech" action="https://princedevops.live/dizzcall-ai-dialer-api/webhook/speech" method="POST" timeout="5" speechTimeout="3">
        <Say voice="Polly.Joanna">How can I help you today?</Say>
    </Gather>
    <Say voice="Polly.Joanna">Thank you for calling Dizaart Systems. Have a great day!</Say>
    <Hangup/>
</Response>
```

### 2. Speech Processing Webhook
**POST** `/webhook/speech`

**Purpose:** Process what the caller says and generate AI response

**Request Body:**
```json
{
  "From": "+1234567890",
  "To": "+16084969211",
  "CallSid": "CA1234567890abcdef",
  "SpeechResult": "I need help with your software development services",
  "Confidence": "0.95"
}
```

**Response:** TwiML XML with AI response
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">Absolutely! We specialize in custom software development, mobile applications, and AI solutions. What specific project are you working on?</Say>
    <Gather input="speech" action="https://princedevops.live/dizzcall-ai-dialer-api/webhook/speech" method="POST" timeout="5" speechTimeout="3">
        <Say voice="Polly.Joanna">Is there anything else I can help you with?</Say>
    </Gather>
    <Say voice="Polly.Joanna">Thank you for calling Dizaart Systems. Have a great day!</Say>
    <Hangup/>
</Response>
```

### 3. Outbound Call Webhook
**POST** `/webhook/outbound`

**Purpose:** Handle outbound call status updates

**Request Body:**
```json
{
  "CallSid": "CA1234567890abcdef",
  "CallStatus": "completed",
  "Duration": "120",
  "From": "+16084969211",
  "To": "+1234567890"
}
```

**Response:** JSON
```json
{
  "success": true,
  "message": "Outbound call handled",
  "status": "completed",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

### 4. System Status
**GET** `/status`

**Purpose:** Check if the AI system is operational

**Response:**
```json
{
  "success": true,
  "message": "DizzCall AI System Status",
  "status": "operational",
  "ai_available": true,
  "response_time_ms": 1200,
  "timestamp": "2024-01-15T10:30:00.000Z",
  "endpoints": {
    "incoming_webhook": "https://princedevops.live/dizzcall-ai-dialer-api/webhook/incoming",
    "speech_webhook": "https://princedevops.live/dizzcall-ai-dialer-api/webhook/speech",
    "outbound_webhook": "https://princedevops.live/dizzcall-ai-dialer-api/webhook/outbound"
  }
}
```

### 5. Test Integration
**POST** `/test`

**Purpose:** Test the dialer integration without making actual calls

**Request Body:**
```json
{
  "message": "Hello, I need help with your services",
  "caller_phone": "+1234567890"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Dialer integration test completed",
  "data": {
    "test_message": "Hello, I need help with your services",
    "ai_response": "Hi there! This is Alex from Dizaart Systems. I'm excited to help you today. What can I assist you with?",
    "twiml_response": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>...</Response>",
    "caller_phone": "+1234567890",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

---

## 🔧 Integration Steps

### Step 1: Deploy the API
1. Upload `dizzcall-ai-dialer-api.zip` to your cPanel
2. Extract in `public_html/`
3. Set permissions: 755 for folders, 644 for files

### Step 2: Configure Your Dialer
Configure your dialer to use these webhook URLs:

**Incoming Call Webhook:**
```
https://princedevops.live/dizzcall-ai-dialer-api/webhook/incoming
```

**Speech Processing Webhook:**
```
https://princedevops.live/dizzcall-ai-dialer-api/webhook/speech
```

**Outbound Call Webhook:**
```
https://princedevops.live/dizzcall-ai-dialer-api/webhook/outbound
```

### Step 3: Test the Integration
```bash
# Test system status
curl https://princedevops.live/dizzcall-ai-dialer-api/status

# Test AI response
curl -X POST https://princedevops.live/dizzcall-ai-dialer-api/test \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello, I need help", "caller_phone": "+1234567890"}'
```

---

## 📞 Phone Number Configuration

### Your AI Phone Number
**Phone Number:** `+16084969211`

### Twilio Configuration
If using Twilio, configure these webhook URLs in your Twilio Console:

1. **Go to:** [Twilio Console](https://console.twilio.com/)
2. **Navigate to:** Phone Numbers → Manage → Active Numbers
3. **Click on:** `+16084969211`
4. **Set Webhook URLs:**
   - **Voice URL:** `https://princedevops.live/dizzcall-ai-dialer-api/webhook/incoming`
   - **Status Callback URL:** `https://princedevops.live/dizzcall-ai-dialer-api/webhook/outbound`

---

## 🎯 Dialer Integration Examples

### JavaScript/Node.js
```javascript
const axios = require('axios');

const API_BASE = 'https://princedevops.live/dizzcall-ai-dialer-api';

// Test the integration
async function testDialerIntegration() {
  try {
    const response = await axios.post(`${API_BASE}/test`, {
      message: 'Hello, I need help with your services',
      caller_phone: '+1234567890'
    });
    
    console.log('AI Response:', response.data.data.ai_response);
    console.log('TwiML:', response.data.data.twiml_response);
  } catch (error) {
    console.error('Test failed:', error.message);
  }
}

// Check system status
async function checkSystemStatus() {
  try {
    const response = await axios.get(`${API_BASE}/status`);
    console.log('System Status:', response.data.status);
    console.log('AI Available:', response.data.ai_available);
  } catch (error) {
    console.error('Status check failed:', error.message);
  }
}
```

### Python
```python
import requests
import json

API_BASE = 'https://princedevops.live/dizzcall-ai-dialer-api'

def test_dialer_integration():
    try:
        response = requests.post(f'{API_BASE}/test', json={
            'message': 'Hello, I need help with your services',
            'caller_phone': '+1234567890'
        })
        
        data = response.json()
        print('AI Response:', data['data']['ai_response'])
        print('TwiML:', data['data']['twiml_response'])
    except Exception as e:
        print('Test failed:', str(e))

def check_system_status():
    try:
        response = requests.get(f'{API_BASE}/status')
        data = response.json()
        print('System Status:', data['status'])
        print('AI Available:', data['ai_available'])
    except Exception as e:
        print('Status check failed:', str(e))
```

### PHP
```php
<?php
$apiBase = 'https://princedevops.live/dizzcall-ai-dialer-api';

function testDialerIntegration() {
    global $apiBase;
    
    $data = [
        'message' => 'Hello, I need help with your services',
        'caller_phone' => '+1234567890'
    ];
    
    $options = [
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => json_encode($data)
        ]
    ];
    
    $context = stream_context_create($options);
    $response = file_get_contents($apiBase . '/test', false, $context);
    $result = json_decode($response, true);
    
    echo 'AI Response: ' . $result['data']['ai_response'] . "\n";
    echo 'TwiML: ' . $result['data']['twiml_response'] . "\n";
}

function checkSystemStatus() {
    global $apiBase;
    
    $response = file_get_contents($apiBase . '/status');
    $result = json_decode($response, true);
    
    echo 'System Status: ' . $result['status'] . "\n";
    echo 'AI Available: ' . ($result['ai_available'] ? 'Yes' : 'No') . "\n";
}
?>
```

---

## 📊 Monitoring and Logs

### Call Logs
All calls are logged to: `/logs/dialer_calls.log`

### Error Logs
Errors are logged to: `/logs/errors.log`

### Log Format
```json
{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "type": "incoming",
  "data": {
    "From": "+1234567890",
    "To": "+16084969211",
    "CallSid": "CA1234567890abcdef"
  }
}
```

---

## 🚨 Troubleshooting

### Common Issues

**1. 500 Internal Server Error**
- Check file permissions (755 for folders, 644 for files)
- Verify PHP version (7.4+ required)
- Check error logs

**2. AI Not Responding**
- Verify Gemini API key is working
- Check internet connection
- Verify API quota limits

**3. TwiML Not Working**
- Check webhook URLs are correct
- Verify Twilio configuration
- Test with Twilio's webhook validator

**4. CORS Issues**
- Check .htaccess CORS headers
- Verify server configuration

### Debug Steps
1. **Test individual endpoints** with curl/Postman
2. **Check system status** endpoint
3. **Verify webhook URLs** are accessible
4. **Check logs** for error details

---

## ✅ Integration Checklist

- [ ] API deployed to cPanel
- [ ] Webhook URLs configured in dialer
- [ ] System status check passes
- [ ] Test integration works
- [ ] Phone number configured
- [ ] Twilio webhooks set (if using Twilio)
- [ ] Monitoring setup
- [ ] Error handling implemented

---

## 🎉 Ready for Production!

Your dialer integration API is ready! The AI will:

1. **Answer incoming calls** with professional greetings
2. **Process caller speech** and generate intelligent responses
3. **Handle multiple conversation turns** naturally
4. **Log all interactions** for monitoring
5. **Provide fallback responses** if AI fails

**Your senior can now integrate this API with their dialer system!** 🚀

---

## 📞 Support

For technical support:
- **Email:** info@dizaartsystems.com
- **Phone:** +16084969211 (AI will answer!)
- **API Status:** Check `/status` endpoint

**🎯 Your AI phone system is ready for dialer integration!**
