<?php

session_start();

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

include("../config/db.php");
include("../includes/auth.php");

require_once("../includes/conversation_engine.php");
require_once("../includes/ai_engine.php");

$user_id = $_SESSION['user_id'];

$response_text = "";
$question = "";

/*
============================================
TODOS LOS USUARIOS LOGUEADOS PUEDEN USAR IA
============================================
*/

if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $question = trim($_POST['question']);

    /*
    ============================================
    MEMORIA CONVERSACIONAL
    ============================================
    */

    ConversationEngine::remember($question);

    $product =
    ConversationEngine::recoverProduct($question);

    $intent =
    ConversationEngine::recoverIntent($question);

    ConversationEngine::setContext(
        $intent,
        $product,
        $question
    );

    if($question != ""){

        $question_lower = strtolower($question);

        /*
        ============================================
        RESPUESTAS NATURALES
        ============================================
        */

        if(
            strpos($question_lower, 'hola') !== false
            ||
            strpos($question_lower, 'buenas') !== false
            ||
            strpos($question_lower, 'hey') !== false
        ){

            $response_text = "

            <div class='result-card'>

                <div class='result-title'>
                    👋 Hola
                </div>

                <div class='result-content'>

                    Soy el asistente comercial de Wolfxell.

                    <br><br>

                    Puedo ayudarte con:

                    <br><br>

                    • tarifas de luz<br>
                    • promociones<br>
                    • objeciones comerciales<br>
                    • permanencias<br>
                    • estrategias de venta<br>
                    • comparaciones<br>
                    • contratos<br>

                    <br>

                    ¿Qué necesitas consultar hoy?

                </div>

            </div>

            ";

        } else {

            /*
            ============================================
            BUSCADOR INTELIGENTE
            ============================================
            */

            $question_words = explode(
                " ",
                strtolower($question)
            );

            $where_parts = [];
            $params = [];
            $types = "";

            foreach($question_words as $word){

                $word = trim($word);

                if(strlen($word) < 3){
                    continue;
                }

                $where_parts[] = "
                    (
                        kb.extracted_text LIKE ?
                        OR kb.title LIKE ?
                        OR kb.category LIKE ?
                        OR kb.description LIKE ?
                    )
                ";

                $search = "%" . $word . "%";

                $params[] = $search;
                $params[] = $search;
                $params[] = $search;
                $params[] = $search;

                $types .= "ssss";
            }

            /*
            ============================================
            SI NO HAY PALABRAS
            ============================================
            */

            if(empty($where_parts)){

                $response_text = "

                <div class='result-card'>

                    <div class='result-title'>
                        🤔 Necesito más información
                    </div>

                    <div class='result-content'>
                        Intenta escribirme algo más específico.
                    </div>

                </div>

                ";

            } else {

                $where_sql = implode(
                    " OR ",
                    $where_parts
                );

                $sql = "

                    SELECT
                        kb.id,
                        kb.title,
                        kb.category,
                        kb.description,
                        kb.extracted_text,
                        c.name AS campaign_name
                    FROM knowledge_base kb
                    LEFT JOIN campaigns c
                    ON kb.campaign_id = c.id
                    WHERE (
                        $where_sql
                    )
                    GROUP BY kb.id
                    ORDER BY kb.created_at DESC
                    LIMIT 5

                ";

                $stmt = $conn->prepare($sql);

                /*
                ============================================
                BIND DINÁMICO
                ============================================
                */

                $bind_values = [];
                $bind_values[] = $types;

                for($i = 0; $i < count($params); $i++){

                    $bind_name = 'bind' . $i;

                    $$bind_name = $params[$i];

                    $bind_values[] = &$$bind_name;
                }

                call_user_func_array(
                    [$stmt, 'bind_param'],
                    $bind_values
                );

                $stmt->execute();

                $result = $stmt->get_result();

                /*
                ============================================
                SI ENCUENTRA RESULTADOS
                ============================================
                */

                if($result->num_rows > 0){

                    while($row = $result->fetch_assoc()){

                        $relevantTexts =
                        AIEngine::extractRelevant(
                            $row['extracted_text'],
                            $question
                        );

                        /*
                        ============================================
                        RESPUESTA IA
                        ============================================
                        */

                        $response_text .=
                        AIEngine::buildAnswer(
                            $row['title'],
                            $row['campaign_name'],
                            $row['category'],
                            $relevantTexts,
                            $question
                        );
                    }

                } else {

                    /*
                    ============================================
                    RESPUESTA HUMANA
                    ============================================
                    */

                    $response_text = "

                    <div class='result-card'>

                        <div class='result-title'>
                            🤔 No encontré resultados exactos
                        </div>

                        <div class='result-content'>

                            No encontré coincidencias exactas,
                            pero puedes intentar preguntarme usando
                            otras palabras.

                            <br><br>

                            Ejemplos:

                            <br><br>

                            • precios luz<br>
                            • tarifas sin permanencia<br>
                            • promociones activas<br>
                            • dual luz y gas<br>
                            • factura<br>
                            • ahorro energético<br>

                            <br>

                            También puedo ayudarte
                            con objeciones comerciales.

                        </div>

                    </div>

                    ";
                }
            }

            /*
            ============================================
            GUARDAR CONSULTA
            ============================================
            */

            if(tableExists($conn, 'ai_queries')){

                $save = $conn->prepare("
                    INSERT INTO ai_queries
                    (
                        user_id,
                        question,
                        response
                    )
                    VALUES
                    (
                        ?, ?, ?
                    )
                ");

                $plain_response =
                strip_tags($response_text);

                $save->bind_param(
                    "iss",
                    $user_id,
                    $question,
                    $plain_response
                );

                $save->execute();
            }
        }
    }
}

/*
============================================
VERIFICAR TABLA
============================================
*/

function tableExists($conn, $table){

    $check =
    $conn->query("
        SHOW TABLES LIKE '$table'
    ");

    return $check->num_rows > 0;
}

?>

<!DOCTYPE html>
<html lang="es">

<head>

<meta charset="UTF-8">

<title>AI Assistant</title>

<link rel="stylesheet" href="/assets/css/style.css">

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-title{
    font-size:42px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.page-subtitle{
    color:#64748b;
    margin-bottom:35px;
}

.ai-box{
    background:#ffffff;
    border-radius:24px;
    padding:30px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
    margin-bottom:30px;
}

textarea{
    width:100%;
    min-height:140px;
    border:none;
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
    font-size:15px;
    resize:none;
    outline:none;
}

.ask-btn{
    margin-top:20px;
    background:#5b3df5;
    color:white;
    border:none;
    padding:14px 26px;
    border-radius:14px;
    font-weight:700;
    cursor:pointer;
}

.result-card{
    background:#ffffff;
    border-radius:22px;
    padding:24px;
    margin-bottom:20px;
    box-shadow:0 10px 30px rgba(15,23,42,.05);
}

.result-title{
    font-size:20px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.result-meta{
    font-size:13px;
    color:#64748b;
    margin-bottom:18px;
}

.result-content{
    color:#1e293b;
    line-height:1.8;
    font-size:15px;
}

.ai-fragment{
    margin-bottom:12px;
}

.empty-state{
    background:#ffffff;
    padding:30px;
    border-radius:20px;
}

ul{
    padding-left:20px;
}

li{
    margin-bottom:10px;
}

</style>

</head>

<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-title">
        AI Assistant
    </div>

    <div class="page-subtitle">
        Consulta tarifas, ventas, objeciones y documentación IA
    </div>

    <div class="ai-box">

        <form method="POST">

            <textarea
                name="question"
                placeholder="Ejemplo: ¿Qué tarifas sin permanencia tenemos?"
            ><?php echo htmlspecialchars($question); ?></textarea>

            <button
                type="submit"
                class="ask-btn"
            >
                Consultar IA
            </button>

        </form>

    </div>

    <?php echo $response_text; ?>

</div>

</body>
</html>