<?php
/**
 * DizzCall AI - Dialer Integration API
 * Real API for dialer system integration
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Simple routing
$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);

// Remove the base path from the URL
$base_path = '/dialer-api';
if (strpos($path, $base_path) === 0) {
    $path = substr($path, strlen($base_path));
}

// Remove query string
$path = strtok($path, '?');

// Route handling
switch ($path) {
    case '/webhook/incoming':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleIncomingCall();
        }
        break;
        
    case '/webhook/speech':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleSpeech();
        }
        break;
        
    case '/webhook/outbound':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            handleOutboundCall();
        }
        break;
        
    case '/status':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            getSystemStatus();
        }
        break;
        
    case '/test':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            testDialerIntegration();
        }
        break;
        
    default:
        showIntegrationInfo();
        break;
}

/**
 * Handle Incoming Call from Dialer
 * This is what the dialer calls when someone calls in
 */
function handleIncomingCall() {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        // Log the incoming call
        logCall('incoming', $input);
        
        // Get caller information
        $from = $input['From'] ?? $input['from'] ?? 'unknown';
        $to = $input['To'] ?? $input['to'] ?? 'unknown';
        
        // Generate AI greeting
        $greeting = generateAIGreeting($from);
        
        // Create TwiML response for Twilio
        $twiml = generateTwiML($greeting);
        
        // Return TwiML response
        header('Content-Type: text/xml');
        echo $twiml;
        
    } catch (Exception $e) {
        logError('handleIncomingCall', $e->getMessage());
        
        // Fallback TwiML
        $fallbackTwiML = '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">Thank you for calling Dizaart Systems. I apologize, but I\'m experiencing technical difficulties. Please try again later.</Say>
    <Hangup/>
</Response>';
        
        header('Content-Type: text/xml');
        echo $fallbackTwiML;
    }
}

/**
 * Handle Speech Input from Dialer
 * This processes what the caller says
 */
function handleSpeech() {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        // Log the speech input
        logCall('speech', $input);
        
        $speechResult = $input['SpeechResult'] ?? $input['speech_result'] ?? '';
        $from = $input['From'] ?? $input['from'] ?? 'unknown';
        
        if (empty($speechResult)) {
            // No speech detected, ask again
            $twiml = '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">I didn\'t catch that. Could you please repeat what you need help with?</Say>
    <Gather input="speech" action="' . getCurrentUrl() . '/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. Have a great day!</Say>
    <Hangup/>
</Response>';
        } else {
            // Process speech with AI
            $aiResponse = processWithAI($speechResult, $from);
            
            // Create TwiML response
            $twiml = generateTwiML($aiResponse, true);
        }
        
        header('Content-Type: text/xml');
        echo $twiml;
        
    } catch (Exception $e) {
        logError('handleSpeech', $e->getMessage());
        
        // Fallback TwiML
        $fallbackTwiML = '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">Thank you for calling. I\'m experiencing technical difficulties. Please try again later.</Say>
    <Hangup/>
</Response>';
        
        header('Content-Type: text/xml');
        echo $fallbackTwiML;
    }
}

/**
 * Handle Outbound Call from Dialer
 * This handles outbound calls made by the dialer
 */
function handleOutboundCall() {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        // Log the outbound call
        logCall('outbound', $input);
        
        $callStatus = $input['CallStatus'] ?? $input['call_status'] ?? 'unknown';
        
        if ($callStatus === 'completed') {
            // Call completed, log the result
            logCall('completed', $input);
        }
        
        // Return success response
        sendResponse([
            'success' => true,
            'message' => 'Outbound call handled',
            'status' => $callStatus,
            'timestamp' => date('c')
        ]);
        
    } catch (Exception $e) {
        logError('handleOutboundCall', $e->getMessage());
        sendResponse([
            'success' => false,
            'message' => 'Failed to handle outbound call',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Get System Status
 * Check if the AI system is operational
 */
function getSystemStatus() {
    try {
        // Test AI connection
        $aiTest = testAIConnection();
        
        sendResponse([
            'success' => true,
            'message' => 'DizzCall AI System Status',
            'status' => 'operational',
            'ai_available' => $aiTest['success'],
            'response_time_ms' => $aiTest['response_time_ms'] ?? 0,
            'timestamp' => date('c'),
            'endpoints' => [
                'incoming_webhook' => getCurrentUrl() . '/webhook/incoming',
                'speech_webhook' => getCurrentUrl() . '/webhook/speech',
                'outbound_webhook' => getCurrentUrl() . '/webhook/outbound'
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'System status check failed',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Test Dialer Integration
 * Test endpoint for dialer integration
 */
function testDialerIntegration() {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $testMessage = $input['message'] ?? 'Hello, this is a test call';
        $callerPhone = $input['caller_phone'] ?? '+1234567890';
        
        // Test AI response
        $aiResponse = processWithAI($testMessage, $callerPhone);
        
        // Generate test TwiML
        $testTwiML = generateTwiML($aiResponse);
        
        sendResponse([
            'success' => true,
            'message' => 'Dialer integration test completed',
            'data' => [
                'test_message' => $testMessage,
                'ai_response' => $aiResponse,
                'twiml_response' => $testTwiML,
                'caller_phone' => $callerPhone,
                'timestamp' => date('c')
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'Dialer integration test failed',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Show Integration Information
 */
function showIntegrationInfo() {
    sendResponse([
        'success' => true,
        'message' => 'DizzCall AI - Dialer Integration API',
        'version' => '1.0.0',
        'description' => 'API for integrating AI phone system with dialer software',
        'endpoints' => [
            'POST /webhook/incoming' => 'Handle incoming calls from dialer',
            'POST /webhook/speech' => 'Process speech input from callers',
            'POST /webhook/outbound' => 'Handle outbound call status updates',
            'GET /status' => 'Check system status',
            'POST /test' => 'Test dialer integration'
        ],
        'webhook_urls' => [
            'incoming' => 'https://princedevops.live/dizzcall-ai-dialer-api/webhook/incoming',
            'speech' => 'https://princedevops.live/dizzcall-ai-dialer-api/webhook/speech',
            'outbound' => 'https://princedevops.live/dizzcall-ai-dialer-api/webhook/outbound'
        ],
        'phone_number' => '+16084969211',
        'documentation' => 'See DIALER_INTEGRATION_GUIDE.md for detailed usage',
        'timestamp' => date('c')
    ]);
}

/**
 * Process speech with AI
 */
function processWithAI($speech, $phoneNumber) {
    try {
        $apiKey = 'AIzaSyA90MNxC9K8aOh9u9sRHpHba55pfDK2QoM';
        
        // Add context for phone conversation
        $context = 'You are Alex, a helpful AI assistant from Dizaart Systems. Respond professionally and helpfully to customer inquiries. Keep responses concise and friendly for phone conversation. ';
        $fullMessage = $context . $speech;
        
        $response = callGeminiAPI($apiKey, $fullMessage);
        
        if ($response['success']) {
            return $response['response'];
        } else {
            return 'Thank you for calling Dizaart Systems. I apologize, but I\'m experiencing technical difficulties. Please try again later.';
        }
        
    } catch (Exception $e) {
        logError('processWithAI', $e->getMessage());
        return 'Thank you for calling Dizaart Systems. I apologize, but I\'m experiencing technical difficulties. Please try again later.';
    }
}

/**
 * Generate AI greeting
 */
function generateAIGreeting($phoneNumber) {
    try {
        $greetings = [
            'Hi there! This is Alex from Dizaart Systems. I\'m excited to help you today. What can I assist you with?',
            'Hello! Welcome to Dizaart Systems. I\'m Alex, and I\'m here to help you with any questions you might have.',
            'Good day! This is Alex from Dizaart Systems. I\'m thrilled to assist you today. How can I help you?',
            'Hi! Thanks for calling Dizaart Systems. I\'m Alex, and I\'m here to provide you with excellent service. What can I do for you?'
        ];
        
        // Use phone number to determine greeting (for consistency)
        $index = crc32($phoneNumber) % count($greetings);
        return $greetings[$index];
        
    } catch (Exception $e) {
        return 'Hello! This is Alex from Dizaart Systems. How can I help you today?';
    }
}

/**
 * Generate TwiML response
 */
function generateTwiML($message, $continueConversation = false) {
    $message = htmlspecialchars($message);
    
    if ($continueConversation) {
        return '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">' . $message . '</Say>
    <Gather input="speech" action="' . getCurrentUrl() . '/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>';
    } else {
        return '<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="Polly.Joanna">' . $message . '</Say>
    <Gather input="speech" action="' . getCurrentUrl() . '/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>';
    }
}

/**
 * Call Gemini API
 */
function callGeminiAPI($apiKey, $message) {
    $startTime = microtime(true);
    
    $url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' . $apiKey;
    
    $data = [
        'contents' => [
            [
                'parts' => [
                    ['text' => $message]
                ]
            ]
        ],
        'generationConfig' => [
            'maxOutputTokens' => 100,
            'temperature' => 0.1,
            'topP' => 0.8
        ]
    ];
    
    $options = [
        'http' => [
            'header' => "Content-Type: application/json\r\n",
            'method' => 'POST',
            'content' => json_encode($data),
            'timeout' => 10
        ]
    ];
    
    $context = stream_context_create($options);
    $result = @file_get_contents($url, false, $context);
    
    $responseTime = round((microtime(true) - $startTime) * 1000, 2);
    
    if ($result === false) {
        return [
            'success' => false,
            'error' => 'Failed to connect to AI service',
            'response_time_ms' => $responseTime
        ];
    }
    
    $response = json_decode($result, true);
    
    if (isset($response['candidates'][0]['content']['parts'][0]['text'])) {
        return [
            'success' => true,
            'response' => $response['candidates'][0]['content']['parts'][0]['text'],
            'response_time_ms' => $responseTime
        ];
    } else {
        return [
            'success' => false,
            'error' => 'Invalid response from AI service',
            'response_time_ms' => $responseTime
        ];
    }
}

/**
 * Test AI connection
 */
function testAIConnection() {
    try {
        $apiKey = 'AIzaSyA90MNxC9K8aOh9u9sRHpHba55pfDK2QoM';
        $testMessage = 'Hello, test connection';
        
        $response = callGeminiAPI($apiKey, $testMessage);
        return $response;
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage(),
            'response_time_ms' => 0
        ];
    }
}

/**
 * Get current URL
 */
function getCurrentUrl() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $path = dirname($_SERVER['REQUEST_URI']);
    return $protocol . '://' . $host . $path;
}

/**
 * Log call information
 */
function logCall($type, $data) {
    $logFile = __DIR__ . '/logs/dialer_calls.log';
    $logDir = dirname($logFile);
    
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logEntry = [
        'timestamp' => date('c'),
        'type' => $type,
        'data' => $data
    ];
    
    file_put_contents($logFile, json_encode($logEntry) . "\n", FILE_APPEND | LOCK_EX);
}

/**
 * Log errors
 */
function logError($function, $message) {
    $logFile = __DIR__ . '/logs/errors.log';
    $logDir = dirname($logFile);
    
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logEntry = [
        'timestamp' => date('c'),
        'function' => $function,
        'error' => $message
    ];
    
    file_put_contents($logFile, json_encode($logEntry) . "\n", FILE_APPEND | LOCK_EX);
}

/**
 * Send JSON response
 */
function sendResponse($data, $httpCode = 200) {
    http_response_code($httpCode);
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit();
}
?>
