<?php
session_start();
if(!isset($_SESSION['user_id'])){

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

}

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

$current_page = basename($_SERVER['PHP_SELF']);

$conn->query("
CREATE TABLE IF NOT EXISTS custom_fields (
    id INT AUTO_INCREMENT PRIMARY KEY,
    module_name VARCHAR(100) NOT NULL,
    field_label VARCHAR(255) NOT NULL,
    field_name VARCHAR(255) NOT NULL,
    field_type VARCHAR(50) NOT NULL,
    is_required TINYINT(1) DEFAULT 0,
    allow_files TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

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

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

    $module_name = trim($_POST['module_name']);
    $field_label = trim($_POST['field_label']);
    $field_name = trim($_POST['field_name']);
    $field_type = trim($_POST['field_type']);

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

    if (
        empty($module_name) ||
        empty($field_label) ||
        empty($field_name) ||
        empty($field_type)
    ) {

        $error = "Todos los campos son obligatorios.";

    } else {

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

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

        $stmt->bind_param(
            "ssssii",
            $module_name,
            $field_label,
            $field_name,
            $field_type,
            $is_required,
            $allow_files
        );

        if ($stmt->execute()) {

            $success = "Campo creado correctamente.";

        } else {

            $error = "Error al guardar campo.";

        }
    }
}

$fields = $conn->query("
    SELECT *
    FROM custom_fields
    ORDER BY 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{
    font-size:16px;
    color:#6b7280;
    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);
}

.white-card-title{
    font-size:24px;
    font-weight:700;
    margin-bottom:25px;
    color:#02122c;
}

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

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

.form-group label{
    margin-bottom:10px;
    font-size:14px;
    font-weight:600;
    color:#5f6b7a;
}

.form-control{
    height:52px;
    border:none;
    background:#f3f5fa;
    border-radius:14px;
    padding:0 16px;
    font-size:15px;
}

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

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

.btn-save:hover{
    opacity:.95;
}

.success-box{
    background:#dcfce7;
    color:#166534;
    padding:14px 18px;
    border-radius:12px;
    margin-bottom:20px;
    font-weight:600;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:14px 18px;
    border-radius:12px;
    margin-bottom:20px;
    font-weight:600;
}

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

.crm-table th{
    text-align:left;
    padding:16px;
    font-size:13px;
    text-transform:uppercase;
    color:#7b8190;
    border-bottom:1px solid #edf0f5;
}

.crm-table td{
    padding:18px 16px;
    border-bottom:1px solid #edf0f5;
    color:#02122c;
    font-size:14px;
}

.check-grid{
    display:flex;
    gap:30px;
    margin-top:10px;
    margin-bottom:25px;
}

.check-item{
    display:flex;
    align-items:center;
    gap:10px;
    font-size:14px;
    font-weight:600;
    color:#02122c;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:30px;
    padding:0 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
}

.badge-required{
    background:#fee2e2;
    color:#991b1b;
}

.badge-files{
    background:#dbeafe;
    color:#1d4ed8;
}

.type-badge{
    background:#eef2ff;
    color:#4338ca;
    padding:8px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    display:inline-block;
}

</style>

</head>

<body>

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

<div class="content-area">

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

    <div class="page-subtitle">
        Crea campos dinámicos para contratos, leads y campañas.
    </div>

    <div class="white-card">

        <div class="white-card-title">
            Nuevo campo
        </div>

        <?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">

            <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="contracts">
                            Contratos
                        </option>

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

                        <option value="campaigns">
                            Campañas
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Nombre visible
                    </label>

                    <input
                        type="text"
                        name="field_label"
                        class="form-control"
                        placeholder="Ej: DNI"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>
                        Nombre interno
                    </label>

                    <input
                        type="text"
                        name="field_name"
                        class="form-control"
                        placeholder="Ej: dni"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>
                        Tipo
                    </label>

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

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

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

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

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

                        <option value="textarea">
                            Área de texto
                        </option>

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

                        <option value="image">
                            Imagen (JPG, PNG)
                        </option>

                        <option value="pdf">
                            PDF
                        </option>

                        <option value="audio">
                            Audio (MP3)
                        </option>

                        <option value="document">
                            Documento (DOC, DOCX)
                        </option>

                        <option value="zip">
                            ZIP / RAR
                        </option>

                    </select>

                </div>

            </div>

            <div class="check-grid">

                <label class="check-item">

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

                    Campo obligatorio

                </label>

                <label class="check-item">

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

                    Permitir adjuntos

                </label>

            </div>

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

        </form>

    </div>

    <div class="white-card">

        <div class="white-card-title">
            Campos creados
        </div>

        <table class="crm-table">

            <thead>

                <tr>

                    <th>
                        Módulo
                    </th>

                    <th>
                        Campo
                    </th>

                    <th>
                        Interno
                    </th>

                    <th>
                        Tipo
                    </th>

                    <th>
                        Obligatorio
                    </th>

                    <th>
                        Adjuntos
                    </th>

                </tr>

            </thead>

            <tbody>

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

                    <tr>

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

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

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

                        <td>

                            <span class="type-badge">
                                <?= ucfirst($field['field_type']) ?>
                            </span>

                        </td>

                        <td>

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

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

                            <?php else: ?>

                                No

                            <?php endif; ?>

                        </td>

                        <td>

                            <?php if($field['allow_files']): ?>

                                <span class="badge badge-files">
                                    Permitido
                                </span>

                            <?php else: ?>

                                No

                            <?php endif; ?>

                        </td>

                    </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>