<?php

session_start();

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

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

/*
|--------------------------------------------------------------------------
| TABLA
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS custom_fields (
    id INT AUTO_INCREMENT PRIMARY KEY,

    module_name VARCHAR(100),

    campaign_id INT NULL,

    field_label VARCHAR(255),

    field_name VARCHAR(255),

    field_type VARCHAR(100) DEFAULT 'text',

    is_required TINYINT(1) DEFAULT 0,

    field_options TEXT NULL,

    field_order INT DEFAULT 0,

    min_length INT DEFAULT 0,

    max_length INT DEFAULT 0,

    allowed_extensions TEXT NULL,

    phone_validation TINYINT(1) DEFAULT 0,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

/*
|--------------------------------------------------------------------------
| VALIDAR NUEVA COLUMNA
|--------------------------------------------------------------------------
*/

$check_options = $conn->query("
SHOW COLUMNS
FROM custom_fields
LIKE 'field_options'
");

if($check_options->num_rows == 0){

    $conn->query("
    ALTER TABLE custom_fields
    ADD COLUMN field_options LONGTEXT NULL
    ");

}

/*
|--------------------------------------------------------------------------
| CREAR CAMPO
|--------------------------------------------------------------------------
*/

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

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

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

    if($campaign_id == 0){

        $campaign_id = null;

    }

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

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

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

    $is_required =
    isset($_POST['is_required'])
    ? 1
    : 0;

    if(
        $module_name == '' ||
        $field_label == ''
    ){

        $error =
        "Completa todos los campos.";

    } else {

        $field_name =
        strtolower($field_label);

        $field_name =
        preg_replace(
            '/[^a-zA-Z0-9]/',
            '_',
            $field_name
        );

        $safe_name =
        $conn->real_escape_string($field_name);

        $exists = $conn->query("
        SELECT id
        FROM custom_fields
        WHERE field_name = '$safe_name'
        AND module_name = '$module_name'
        LIMIT 1
        ");

        if($exists->num_rows > 0){

            $error =
            "Ya existe un campo con ese nombre.";

        } else {

            $stmt = $conn->prepare("
            INSERT INTO custom_fields
            (
                module_name,
                campaign_id,
                field_label,
                field_name,
                field_type,
                field_options,
                is_required
            )
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->bind_param(
                "sissssi",
                $module_name,
                $campaign_id,
                $field_label,
                $field_name,
                $field_type,
                $field_options,
                $is_required
            );

            if($stmt->execute()){

                $success =
                "Campo creado correctamente.";

            } else {

                $error =
                "No se pudo crear el campo.";

            }

        }

    }

}

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

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

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

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

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

}

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

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

/*
|--------------------------------------------------------------------------
| CAMPOS
|--------------------------------------------------------------------------
*/

$fields = $conn->query("
SELECT
    custom_fields.*,
    campaigns.campaign_name
FROM custom_fields

LEFT JOIN campaigns
ON campaigns.id = custom_fields.campaign_id

ORDER BY custom_fields.id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Campos personalizados
</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(250px,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{
    width:100%;
    height:54px;
    border:none;
    background:#f1f5f9;
    border-radius:14px;
    padding:0 16px;
    font-size:15px;
}

textarea.form-control{
    height:120px;
    padding-top:14px;
}

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

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

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

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

.fields-table th{
    background:#f8fafc;
    padding:16px;
    text-align:left;
    font-size:13px;
    color:#475569;
}

.fields-table td{
    padding:16px;
    border-top:1px solid #eef2ff;
    font-size:14px;
    vertical-align:top;
}

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

.required-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 12px;
    border-radius:999px;
    background:#dbeafe;
    color:#1d4ed8;
    font-size:12px;
    font-weight:700;
}

.options-box{
    background:#f8fafc;
    border-radius:12px;
    padding:10px;
    line-height:1.7;
}

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-title">
        Campos personalizados
    </div>

    <div class="page-subtitle">
        Configura campos dinámicos por campañas
    </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">

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

            <div class="form-grid">

                <div class="form-group">

                    <label>
                        Módulo
                    </label>

                    <select
                        name="module_name"
                        class="form-control"
                        required
                    >

                        <option value="">
                            Seleccionar
                        </option>

                        <option value="leads">
                            Leads
                        </option>

                        <option value="contracts">
                            Contratos
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Campaña
                    </label>

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

                        <option value="0">
                            Global
                        </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>
                        Nombre del campo
                    </label>

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

                </div>

                <div class="form-group">

                    <label>
                        Tipo
                    </label>

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

    <option value="text">
        Texto
    </option>

    <option value="number">
        Número
    </option>

    <option value="date">
        Fecha
    </option>

    <option value="email">
        Email
    </option>

    <option value="select">
        Select
    </option>

    <option value="textarea">
        Textarea
    </option>

    <option value="tel">
        Teléfono internacional
    </option>

    <option value="file">
        Archivo
    </option>

</select>

                </div>

                <div class="form-group" style="grid-column:1/-1;">

                    <label>
                        Opciones (solo select)
                    </label>

                    <textarea
                        name="field_options"
                        class="form-control"
                        placeholder="Ejemplo:
Pendiente
Aprobado
Rechazado"
                    ></textarea>
                    <div class="form-grid" style="margin-top:20px;">

    <div class="form-group">

        <label>
            Largo mínimo
        </label>

        <input
            type="number"
            name="min_length"
            class="form-control"
            min="0"
            value="0"
        >

    </div>

    <div class="form-group">

        <label>
            Largo máximo
        </label>

        <input
            type="number"
            name="max_length"
            class="form-control"
            min="0"
            value="0"
        >

    </div>

    <div class="form-group">

        <label>
            Extensiones permitidas
        </label>

        <input
            type="text"
            name="allowed_extensions"
            class="form-control"
            placeholder="jpg,jpeg,png,pdf,docx"
        >

    </div>

</div>

<div
    style="
        margin-top:20px;
        display:flex;
        align-items:center;
        gap:10px;
    "
>

    <input
        type="checkbox"
        name="phone_validation"
        value="1"
    >

    <label style="margin:0;">
        Validar teléfono internacional
    </label>

</div>

                </div>

            </div>

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

                <label style="display:flex;gap:10px;align-items:center;">

                    <input
                        type="checkbox"
                        name="is_required"
                    >

                    Campo obligatorio

                </label>

            </div>

            <button
                type="submit"
                class="btn-save"
            >
                Crear campo
            </button>

        </form>

    </div>

    <div class="white-card">

        <table class="fields-table">

            <thead>

                <tr>

                    <th>ID</th>
                    <th>Módulo</th>
                    <th>Campaña</th>
                    <th>Campo</th>
                    <th>Tipo</th>
                    <th>Opciones</th>
                    <th>Obligatorio</th>
                    <th>Acciones</th>

                </tr>

            </thead>

            <tbody>

                <?php while($field = $fields->fetch_assoc()): ?>

                    <tr>

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

                        <td>
                            <?= htmlspecialchars($field['module_name']) ?>
                        </td>

                        <td>
                            <?= htmlspecialchars(
                                $field['campaign_name']
                                ?? 'Global'
                            ) ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($field['field_label']) ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($field['field_type']) ?>
                        </td>

                        <td>

                            <div class="options-box">

                                <?= nl2br(
                                    htmlspecialchars(
                                        $field['field_options']
                                    )
                                ) ?>

                            </div>

                        </td>

                        <td>

                            <?php if($field['is_required'] == 1): ?>

                                <span class="required-badge">
                                    Sí
                                </span>

                            <?php else: ?>

                                No

                            <?php endif; ?>

                        </td>

                        <td>

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

                        </td>

                    </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>