<?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,
    campaign_id INT NULL,
    module_name VARCHAR(100),
    field_label VARCHAR(255),
    field_name VARCHAR(255),
    field_type VARCHAR(100),
    is_required TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

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

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

    $campaign_ids =
    isset($_POST['campaign_ids'])
    ? $_POST['campaign_ids']
    : [];

    $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 =
    intval($_POST['is_required']);

    if(
        count($campaign_ids) > 0 &&
        $field_label != '' &&
        $field_name != ''
    ){

        foreach($campaign_ids as $campaign_id){

            $campaign_id =
            intval($campaign_id);

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

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

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

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

                $stmt->execute();

            }

        }

        $success =
        "Campo creado correctamente.";

    }

}

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

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

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

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

    header("Location: settings_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;
    margin-bottom:10px;
    color:#02122c;
}

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

.white-card{
    background:#fff;
    padding:30px;
    border-radius:24px;
    margin-bottom:30px;
    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-control{
    height:54px;
    border:none;
    background:#f1f5f9;
    border-radius:16px;
    padding:0 16px;
    font-size:15px;
}

.btn-save{
    margin-top:20px;
    height:52px;
    border:none;
    border-radius:16px;
    background:#5b4bff;
    color:#fff;
    padding:0 24px;
    cursor:pointer;
    font-weight:700;
}

.field-card{
    padding:20px;
    background:#f8fafc;
    border-radius:18px;
    margin-bottom:15px;
}

.field-title{
    font-size:17px;
    font-weight:800;
    color:#02122c;
    margin-bottom:8px;
}

.field-meta{
    color:#64748b;
    font-size:14px;
    margin-bottom:4px;
}

.delete-btn{
    display:inline-block;
    margin-top:12px;
    padding:10px 14px;
    background:#fee2e2;
    color:#b91c1c;
    border-radius:12px;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

.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;
}

.campaign-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:12px;
}

.campaign-box{
    display:flex;
    align-items:center;
    gap:10px;
    background:#f8fafc;
    padding:14px;
    border-radius:14px;
    cursor:pointer;
}

.radio-grid{
    display:flex;
    gap:14px;
}

.radio-box{
    display:flex;
    align-items:center;
    gap:8px;
    background:#f8fafc;
    padding:14px 18px;
    border-radius:14px;
    cursor:pointer;
}

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

</style>

</head>

<body>

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

<div class="content-area">

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

<div class="page-subtitle">
Administra campos por campaña
</div>

<?php if($success): ?>

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

<?php endif; ?>

<?php if($error): ?>

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

<?php endif; ?>

<div class="white-card">

<form method="POST">

<div class="form-grid">

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

<label class="form-label">
Campañas
</label>

<div class="campaign-grid">

<?php

$campaigns->data_seek(0);

while($campaign = $campaigns->fetch_assoc()):

?>

<label class="campaign-box">

<input
type="checkbox"
name="campaign_ids[]"
value="<?= $campaign['id'] ?>"
>

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

</label>

<?php endwhile; ?>

</div>

</div>

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

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

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

</select>

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

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

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

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

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

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

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

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

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

</select>

<div>

<label class="form-label">
Campo obligatorio
</label>

<div class="radio-grid">

<label class="radio-box">

<input
type="radio"
name="is_required"
value="1"
>

<span>
Sí
</span>

</label>

<label class="radio-box">

<input
type="radio"
name="is_required"
value="0"
checked
>

<span>
No
</span>

</label>

</div>

</div>

</div>

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

</form>

</div>

<div class="white-card">

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

<div class="field-card">

<div class="field-title">
<?= htmlspecialchars($field['field_label']) ?>
</div>

<div class="field-meta">
Campaña:
<?= htmlspecialchars($field['campaign_name'] ?? '-') ?>
</div>

<div class="field-meta">
Campo:
<?= htmlspecialchars($field['field_name']) ?>
</div>

<div class="field-meta">
Tipo:
<?= htmlspecialchars($field['field_type']) ?>
</div>

<div class="field-meta">
<?= $field['is_required'] ? 'Requerido' : 'Opcional' ?>
</div>

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

</div>

<?php endwhile; ?>

</div>

</div>

</body>
</html>