<?php
/**
 * DizzCall AI - Standalone Test API
 * Simple API for testing AI functionality without full Laravel setup
 */

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');

// 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 = '/dizzcall-ai-test-api';
if (strpos($path, $base_path) === 0) {
    $path = substr($path, strlen($base_path));
}

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

// Route handling
switch ($path) {
    case '/connection':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            testConnection();
        }
        break;
        
    case '/simulate-call':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            simulateCall();
        }
        break;
        
    case '/test-responses':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            testResponses();
        }
        break;
        
    case '/performance':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            getPerformance();
        }
        break;
        
    case '/scenarios':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            testScenarios();
        }
        break;
        
    case '/dashboard':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            showDashboard();
        }
        break;
        
    default:
        showApiInfo();
        break;
}

/**
 * Test AI Connection
 */
function testConnection() {
    try {
        // Test Gemini API connection
        $apiKey = 'AIzaSyA90MNxC9K8aOh9u9sRHpHba55pfDK2QoM';
        $testMessage = 'Hello, test connection';
        
        $response = callGeminiAPI($apiKey, $testMessage);
        
        if ($response['success']) {
            sendResponse([
                'success' => true,
                'message' => 'AI System Status Check',
                'timestamp' => date('c'),
                'details' => [
                    'ai_service' => 'operational',
                    'model' => 'gemini-1.5-flash',
                    'response_time_ms' => $response['response_time_ms']
                ],
                'system_status' => 'operational'
            ]);
        } else {
            sendResponse([
                'success' => false,
                'message' => 'AI System Unavailable',
                'error' => $response['error'],
                'timestamp' => date('c')
            ], 500);
        }
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'AI System Error',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Simulate Phone Call
 */
function simulateCall() {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        sendResponse([
            'success' => false,
            'message' => 'Invalid JSON input',
            'timestamp' => date('c')
        ], 400);
        return;
    }
    
    $callerPhone = $input['caller_phone'] ?? '+1234567890';
    $message = $input['message'] ?? 'Hello';
    $conversationType = $input['conversation_type'] ?? 'general';
    
    if (empty($message)) {
        sendResponse([
            'success' => false,
            'message' => 'Message is required',
            'timestamp' => date('c')
        ], 400);
        return;
    }
    
    try {
        $startTime = microtime(true);
        
        // Process with AI
        $aiResponse = processWithAI($message, $conversationType);
        
        $responseTime = round((microtime(true) - $startTime) * 1000, 2);
        
        // Log the test call
        logTestCall($callerPhone, $message, $aiResponse['response']);
        
        sendResponse([
            'success' => true,
            'message' => 'Phone call simulation completed',
            'data' => [
                'caller_phone' => $callerPhone,
                'user_message' => $message,
                'ai_response' => $aiResponse['response'],
                'response_time_ms' => $responseTime,
                'model_used' => $aiResponse['model'],
                'conversation_type' => $conversationType,
                'timestamp' => date('c')
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'Phone call simulation failed',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Test Multiple AI Responses
 */
function testResponses() {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['test_messages'])) {
        sendResponse([
            'success' => false,
            'message' => 'test_messages array is required',
            'timestamp' => date('c')
        ], 400);
        return;
    }
    
    $testMessages = $input['test_messages'];
    $conversationType = $input['conversation_type'] ?? 'general';
    
    if (!is_array($testMessages) || count($testMessages) === 0) {
        sendResponse([
            'success' => false,
            'message' => 'test_messages must be a non-empty array',
            'timestamp' => date('c')
        ], 400);
        return;
    }
    
    try {
        $results = [];
        
        foreach ($testMessages as $index => $message) {
            $startTime = microtime(true);
            $aiResponse = processWithAI($message, $conversationType);
            $responseTime = round((microtime(true) - $startTime) * 1000, 2);
            
            $results[] = [
                'test_number' => $index + 1,
                'user_message' => $message,
                'ai_response' => $aiResponse['response'],
                'response_time_ms' => $responseTime,
                'model_used' => $aiResponse['model'],
                'success' => $aiResponse['success']
            ];
        }
        
        sendResponse([
            'success' => true,
            'message' => 'AI response testing completed',
            'data' => [
                'total_tests' => count($testMessages),
                'conversation_type' => $conversationType,
                'results' => $results,
                'timestamp' => date('c')
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'AI response testing failed',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Get Performance Metrics
 */
function getPerformance() {
    try {
        // Test AI response time
        $startTime = microtime(true);
        $testResponse = processWithAI('Hello, performance test', 'general');
        $responseTime = round((microtime(true) - $startTime) * 1000, 2);
        
        // Get test call statistics
        $testCalls = getTestCallStats();
        
        sendResponse([
            'success' => true,
            'message' => 'Performance metrics retrieved',
            'data' => [
                'ai_response_time_ms' => $responseTime,
                'ai_available' => $testResponse['success'],
                'total_test_calls' => $testCalls['total'],
                'successful_test_calls' => $testCalls['successful'],
                'success_rate' => $testCalls['total'] > 0 ? round(($testCalls['successful'] / $testCalls['total']) * 100, 2) : 0,
                'system_uptime' => 'operational',
                'timestamp' => date('c')
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'Failed to get performance metrics',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Test Predefined Scenarios
 */
function testScenarios() {
    try {
        $scenarios = [
            'greeting' => 'Hello, I\'m interested in your services',
            'pricing' => 'What are your prices for software development?',
            'support' => 'I need help with my existing project',
            'technical' => 'Do you work with React and Laravel?',
            'scheduling' => 'Can I schedule a meeting with your team?',
            'complaint' => 'I\'m not satisfied with the service',
            'compliment' => 'Your team did an excellent job on our project'
        ];
        
        $results = [];
        
        foreach ($scenarios as $scenario => $message) {
            $startTime = microtime(true);
            $aiResponse = processWithAI($message, 'general');
            $responseTime = round((microtime(true) - $startTime) * 1000, 2);
            
            $results[] = [
                'scenario' => $scenario,
                'message' => $message,
                'ai_response' => $aiResponse['response'],
                'response_time_ms' => $responseTime,
                'success' => $aiResponse['success']
            ];
        }
        
        sendResponse([
            'success' => true,
            'message' => 'Scenario testing completed',
            'data' => [
                'total_scenarios' => count($scenarios),
                'results' => $results,
                'timestamp' => date('c')
            ]
        ]);
        
    } catch (Exception $e) {
        sendResponse([
            'success' => false,
            'message' => 'Scenario testing failed',
            'error' => $e->getMessage(),
            'timestamp' => date('c')
        ], 500);
    }
}

/**
 * Show Test Dashboard
 */
function showDashboard() {
    // Set content type to HTML for dashboard
    header('Content-Type: text/html; charset=UTF-8');
    
    $dashboardFile = __DIR__ . '/dashboard.html';
    if (file_exists($dashboardFile)) {
        $dashboardHtml = file_get_contents($dashboardFile);
        echo $dashboardHtml;
    } else {
        echo '<h1>Dashboard not found</h1><p>dashboard.html file is missing</p>';
    }
}

/**
 * Show API Information
 */
function showApiInfo() {
    sendResponse([
        'success' => true,
        'message' => 'DizzCall AI Test API',
        'version' => '1.0.0',
        'endpoints' => [
            'GET /connection' => 'Test AI system connection',
            'POST /simulate-call' => 'Simulate phone call conversation',
            'POST /test-responses' => 'Test multiple AI responses',
            'GET /performance' => 'Get system performance metrics',
            'GET /scenarios' => 'Test predefined scenarios',
            'GET /dashboard' => 'Show test dashboard'
        ],
        'documentation' => 'See CLIENT_API_DOCUMENTATION.md for detailed usage',
        'timestamp' => date('c')
    ]);
}

/**
 * Process message with AI
 */
function processWithAI($message, $conversationType = 'general') {
    try {
        $apiKey = 'AIzaSyA90MNxC9K8aOh9u9sRHpHba55pfDK2QoM';
        
        // Add context based on conversation type
        $context = getContextForType($conversationType);
        $fullMessage = $context . $message;
        
        $response = callGeminiAPI($apiKey, $fullMessage);
        
        if ($response['success']) {
            return [
                'success' => true,
                'response' => $response['response'],
                'model' => 'gemini-1.5-flash'
            ];
        } else {
            return [
                'success' => false,
                'response' => 'Thank you for calling. I\'m experiencing technical difficulties. Please try again later.',
                'model' => 'fallback'
            ];
        }
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'response' => 'Thank you for calling. I\'m experiencing technical difficulties. Please try again later.',
            'model' => 'fallback'
        ];
    }
}

/**
 * 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
        ];
    }
}

/**
 * Get context for conversation type
 */
function getContextForType($type) {
    $contexts = [
        'general' => 'You are Alex, a helpful AI assistant from Dizaart Systems. Respond professionally and helpfully to customer inquiries. Keep responses concise and friendly. ',
        'sales' => 'You are Alex, a sales representative from Dizaart Systems. Help customers understand our services and pricing. Be enthusiastic and professional. ',
        'support' => 'You are Alex, a technical support representative from Dizaart Systems. Help customers with their technical issues and provide solutions. ',
        'technical' => 'You are Alex, a technical expert from Dizaart Systems. Answer technical questions about our development services and technologies. '
    ];
    
    return $contexts[$type] ?? $contexts['general'];
}

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

/**
 * Get test call statistics
 */
function getTestCallStats() {
    $logFile = __DIR__ . '/logs/test_calls.log';
    
    if (!file_exists($logFile)) {
        return ['total' => 0, 'successful' => 0];
    }
    
    $lines = file($logFile, FILE_IGNORE_NEW_LINES);
    $total = count($lines);
    $successful = 0;
    
    foreach ($lines as $line) {
        $entry = json_decode($line, true);
        if ($entry && !empty($entry['response'])) {
            $successful++;
        }
    }
    
    return ['total' => $total, 'successful' => $successful];
}

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