<?php
/**
 * Cliente API para Voiso
 * Maneja todas las operaciones relacionadas con la integración de Voiso
 */

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

require_once BASE_PATH . '/database/connection.php';

class VoisoClient {
    private $pdo;
    private $apiBaseUrl;
    private $apiToken;
    private $defaultCallerId;
    private $defaultAgentId;
    
    public function __construct($pdo = null) {
        if ($pdo === null) {
            $db = Database::getInstance();
            $this->pdo = $db->getConnection();
        } else {
            $this->pdo = $pdo;
        }
        
        $this->loadConfiguration();
    }
    
    /**
     * Carga la configuración de Voiso desde la base de datos
     */
    private function loadConfiguration() {
        try {
            $stmt = $this->pdo->prepare("SELECT setting_key, setting_value FROM integration_settings WHERE integration_name = 'voiso'");
            $stmt->execute();
            
            while ($row = $stmt->fetch()) {
                switch ($row['setting_key']) {
                    case 'api_base_url':
                        $this->apiBaseUrl = $row['setting_value'];
                        break;
                    case 'api_token':
                        $this->apiToken = $row['setting_value'];
                        break;
                    case 'default_caller_id':
                        $this->defaultCallerId = $row['setting_value'];
                        break;
                    case 'default_agent_id':
                        $this->defaultAgentId = $row['setting_value'];
                        break;
                }
            }
        } catch (Exception $e) {
            error_log("Error loading Voiso configuration: " . $e->getMessage());
        }
    }
    
    /**
     * Verifica si Voiso está configurado correctamente
     */
    public function isConfigured() {
        return !empty($this->apiBaseUrl) && !empty($this->apiToken);
    }
    
    /**
     * Guarda la configuración de Voiso
     */
    public function saveConfiguration($apiBaseUrl, $apiToken, $defaultCallerId = '', $defaultAgentId = '') {
        try {
            $this->pdo->beginTransaction();
            
            // Eliminar configuración existente
            $stmt = $this->pdo->prepare("DELETE FROM integration_settings WHERE integration_name = 'voiso'");
            $stmt->execute();
            
            // Insertar nueva configuración
            $settings = [
                'api_base_url' => $apiBaseUrl,
                'api_token' => $apiToken,
                'default_caller_id' => $defaultCallerId,
                'default_agent_id' => $defaultAgentId
            ];
            
            $stmt = $this->pdo->prepare("INSERT INTO integration_settings (integration_name, setting_key, setting_value) VALUES ('voiso', ?, ?)");
            
            foreach ($settings as $key => $value) {
                if (!empty($value)) {
                    $stmt->execute([$key, $value]);
                }
            }
            
            $this->pdo->commit();
            
            // Actualizar propiedades locales
            $this->apiBaseUrl = $apiBaseUrl;
            $this->apiToken = $apiToken;
            $this->defaultCallerId = $defaultCallerId;
            $this->defaultAgentId = $defaultAgentId;
            
            return true;
        } catch (Exception $e) {
            $this->pdo->rollBack();
            error_log("Error saving Voiso configuration: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Realiza una llamada a la API de Voiso
     */
    private function makeApiCall($endpoint, $method = 'GET', $data = null) {
        if (!$this->isConfigured()) {
            throw new Exception('Voiso no está configurado correctamente');
        }
        
        $url = rtrim($this->apiBaseUrl, '/') . '/' . ltrim($endpoint, '/');
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiToken,
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        } elseif ($method === 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception('Error de conexión: ' . $error);
        }
        
        if ($httpCode >= 400) {
            throw new Exception('Error HTTP: ' . $httpCode);
        }
        
        return json_decode($response, true);
    }
    
    /**
     * Prueba la conexión con Voiso
     */
    public function testConnection() {
        try {
            $result = $this->makeApiCall('/test');
            return [
                'success' => true,
                'message' => 'Conexión exitosa con Voiso',
                'data' => $result
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Crea un lead en Voiso
     */
    public function createLead($leadData) {
        try {
            $data = [
                'name' => $leadData['name'] ?? '',
                'phone' => $leadData['phone'] ?? '',
                'email' => $leadData['email'] ?? '',
                'caller_id' => $leadData['caller_id'] ?? $this->defaultCallerId,
                'agent_id' => $leadData['agent_id'] ?? $this->defaultAgentId
            ];
            
            $result = $this->makeApiCall('/leads', 'POST', $data);
            
            return [
                'success' => true,
                'message' => 'Lead creado exitosamente en Voiso',
                'lead_id' => $result['id'] ?? null,
                'data' => $result
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Obtiene la configuración actual (sin token)
     */
    public function getConfiguration() {
        return [
            'api_base_url' => $this->apiBaseUrl,
            'default_caller_id' => $this->defaultCallerId,
            'default_agent_id' => $this->defaultAgentId,
            'configured' => $this->isConfigured()
        ];
    }
    
    /**
     * Realiza una llamada telefónica usando la API de Voiso
     */
    public function makeCall($phone, $context = []) {
        try {
            $data = [
                'phone' => $phone,
                'caller_id' => $this->defaultCallerId,
                'agent_id' => $this->defaultAgentId,
                'context' => $context
            ];
            
            $result = $this->makeApiCall('/calls', 'POST', $data);
            
            return [
                'success' => true,
                'message' => 'Llamada iniciada exitosamente',
                'call_id' => $result['id'] ?? null,
                'data' => $result
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}