<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/session_check.php';

requireAdmin();

$pageTitle = 'Configuración del Agente IA';

require_once __DIR__ . '/../templates/header.php';

require_once __DIR__ . '/../src/IA/Agent.php';
$agent = new \IA\Agent();

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_kb_config'])) {
        $kbConfigKeys = [
            'kb_db_host' => 'kb_host',
            'kb_db_port' => 'kb_port',
            'kb_db_name' => 'kb_dbname',
            'kb_db_user' => 'kb_user',
        ];
        
        $saved = true;
        foreach ($kbConfigKeys as $dbKey => $postKey) {
            $value = $_POST[$postKey] ?? '';
            if (!$agent->updateConfig($dbKey, $value)) {
                $saved = false;
            }
        }
        
        if (!empty($_POST['kb_pass'])) {
            if (!$agent->updateConfig('kb_db_pass', $_POST['kb_pass'])) {
                $saved = false;
            }
        }
        
        if ($saved) {
            $message = 'Configuración de base de datos actualizada correctamente.';
            $messageType = 'success';
            $agent = new \IA\Agent();
            $config = $agent->getAllConfig();
        } else {
            $message = 'Error al guardar la configuración.';
            $messageType = 'danger';
        }
    } elseif (isset($_POST['update_config'])) {
        $key = $_POST['config_key'] ?? '';
        $value = $_POST['config_value'] ?? '';

        if (!empty($key) && $agent->updateConfig($key, $value)) {
            $message = 'Configuración actualizada correctamente.';
            $messageType = 'success';
            $agent = new \IA\Agent();
        } else {
            $message = 'Error al actualizar la configuración.';
            $messageType = 'danger';
        }
    } elseif (isset($_POST['update_config_model']) && isset($_POST['config_value_model'])) {
        $key = 'ai_model';
        $value = $_POST['config_value_model'] ?? '';

        if (!empty($value) && $agent->updateConfig($key, $value)) {
            $message = 'Modelo de IA actualizado correctamente.';
            $messageType = 'success';
            $agent = new \IA\Agent();
        } else {
            $message = 'Error al actualizar el modelo.';
            $messageType = 'danger';
        }
    } elseif (isset($_POST['test_connection'])) {
        $result = $agent->testKbConnection();
        $message = $result['message'];
        $messageType = $result['success'] ? 'success' : 'danger';
    } elseif (isset($_POST['test_question'])) {
        $question = $_POST['test_question'] ?? '';
        if (!empty($question)) {
            $response = $agent->generateResponse($question);
            $testResponse = $response;
        }
    }
}

$config = $agent->getAllConfig();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-robot"></i> Configuración del Agente IA</h2>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-<?= $messageType ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($message) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-database"></i> Conexión a Knowledge Base</h5>
            </div>
            <div class="card-body">
                <form method="POST">
    <div class="mb-3">
        <label class="form-label">Host</label>
        <input type="text" name="kb_host" class="form-control" value="<?= htmlspecialchars($config['kb_db_host'] ?? $_ENV['KB_DB_HOST'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label class="form-label">Puerto</label>
        <input type="text" name="kb_port" class="form-control" value="<?= htmlspecialchars($config['kb_db_port'] ?? $_ENV['KB_DB_PORT'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label class="form-label">Base de Datos</label>
        <input type="text" name="kb_dbname" class="form-control" value="<?= htmlspecialchars($config['kb_db_name'] ?? $_ENV['KB_DB_NAME'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label class="form-label">Usuario</label>
        <input type="text" name="kb_user" class="form-control" value="<?= htmlspecialchars($config['kb_db_user'] ?? $_ENV['KB_DB_USER'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label class="form-label">Contraseña</label>
        <input type="password" name="kb_pass" class="form-control" value="<?= htmlspecialchars($config['kb_db_pass'] ?? '') ?>" placeholder="Dejar vacío para mantener actual">
    </div>
    <div class="d-grid gap-2 d-md-flex">
        <button type="submit" name="update_kb_config" class="btn btn-primary">
            <i class="bi bi-save"></i> Guardar
        </button>
        <button type="submit" name="test_connection" class="btn btn-outline-primary">
            <i class="bi bi-plug"></i> Probar Conexión
        </button>
    </div>
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-cpu"></i> Configuración de IA</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Habilitar Knowledge Base</label>
                        <select name="config_value" class="form-select">
                            <option value="1" <?= ($config['kb_enabled'] ?? '1') === '1' ? 'selected' : '' ?>>Habilitado</option>
                            <option value="0" <?= ($config['kb_enabled'] ?? '1') === '0' ? 'selected' : '' ?>>Deshabilitado</option>
                        </select>
                        <input type="hidden" name="config_key" value="kb_enabled">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Modelo de IA (Groq)</label>
                        <select name="config_value_model" class="form-select">
                            <option value="llama-3.1-8b-instant" <?= ($config['ai_model'] ?? 'llama-3.1-8b-instant') === 'llama-3.1-8b-instant' ? 'selected' : '' ?>>Llama 3.1 8B (Rápido - Recomendado)</option>
                            <option value="mixtral-8x7b-32768" <?= ($config['ai_model'] ?? '') === 'mixtral-8x7b-32768' ? 'selected' : '' ?>>Mixtral 8x7B</option>
                            <option value="llama3-70b-8192" <?= ($config['ai_model'] ?? '') === 'llama3-70b-8192' ? 'selected' : '' ?>>Llama 3 70B</option>
                        </select>
                        <small class="text-muted">Solo modelos gratuitos. Si se agotan los tokens, cambiará automáticamente al siguiente.</small>
                    </div>
                    <div class="d-grid gap-2">
                        <button type="submit" name="update_config" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> Guardar Configuración
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-chat-left-text"></i> Prompt del Sistema</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Instrucciones para el agente</label>
                        <textarea name="config_value" class="form-control" rows="6"><?= htmlspecialchars($config['system_prompt'] ?? '') ?></textarea>
                        <small class="text-muted">Instrucciones que seguirá el agente al responder.</small>
                        <input type="hidden" name="config_key" value="system_prompt">
                    </div>
                    <div class="d-grid">
                        <button type="submit" name="update_config" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> Guardar Prompt
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-sliders"></i> Parámetros Adicionales</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Máximo de resultados de KB</label>
                        <input type="number" name="config_value" class="form-control" value="<?= htmlspecialchars($config['kb_max_results'] ?? '5') ?>" min="1" max="20">
                        <small class="text-muted">Cantidad de artículos a buscar en la base de conocimientos.</small>
                        <input type="hidden" name="config_key" value="kb_max_results">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Máximo de caracteres en respuesta</label>
                        <input type="number" name="config_value2" class="form-control" value="<?= htmlspecialchars($config['response_max_length'] ?? '1500') ?>" min="100" max="4000">
                        <small class="text-muted">Límite de caracteres en las respuestas del agente.</small>
                    </div>
                    <div class="d-grid">
                        <button type="submit" name="update_config" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> Guardar Parámetros
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-chat-dots"></i> Prueba del Agente</h5>
            </div>
            <div class="card-body">
                <form method="POST" class="mb-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-question-circle"></i></span>
                        <input type="text" name="test_question" class="form-control" placeholder="Escribe una pregunta para probar el agente..." value="<?= htmlspecialchars($_POST['test_question'] ?? '') ?>">
                        <button type="submit" class="btn btn-success">
                            <i class="bi bi-send"></i> Enviar
                        </button>
                    </div>
                </form>
                
                <?php if (isset($testResponse)): ?>
                <div class="mt-3">
                    <label class="form-label text-muted">Respuesta del agente:</label>
                    <div class="p-3 bg-light rounded border">
                        <pre class="mb-0 white-space: pre-wrap;"><?= htmlspecialchars($testResponse) ?></pre>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
