<?php

session_start();

if(!isset($_SESSION['user_id'])){

    header("Location: /login.php");
    exit;

}

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

$parserEngine = new ParserEngine($conn);

$success = "";
$error = "";

/*
|--------------------------------------------------------------------------
| CREAR TABLA SI NO EXISTE
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS knowledge_base (

    id INT AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255) NOT NULL,

    campaign_id INT NULL,

    category VARCHAR(100) NULL,

    description TEXT NULL,

    file_name VARCHAR(255) NULL,

    file_path TEXT NULL,

    file_type VARCHAR(50) NULL,

    uploaded_by INT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)
");

/*
|--------------------------------------------------------------------------
| SUBIR ARCHIVO
|--------------------------------------------------------------------------
*/

if(
    $_SERVER['REQUEST_METHOD'] === 'POST'
    &&
    isset($_POST['upload_knowledge'])
){

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

    $campaign_id =
    intval($_POST['campaign_id']);

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

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

    if(
        empty($title)
        ||
        !isset($_FILES['knowledge_file'])
    ){

        $error =
        "Completa todos los campos.";

    } else {

        $allowed = [

            'pdf',
            'xlsx',
            'xls',
            'csv',
            'docx'

        ];

        $file_name =
        $_FILES['knowledge_file']['name'];

        $tmp =
        $_FILES['knowledge_file']['tmp_name'];

        $ext =
        strtolower(
            pathinfo(
                $file_name,
                PATHINFO_EXTENSION
            )
        );

        if(!in_array($ext, $allowed)){

            $error =
            "Formato no permitido.";

        } else {

            $new_name =
            time() . "_" .
            preg_replace(
                '/[^A-Za-z0-9_\-\.]/',
                '_',
                $file_name
            );

            $upload_path =
            "../uploads/knowledge/" . $new_name;

            if(
                move_uploaded_file(
                    $tmp,
                    $upload_path
                )
            ){

                $relative_path =
                "/uploads/knowledge/" . $new_name;

                $stmt =
                $conn->prepare("
                INSERT INTO knowledge_base
                (
                    title,
                    campaign_id,
                    category,
                    description,
                    file_name,
                    file_path,
                    file_type,
                    uploaded_by
                )
                VALUES
                (
                    ?, ?, ?, ?, ?, ?, ?, ?
                )
                ");

                $user_id =
                $_SESSION['user_id'];

                $stmt->bind_param(
                    "sisssssi",
                    $title,
                    $campaign_id,
                    $category,
                    $description,
                    $file_name,
                    $relative_path,
                    $ext,
                    $user_id
                );

                if($stmt->execute()){

    $knowledge_id =
    $stmt->insert_id;

    /*
    |------------------------------------------
    | EXTRAER TEXTO IA
    |------------------------------------------
    */

    $full_path =
    $_SERVER['DOCUMENT_ROOT'] .
    $relative_path;

    $extractedText =
    $parserEngine->extractText($full_path);

    if(!empty($extractedText)){

        $parserEngine->saveKnowledgeText(
            $knowledge_id,
            $extractedText
        );

    }

    $success =
    "Archivo subido y procesado correctamente.";

} else {

    $error =
    "Error guardando archivo.";

}

            } else {

                $error =
                "No se pudo subir el archivo.";

            }

        }

    }

}

/*
|--------------------------------------------------------------------------
| ELIMINAR
|--------------------------------------------------------------------------
*/

if(isset($_GET['delete'])){

    $delete_id =
    intval($_GET['delete']);

    $query =
    $conn->query("
    SELECT *
    FROM knowledge_base
    WHERE id = '$delete_id'
    LIMIT 1
    ");

    if($query && $query->num_rows > 0){

        $file =
        $query->fetch_assoc();

        $physical =
        "../" . ltrim(
            $file['file_path'],
            '/'
        );

        if(file_exists($physical)){

            unlink($physical);

        }

        $conn->query("
        DELETE FROM knowledge_base
        WHERE id = '$delete_id'
        ");

    }

    header("Location: settings_knowledge.php");
    exit;

}

/*
|--------------------------------------------------------------------------
| CAMPAÑAS
|--------------------------------------------------------------------------
*/

$campaigns =
$conn->query("
SELECT *
FROM campaigns
ORDER BY campaign_name ASC
");

/*
|--------------------------------------------------------------------------
| DOCUMENTOS
|--------------------------------------------------------------------------
*/

$docs =
$conn->query("
SELECT kb.*, campaigns.campaign_name
FROM knowledge_base kb

LEFT JOIN campaigns
ON campaigns.id = kb.campaign_id

ORDER BY kb.id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Knowledge Base
</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:30px;
}

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

.form-grid{
    display:grid;
    grid-template-columns:
    repeat(auto-fit,minmax(280px,1fr));
    gap:20px;
}

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:10px;
    font-size:14px;
    font-weight:700;
    color:#475569;
}

.form-control{
    height:54px;
    border:none;
    border-radius:16px;
    background:#f1f5f9;
    padding:0 18px;
    font-size:15px;
}

textarea.form-control{
    height:120px;
    padding-top:15px;
    resize:none;
}

.btn-save{
    margin-top:25px;
    height:54px;
    border:none;
    border-radius:16px;
    padding:0 28px;
    background:linear-gradient(
        90deg,
        #5b4bff,
        #7b61ff
    );
    color:#ffffff;
    font-weight:700;
    cursor:pointer;
}

.success-box{
    background:#dcfce7;
    color:#166534;
    padding:15px;
    border-radius:14px;
    margin-bottom:20px;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:15px;
    border-radius:14px;
    margin-bottom:20px;
}

.crm-table{
    width:100%;
    border-collapse:collapse;
}

.crm-table th{
    text-align:left;
    padding:16px;
    border-bottom:1px solid #e2e8f0;
}

.crm-table td{
    padding:16px;
    border-bottom:1px solid #e2e8f0;
}

.delete-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:10px 14px;
    border-radius:12px;
    background:#fee2e2;
    color:#991b1b;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

.back-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:46px;
    padding:0 18px;
    border-radius:14px;
    background:#e2e8f0;
    color:#02122c;
    text-decoration:none;
    font-size:14px;
    font-weight:700;
    margin-bottom:25px;
}

</style>

</head>

<body>

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

<div class="content-area">

<a
href="/pages/settings.php"
class="back-btn"
>
← Volver
</a>

<div class="page-title">
Knowledge Base IA
</div>

<div class="page-subtitle">
Documentación inteligente para campañas y entrenamiento
</div>

<div class="white-card">

<?php if($success): ?>

<div class="success-box">
<?= $success ?>
</div>

<?php endif; ?>

<?php if($error): ?>

<div class="error-box">
<?= $error ?>
</div>

<?php endif; ?>

<form
method="POST"
enctype="multipart/form-data"
>

<input
type="hidden"
name="upload_knowledge"
value="1"
>

<div class="form-grid">

<div class="form-group">

<label>
Título
</label>

<input
type="text"
name="title"
class="form-control"
required
>

</div>

<div class="form-group">

<label>
Campaña
</label>

<select
name="campaign_id"
class="form-control"
>

<option value="0">
General
</option>

<?php while($campaign = $campaigns->fetch_assoc()): ?>

<option value="<?= $campaign['id'] ?>">

<?= htmlspecialchars(
$campaign['campaign_name']
) ?>

</option>

<?php endwhile; ?>

</select>

</div>

<div class="form-group">

<label>
Categoría
</label>

<select
name="category"
class="form-control"
>

<option value="Tarifas">
Tarifas
</option>

<option value="Ventas">
Ventas
</option>

<option value="Formacion">
Formación
</option>

<option value="Scripts">
Scripts
</option>

<option value="Objeciones">
Objeciones
</option>

<option value="FAQs">
FAQs
</option>

<option value="Promociones">
Promociones
</option>

<option value="General">
General
</option>

</select>

</div>

<div class="form-group">

<label>
Archivo
</label>

<input
type="file"
name="knowledge_file"
class="form-control"
required
>

</div>

</div>

<div class="form-group" style="margin-top:20px;">

<label>
Descripción
</label>

<textarea
name="description"
class="form-control"
></textarea>

</div>

<button
type="submit"
class="btn-save"
>
Subir documento
</button>

</form>

</div>

<div class="white-card">

<h3 style="margin-bottom:25px;">
Documentos subidos
</h3>

<table class="crm-table">

<thead>

<tr>

<th>ID</th>
<th>Título</th>
<th>Campaña</th>
<th>Categoría</th>
<th>Tipo</th>
<th>Fecha</th>
<th>Acciones</th>

</tr>

</thead>

<tbody>

<?php while($doc = $docs->fetch_assoc()): ?>

<tr>

<td>
<?= $doc['id'] ?>
</td>

<td>
<?= htmlspecialchars($doc['title']) ?>
</td>

<td>
<?= htmlspecialchars(
$doc['campaign_name'] ?? 'General'
) ?>
</td>

<td>
<?= htmlspecialchars($doc['category']) ?>
</td>

<td>
<?= strtoupper($doc['file_type']) ?>
</td>

<td>
<?= $doc['created_at'] ?>
</td>

<td>

<a
href="?delete=<?= $doc['id'] ?>"
class="delete-btn"
onclick="return confirm('¿Eliminar documento?')"
>
Eliminar
</a>

</td>

</tr>

<?php endwhile; ?>

</tbody>

</table>

</div>

</div>

</body>
</html>