<?php

session_start();

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

if(!isset($_SESSION['can_manage_campaigns']) || intval($_SESSION['can_manage_campaigns']) !== 1){
    die("No tienes permisos.");
}

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

/*
|--------------------------------------------------------------------------
| TABLAS Y COLUMNAS
|--------------------------------------------------------------------------
*/

$conn->query("CREATE TABLE IF NOT EXISTS campaigns (id INT AUTO_INCREMENT PRIMARY KEY, campaign_name VARCHAR(255) NOT NULL, campaign_status VARCHAR(50) DEFAULT 'Activa', campaign_type VARCHAR(100) NULL, description TEXT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
$conn->query("CREATE TABLE IF NOT EXISTS campaign_statuses (id INT AUTO_INCREMENT PRIMARY KEY, campaign_id INT NOT NULL, status_name VARCHAR(255) NOT NULL, status_color VARCHAR(50) DEFAULT '#5b4bff', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
$conn->query("CREATE TABLE IF NOT EXISTS custom_fields (id INT AUTO_INCREMENT PRIMARY KEY, module_name VARCHAR(100) DEFAULT 'leads', 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, placeholder VARCHAR(255) NULL, tooltip VARCHAR(500) NULL, phone_country VARCHAR(10) DEFAULT 'any', doc_type VARCHAR(50) NULL, regex_pattern VARCHAR(500) NULL, allowed_extensions TEXT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

// Agregar columnas nuevas si no existen
$new_cols = [
    'placeholder'       => "VARCHAR(255) NULL",
    'tooltip'           => "VARCHAR(500) NULL",
    'phone_country'     => "VARCHAR(10) DEFAULT 'any'",
    'doc_type'          => "VARCHAR(50) NULL",
    'regex_pattern'     => "VARCHAR(500) NULL",
    'min_length'        => "INT DEFAULT 0",
    'max_length'        => "INT DEFAULT 0",
    'allowed_extensions'=> "TEXT NULL",
    'show_if'           => "TEXT NULL",
];
foreach($new_cols as $col => $def){
    $chk = $conn->query("SHOW COLUMNS FROM custom_fields LIKE '$col'");
    if($chk && $chk->num_rows == 0) $conn->query("ALTER TABLE custom_fields ADD COLUMN $col $def");
}

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

if(isset($_GET['delete_campaign'])){
    $cid = intval($_GET['delete_campaign']);
    $conn->query("DELETE FROM campaign_statuses WHERE campaign_id='$cid'");
    $conn->query("DELETE FROM custom_fields WHERE campaign_id='$cid'");
    $conn->query("DELETE FROM campaigns WHERE id='$cid'");
    header("Location: settings_campaigns.php"); exit;
}
if(isset($_GET['delete_status'])){
    $conn->query("DELETE FROM campaign_statuses WHERE id='".intval($_GET['delete_status'])."'");
    header("Location: settings_campaigns.php"); exit;
}
if(isset($_GET['delete_field'])){
    $conn->query("DELETE FROM custom_fields WHERE id='".intval($_GET['delete_field'])."'");
    header("Location: settings_campaigns.php"); exit;
}

/*
|--------------------------------------------------------------------------
| CREAR CAMPAÑA
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_campaign'])){
    $name = trim($_POST['campaign_name']);
    $stat = trim($_POST['campaign_status']);
    $type = trim($_POST['campaign_type']);
    $desc = trim($_POST['description']);
    if($name == ""){ $error = "Debes ingresar el nombre."; }
    else {
        $safe = $conn->real_escape_string($name);
        $ex   = $conn->query("SELECT id FROM campaigns WHERE campaign_name='$safe' LIMIT 1");
        if($ex->num_rows > 0){ $error = "La campaña ya existe."; }
        else {
            $s = $conn->prepare("INSERT INTO campaigns (campaign_name,campaign_status,campaign_type,description) VALUES (?,?,?,?)");
            $s->bind_param("ssss",$name,$stat,$type,$desc);
            if($s->execute()){
                $nid = $s->insert_id;
                foreach(['Contrato Nuevo','Contactado','Validación','Aprobado','Rechazado','Cerrado'] as $st){
                    $s2=$conn->prepare("INSERT INTO campaign_statuses (campaign_id,status_name) VALUES (?,?)");
                    $s2->bind_param("is",$nid,$st); $s2->execute();
                }
                $success = "Campaña creada correctamente.";
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| EDITAR CAMPAÑA
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_campaign'])){
    $cid=$intval($_POST['campaign_id']);
    $s=$conn->prepare("UPDATE campaigns SET campaign_name=?,campaign_status=?,campaign_type=?,description=? WHERE id=?");
    $n=trim($_POST['campaign_name']); $st=trim($_POST['campaign_status']); $ty=trim($_POST['campaign_type']); $de=trim($_POST['description']);
    $s->bind_param("ssssi",$n,$st,$ty,$de,$cid); $s->execute();
    $success="Campaña actualizada.";
}

/*
|--------------------------------------------------------------------------
| ESTADOS
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_status'])){
    $cid=intval($_POST['campaign_id']); $sn=trim($_POST['status_name']);
    if($sn==""){$error="Nombre requerido.";}
    else {
        $safe=$conn->real_escape_string($sn);
        $chk=$conn->query("SELECT id FROM campaign_statuses WHERE campaign_id='$cid' AND status_name='$safe' LIMIT 1");
        if($chk->num_rows>0){$error="Ya existe.";}
        else { $s=$conn->prepare("INSERT INTO campaign_statuses (campaign_id,status_name) VALUES (?,?)"); $s->bind_param("is",$cid,$sn); $s->execute(); $success="Estado agregado."; }
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_status'])){
    $sid=intval($_POST['status_id']); $sn=trim($_POST['status_name']);
    if($sn!=""){ $s=$conn->prepare("UPDATE campaign_statuses SET status_name=? WHERE id=?"); $s->bind_param("si",$sn,$sid); $s->execute(); $success="Estado actualizado."; }
}

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

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_field'])){
    $cid      = intval($_POST['campaign_id']);
    $label    = trim($_POST['field_label']);
    $type     = trim($_POST['field_type']);
    $req      = isset($_POST['is_required']) ? intval($_POST['is_required']) : 0;
    $options  = trim($_POST['field_options']   ?? '');
    $placeholder = trim($_POST['placeholder']  ?? '');
    $tooltip  = trim($_POST['tooltip']         ?? '');
    $min_len  = intval($_POST['min_length']    ?? 0);
    $max_len  = intval($_POST['max_length']    ?? 0);
    $phone_country = trim($_POST['phone_country'] ?? 'any');
    $doc_type = trim($_POST['doc_type']        ?? '');
    $regex    = trim($_POST['regex_pattern']   ?? '');
    $ext      = trim($_POST['allowed_extensions'] ?? '');
    $module   = 'leads';

    $show_if_field = intval($_POST['show_if_field'] ?? 0);
    $show_if_value = trim($_POST['show_if_value'] ?? '');
    $show_if = ($show_if_field > 0 && $show_if_value !== '')
        ? json_encode(['field_id' => $show_if_field, 'value' => $show_if_value])
        : null;

    if($label == ""){ $error = "Nombre del campo requerido."; }
    else {
        $fname = strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $label));
        $s = $conn->prepare("INSERT INTO custom_fields (module_name,campaign_id,field_label,field_name,field_type,is_required,field_options,placeholder,tooltip,min_length,max_length,phone_country,doc_type,regex_pattern,allowed_extensions,show_if) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $s->bind_param("sissssissiisssss",$module,$cid,$label,$fname,$type,$req,$options,$placeholder,$tooltip,$min_len,$max_len,$phone_country,$doc_type,$regex,$ext,$show_if);
        $s->execute();
        $success = "Campo agregado.";
    }
}

/*
|--------------------------------------------------------------------------
| EDITAR CAMPO
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_field'])){
    $fid     = intval($_POST['field_id']);
    $label   = trim($_POST['field_label']);
    $type    = trim($_POST['field_type']);
    $req     = intval($_POST['is_required'] ?? 0);
    $options = trim($_POST['field_options'] ?? '');
    $placeholder = trim($_POST['placeholder'] ?? '');
    $tooltip = trim($_POST['tooltip'] ?? '');
    $min_len = intval($_POST['min_length'] ?? 0);
    $max_len = intval($_POST['max_length'] ?? 0);
    $phone_country = trim($_POST['phone_country'] ?? 'any');
    $doc_type = trim($_POST['doc_type'] ?? '');
    $regex   = trim($_POST['regex_pattern'] ?? '');
    $ext     = trim($_POST['allowed_extensions'] ?? '');
    $show_if_field = intval($_POST['show_if_field'] ?? 0);
    $show_if_value = trim($_POST['show_if_value'] ?? '');
    $show_if = ($show_if_field > 0 && $show_if_value !== '')
        ? json_encode(['field_id' => $show_if_field, 'value' => $show_if_value])
        : null;

    $s = $conn->prepare("UPDATE custom_fields SET field_label=?,field_type=?,is_required=?,field_options=?,placeholder=?,tooltip=?,min_length=?,max_length=?,phone_country=?,doc_type=?,regex_pattern=?,allowed_extensions=?,show_if=? WHERE id=?");
    $s->bind_param("ssisssiisissssi",$label,$type,$req,$options,$placeholder,$tooltip,$min_len,$max_len,$phone_country,$doc_type,$regex,$ext,$show_if,$fid);
    $s->execute();
    $success = "Campo actualizado.";
}

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

// Países para validación de teléfono
$phone_countries = [
    'any' => 'Cualquier formato',
    'CO'  => 'Colombia (+57, 10 dígitos)',
    'ES'  => 'España (+34, 9 dígitos)',
    'MX'  => 'México (+52, 10 dígitos)',
    'US'  => 'USA/Canadá (+1, 10 dígitos)',
    'AR'  => 'Argentina (+54)',
    'CL'  => 'Chile (+56)',
    'PE'  => 'Perú (+51)',
    'VE'  => 'Venezuela (+58)',
    'custom' => 'Personalizado (regex)',
];

$doc_types = [
    ''    => 'Sin validación',
    'CC'  => 'Cédula Ciudadanía (Colombia)',
    'NIT' => 'NIT (Colombia)',
    'TI'  => 'Tarjeta de Identidad (Colombia)',
    'CE'  => 'Cédula Extranjería (Colombia)',
    'DNI' => 'DNI (España)',
    'NIE' => 'NIE (España)',
    'CIF' => 'CIF (España)',
    'PASSPORT' => 'Pasaporte',
    'RUT' => 'RUT (Chile)',
    'RFC' => 'RFC (México)',
    'CURP'=> 'CURP (México)',
];

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Campañas</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:#fff; 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(240px,1fr)); gap:18px; }
.form-control{ width:100%; height:52px; border:none; background:#f1f5f9; border-radius:14px; padding:0 16px; font-size:14px; box-sizing:border-box; }
textarea.form-control{ height:80px; padding-top:12px; }
.btn-save{ margin-top:18px; height:50px; border:none; border-radius:14px; background:linear-gradient(90deg,#5b4bff,#7b61ff); color:#fff; padding:0 24px; font-size:14px; font-weight:700; cursor:pointer; }
.success-box{ background:#dcfce7; color:#166534; padding:14px; border-radius:12px; margin-bottom:20px; font-weight:700; }
.error-box{ background:#fee2e2; color:#991b1b; padding:14px; border-radius:12px; margin-bottom:20px; font-weight:700; }
.campaign-item{ background:#f8fafc; border-radius:20px; padding:24px; margin-bottom:20px; }
.campaign-name{ font-size:19px; font-weight:800; color:#02122c; }
.section-label{ font-size:12px; font-weight:700; color:#475569; text-transform:uppercase; letter-spacing:.5px; margin:18px 0 10px; }
.status-row{ display:flex; gap:8px; align-items:center; margin-bottom:8px; }
.status-input{ flex:1; height:42px; border:none; background:#fff; border-radius:12px; padding:0 12px; font-size:14px; }
.small-btn{ height:42px; border:none; border-radius:12px; padding:0 14px; font-weight:700; cursor:pointer; font-size:13px; white-space:nowrap; }
.btn-blue{ background:#dbeafe; color:#1d4ed8; }
.btn-red{ background:#fee2e2; color:#b91c1c; text-decoration:none; display:inline-flex; align-items:center; }
.btn-green{ background:#dcfce7; color:#166534; }
.btn-gray{ background:#e2e8f0; color:#02122c; }
.divider{ margin:20px 0; border:none; border-top:2px solid #e2e8f0; }
.field-card{ background:#fff; border-radius:14px; padding:16px; margin-bottom:10px; }
.field-header{ display:flex; justify-content:space-between; align-items:center; }
.field-name{ font-size:14px; font-weight:700; color:#02122c; }
.field-meta{ font-size:12px; color:#64748b; margin-top:4px; }
.badge{ display:inline-flex; align-items:center; height:24px; padding:0 10px; border-radius:20px; font-size:11px; font-weight:700; margin-left:6px; }
.badge-type{ background:#ede9fe; color:#5b4bff; }
.badge-req{ background:#fee2e2; color:#dc2626; }
.badge-country{ background:#dcfce7; color:#166534; }
.badge-doc{ background:#fef3c7; color:#92400e; }
.add-field-box{ background:#fff; border-radius:14px; padding:18px; margin-top:14px; border:2px dashed #e2e8f0; }
.add-field-box:hover{ border-color:#5b4bff; }
.field-form-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:12px; }
.fi{ display:flex; flex-direction:column; gap:5px; }
.fi label{ font-size:11px; font-weight:700; color:#64748b; text-transform:uppercase; }
.fi input,.fi select,.fi textarea{ height:42px; border:none; background:#f1f5f9; border-radius:10px; padding:0 12px; font-size:13px; width:100%; box-sizing:border-box; }
.fi textarea{ height:70px; padding-top:10px; }
.validation-section{ background:#f0f9ff; border-radius:10px; padding:14px; margin-top:12px; border-left:3px solid #0ea5e9; }
.validation-title{ font-size:12px; font-weight:700; color:#0369a1; margin-bottom:10px; text-transform:uppercase; }
.modal-bg{ display:none; position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:1000; align-items:center; justify-content:center; }
.modal-bg.open{ display:flex; }
.modal{ background:#fff; border-radius:20px; padding:28px; width:600px; max-width:95vw; max-height:85vh; overflow-y:auto; }
.modal-title{ font-size:18px; font-weight:800; color:#02122c; margin-bottom:20px; }
</style>
</head>
<body>

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

<div class="content-area">

<div class="page-title">Campañas</div>
<div class="page-subtitle">Gestión de campañas, pipeline y campos del formulario</div>

<?php if($success): ?><div class="success-box">✓ <?= htmlspecialchars($success) ?></div><?php endif; ?>
<?php if($error):   ?><div class="error-box">✗ <?= htmlspecialchars($error) ?></div><?php endif; ?>

<!-- NUEVA CAMPAÑA -->
<div class="white-card">
    <div style="font-size:17px;font-weight:800;color:#02122c;margin-bottom:18px">+ Nueva campaña</div>
    <form method="POST">
        <input type="hidden" name="create_campaign" value="1">
        <div class="form-grid">
            <input type="text" name="campaign_name" class="form-control" placeholder="Nombre de la campaña" required>
            <select name="campaign_status" class="form-control">
                <option value="Activa">Activa</option>
                <option value="Pausada">Pausada</option>
                <option value="Finalizada">Finalizada</option>
            </select>
            <input type="text" name="campaign_type" class="form-control" placeholder="Tipo (Energía, Seguros...)">
            <textarea name="description" class="form-control" placeholder="Descripción"></textarea>
        </div>
        <button type="submit" class="btn-save">Crear campaña</button>
    </form>
</div>

<!-- CAMPAÑAS -->
<?php while($camp = $campaigns->fetch_assoc()):
    $cid      = intval($camp['id']);
    $statuses = $conn->query("SELECT * FROM campaign_statuses WHERE campaign_id='$cid' ORDER BY id ASC");
    $fields   = $conn->query("SELECT * FROM custom_fields WHERE campaign_id='$cid' AND module_name='leads' ORDER BY field_order ASC, id ASC");
    $fields_arr = [];
    while($f = $fields->fetch_assoc()) $fields_arr[] = $f;
?>

<div class="campaign-item">

    <!-- HEADER -->
    <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:12px">
        <div>
            <div class="campaign-name"><?= htmlspecialchars($camp['campaign_name']) ?></div>
            <div style="font-size:13px;color:#64748b;margin-top:4px">
                <?= htmlspecialchars($camp['campaign_status']) ?>
                <?php if($camp['campaign_type']): ?> · <?= htmlspecialchars($camp['campaign_type']) ?><?php endif; ?>
                · <?= count($fields_arr) ?> campos · <?= $statuses->num_rows ?> etapas
            </div>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="small-btn btn-gray" onclick="toggle('edit_camp_<?= $cid ?>')">✏ Editar</button>
            <a href="?delete_campaign=<?= $cid ?>" class="small-btn btn-red" onclick="return confirm('¿Eliminar campaña completa?')">🗑 Eliminar</a>
        </div>
    </div>

    <!-- EDITAR CAMPAÑA -->
    <div id="edit_camp_<?= $cid ?>" style="display:none;background:#fff;border-radius:14px;padding:18px;margin-top:14px">
        <form method="POST">
            <input type="hidden" name="edit_campaign" value="1">
            <input type="hidden" name="campaign_id" value="<?= $cid ?>">
            <div class="form-grid">
                <input type="text" name="campaign_name" class="form-control" value="<?= htmlspecialchars($camp['campaign_name']) ?>" required>
                <select name="campaign_status" class="form-control">
                    <option value="Activa" <?= $camp['campaign_status']=='Activa'?'selected':'' ?>>Activa</option>
                    <option value="Pausada" <?= $camp['campaign_status']=='Pausada'?'selected':'' ?>>Pausada</option>
                    <option value="Finalizada" <?= $camp['campaign_status']=='Finalizada'?'selected':'' ?>>Finalizada</option>
                </select>
                <input type="text" name="campaign_type" class="form-control" value="<?= htmlspecialchars($camp['campaign_type'] ?? '') ?>">
                <textarea name="description" class="form-control"><?= htmlspecialchars($camp['description'] ?? '') ?></textarea>
            </div>
            <button type="submit" class="small-btn btn-green" style="margin-top:12px">Guardar</button>
        </form>
    </div>

    <!-- ESTADOS PIPELINE -->
    <div class="section-label">📊 Etapas del pipeline</div>

    <?php
    // Reset statuses query
    $statuses = $conn->query("SELECT * FROM campaign_statuses WHERE campaign_id='$cid' ORDER BY id ASC");
    while($st = $statuses->fetch_assoc()):
    ?>
    <form method="POST" class="status-row">
        <input type="hidden" name="edit_status" value="1">
        <input type="hidden" name="status_id" value="<?= $st['id'] ?>">
        <input type="text" name="status_name" class="status-input" value="<?= htmlspecialchars($st['status_name']) ?>" required>
        <button type="submit" class="small-btn btn-blue">Guardar</button>
        <a href="?delete_status=<?= $st['id'] ?>" class="small-btn btn-red" onclick="return confirm('¿Eliminar?')">✕</a>
    </form>
    <?php endwhile; ?>

    <form method="POST" class="status-row" style="margin-top:8px">
        <input type="hidden" name="create_status" value="1">
        <input type="hidden" name="campaign_id" value="<?= $cid ?>">
        <input type="text" name="status_name" class="status-input" placeholder="+ Nueva etapa" required>
        <button type="submit" class="small-btn btn-green">Agregar</button>
    </form>

    <hr class="divider">

    <!-- CAMPOS PERSONALIZADOS -->
    <div class="section-label">📋 Campos del formulario de leads</div>
    <div style="font-size:13px;color:#64748b;margin-bottom:12px">Aparecen al crear o editar un lead de esta campaña</div>

    <?php foreach($fields_arr as $f): ?>
    <div class="field-card">
        <div class="field-header">
            <div>
                <span class="field-name"><?= htmlspecialchars($f['field_label']) ?></span>
                <span class="badge badge-type"><?= $f['field_type'] ?></span>
                <?php if($f['is_required']): ?><span class="badge badge-req">Requerido</span><?php endif; ?>
                <?php if(!empty($f['phone_country']) && $f['phone_country'] != 'any'): ?><span class="badge badge-country">📞 <?= $f['phone_country'] ?></span><?php endif; ?>
                <?php if(!empty($f['doc_type'])): ?><span class="badge badge-doc">🪪 <?= $f['doc_type'] ?></span><?php endif; ?>
            </div>
            <div style="display:flex;gap:8px">
                <button class="small-btn btn-blue" onclick="openEdit(<?= htmlspecialchars(json_encode($f)) ?>)">Editar</button>
                <a href="?delete_field=<?= $f['id'] ?>" class="small-btn btn-red" onclick="return confirm('¿Eliminar campo?')">✕</a>
            </div>
        </div>
        <?php if(!empty($f['field_options'])): ?>
        <div class="field-meta">Opciones: <?= htmlspecialchars(str_replace("\n", ' · ', $f['field_options'])) ?></div>
        <?php endif; ?>
        <?php if($f['min_length'] > 0 || $f['max_length'] > 0): ?>
        <div class="field-meta">Longitud: <?= $f['min_length'] ?>–<?= $f['max_length'] ?> caracteres</div>
        <?php endif; ?>
        <?php if(!empty($f['placeholder'])): ?>
        <div class="field-meta">Placeholder: "<?= htmlspecialchars($f['placeholder']) ?>"</div>
        <?php endif; ?>
        <?php if(!empty($f['show_if'])): 
            $cond = json_decode($f['show_if'], true);
            $dep_field = array_values(array_filter($fields_arr, fn($x) => $x['id'] == ($cond['field_id']??0)));
        ?>
        <div class="field-meta" style="color:#92400e">⚡ Solo visible cuando <strong><?= htmlspecialchars($dep_field[0]['field_label'] ?? 'campo') ?></strong> = "<?= htmlspecialchars($cond['value'] ?? '') ?>"</div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>

    <?php if(empty($fields_arr)): ?>
    <div style="color:#94a3b8;font-size:14px;padding:10px 0">Sin campos configurados.</div>
    <?php endif; ?>

    <!-- AGREGAR CAMPO -->
    <div class="add-field-box">
        <div style="font-size:14px;font-weight:700;color:#02122c;margin-bottom:14px">+ Agregar campo</div>
        <form method="POST" id="addForm_<?= $cid ?>">
            <input type="hidden" name="create_field" value="1">
            <input type="hidden" name="campaign_id" value="<?= $cid ?>">

            <div class="field-form-grid">
                <div class="fi">
                    <label>Nombre del campo *</label>
                    <input type="text" name="field_label" placeholder="Ej: Número de contrato" required>
                </div>
                <div class="fi">
                    <label>Tipo de campo</label>
                    <select name="field_type" onchange="onTypeChange(this, <?= $cid ?>)">
                        <option value="text">Texto libre</option>
                        <option value="tel">Teléfono</option>
                        <option value="document">Documento / ID</option>
                        <option value="select">Opciones (select)</option>
                        <option value="number">Número</option>
                        <option value="date">Fecha</option>
                        <option value="email">Email</option>
                        <option value="textarea">Texto largo</option>
                        <option value="file">Archivo</option>
                    </select>
                </div>
                <div class="fi">
                    <label>¿Requerido?</label>
                    <select name="is_required">
                        <option value="0">No</option>
                        <option value="1">Sí</option>
                    </select>
                </div>
                <div class="fi">
                    <label>Placeholder</label>
                    <input type="text" name="placeholder" placeholder="Texto de ayuda">
                </div>
                <div class="fi">
                    <label>Tooltip / Instrucción</label>
                    <input type="text" name="tooltip" placeholder="Ej: Ingresa solo números">
                </div>
            </div>

            <!-- VALIDACIONES DINÁMICAS -->
            <div id="val_tel_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">📞 Validación de teléfono</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>País</label>
                        <select name="phone_country">
                            <?php foreach($phone_countries as $k => $v): ?>
                            <option value="<?= $k ?>"><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fi">
                        <label>Mín. dígitos</label>
                        <input type="number" name="min_length" value="7" min="0">
                    </div>
                    <div class="fi">
                        <label>Máx. dígitos</label>
                        <input type="number" name="max_length" value="15" min="0">
                    </div>
                    <div class="fi" id="val_tel_regex_<?= $cid ?>" style="display:none">
                        <label>Patrón (regex)</label>
                        <input type="text" name="regex_pattern" placeholder="^\+?[0-9]{10}$">
                    </div>
                </div>
            </div>

            <div id="val_doc_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">🪪 Validación de documento</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>Tipo de documento</label>
                        <select name="doc_type">
                            <?php foreach($doc_types as $k => $v): ?>
                            <option value="<?= $k ?>"><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fi">
                        <label>Mín. caracteres</label>
                        <input type="number" name="min_length" value="6" min="0">
                    </div>
                    <div class="fi">
                        <label>Máx. caracteres</label>
                        <input type="number" name="max_length" value="20" min="0">
                    </div>
                </div>
            </div>

            <div id="val_text_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">✏ Validación de texto</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>Mín. caracteres</label>
                        <input type="number" name="min_length" value="0" min="0">
                    </div>
                    <div class="fi">
                        <label>Máx. caracteres</label>
                        <input type="number" name="max_length" value="0" min="0" placeholder="0 = sin límite">
                    </div>
                    <div class="fi">
                        <label>Patrón regex (opcional)</label>
                        <input type="text" name="regex_pattern" placeholder="Ej: ^[A-Za-z ]+$">
                    </div>
                </div>
            </div>

            <div id="val_num_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">🔢 Validación de número</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>Valor mínimo</label>
                        <input type="number" name="min_length" value="0">
                    </div>
                    <div class="fi">
                        <label>Valor máximo</label>
                        <input type="number" name="max_length" value="0" placeholder="0 = sin límite">
                    </div>
                </div>
            </div>

            <div id="val_select_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">📋 Opciones del select</div>
                <div class="fi">
                    <label>Una opción por línea</label>
                    <textarea name="field_options" style="height:90px" placeholder="Opción 1&#10;Opción 2&#10;Opción 3"></textarea>
                </div>
            </div>

            <div id="val_file_<?= $cid ?>" style="display:none" class="validation-section">
                <div class="validation-title">📎 Validación de archivo</div>
                <div class="fi">
                    <label>Extensiones permitidas (separadas por coma)</label>
                    <input type="text" name="allowed_extensions" placeholder="pdf,jpg,png,docx">
                </div>
            </div>

            <!-- CAMPO CONDICIONAL -->
            <div class="validation-section" style="background:#fef9c3;border-left-color:#f59e0b">
                <div class="validation-title" style="color:#92400e">⚡ Mostrar solo si otro campo tiene cierto valor (opcional)</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>Depende del campo</label>
                        <select name="show_if_field" id="cond_field_<?= $cid ?>">
                            <option value="0">Siempre visible</option>
                            <?php foreach($fields_arr as $fopt): ?>
                            <?php if($fopt['field_type'] === 'select'): ?>
                            <option value="<?= $fopt['id'] ?>"><?= htmlspecialchars($fopt['field_label']) ?></option>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fi">
                        <label>Cuando su valor sea</label>
                        <input type="text" name="show_if_value" placeholder="Ej: Empresa" id="cond_val_<?= $cid ?>">
                    </div>
                </div>
            </div>

            <button type="submit" class="small-btn btn-green" style="margin-top:14px">+ Agregar campo</button>
        </form>
    </div>

</div>

<?php endwhile; ?>
</div>

<!-- MODAL EDITAR CAMPO -->
<div class="modal-bg" id="editModal">
    <div class="modal">
        <div class="modal-title">Editar campo</div>
        <form method="POST">
            <input type="hidden" name="edit_field" value="1">
            <input type="hidden" name="field_id" id="m_id">

            <div class="field-form-grid" style="margin-bottom:14px">
                <div class="fi">
                    <label>Nombre *</label>
                    <input type="text" name="field_label" id="m_label" required>
                </div>
                <div class="fi">
                    <label>Tipo</label>
                    <select name="field_type" id="m_type" onchange="modalTypeChange(this)">
                        <option value="text">Texto libre</option>
                        <option value="tel">Teléfono</option>
                        <option value="document">Documento / ID</option>
                        <option value="select">Opciones (select)</option>
                        <option value="number">Número</option>
                        <option value="date">Fecha</option>
                        <option value="email">Email</option>
                        <option value="textarea">Texto largo</option>
                        <option value="file">Archivo</option>
                    </select>
                </div>
                <div class="fi">
                    <label>¿Requerido?</label>
                    <select name="is_required" id="m_req">
                        <option value="0">No</option>
                        <option value="1">Sí</option>
                    </select>
                </div>
                <div class="fi">
                    <label>Placeholder</label>
                    <input type="text" name="placeholder" id="m_placeholder">
                </div>
                <div class="fi">
                    <label>Tooltip</label>
                    <input type="text" name="tooltip" id="m_tooltip">
                </div>
            </div>

            <!-- Validaciones modal -->
            <div id="m_val_tel" style="display:none" class="validation-section">
                <div class="validation-title">📞 Validación teléfono</div>
                <div class="field-form-grid">
                    <div class="fi"><label>País</label>
                        <select name="phone_country" id="m_phone_country">
                            <?php foreach($phone_countries as $k => $v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fi"><label>Mín.</label><input type="number" name="min_length" id="m_min" value="7"></div>
                    <div class="fi"><label>Máx.</label><input type="number" name="max_length" id="m_max" value="15"></div>
                </div>
            </div>

            <div id="m_val_doc" style="display:none" class="validation-section">
                <div class="validation-title">🪪 Validación documento</div>
                <div class="field-form-grid">
                    <div class="fi"><label>Tipo</label>
                        <select name="doc_type" id="m_doc_type">
                            <?php foreach($doc_types as $k => $v): ?><option value="<?= $k ?>"><?= $v ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fi"><label>Mín.</label><input type="number" name="min_length" id="m_min2" value="6"></div>
                    <div class="fi"><label>Máx.</label><input type="number" name="max_length" id="m_max2" value="20"></div>
                </div>
            </div>

            <div id="m_val_text" style="display:none" class="validation-section">
                <div class="validation-title">✏ Validación texto</div>
                <div class="field-form-grid">
                    <div class="fi"><label>Mín.</label><input type="number" name="min_length" id="m_min3" value="0"></div>
                    <div class="fi"><label>Máx.</label><input type="number" name="max_length" id="m_max3" value="0"></div>
                    <div class="fi"><label>Regex</label><input type="text" name="regex_pattern" id="m_regex"></div>
                </div>
            </div>

            <div id="m_val_select" style="display:none" class="validation-section">
                <div class="validation-title">📋 Opciones</div>
                <div class="fi"><label>Una por línea</label><textarea name="field_options" id="m_options" style="height:90px"></textarea></div>
            </div>

            <div id="m_val_num" style="display:none" class="validation-section">
                <div class="validation-title">🔢 Número</div>
                <div class="field-form-grid">
                    <div class="fi"><label>Mín.</label><input type="number" name="min_length" id="m_min4" value="0"></div>
                    <div class="fi"><label>Máx.</label><input type="number" name="max_length" id="m_max4" value="0"></div>
                </div>
            </div>

            <div id="m_val_file" style="display:none" class="validation-section">
                <div class="validation-title">📎 Archivo</div>
                <div class="fi"><label>Extensiones</label><input type="text" name="allowed_extensions" id="m_ext" placeholder="pdf,jpg,png"></div>
            </div>

            <!-- Condicional -->
            <div class="validation-section" style="background:#fef9c3;border-left-color:#f59e0b;margin-top:14px">
                <div class="validation-title" style="color:#92400e">⚡ Mostrar solo si (opcional)</div>
                <div class="field-form-grid">
                    <div class="fi">
                        <label>Campo condicional (ID)</label>
                        <input type="number" name="show_if_field" id="m_show_if_field" placeholder="ID del campo select">
                    </div>
                    <div class="fi">
                        <label>Cuando el valor sea</label>
                        <input type="text" name="show_if_value" id="m_show_if_value" placeholder="Ej: Empresa">
                    </div>
                </div>
            </div>

            <div style="display:flex;gap:10px;margin-top:20px">
                <button type="submit" class="btn-save" style="margin-top:0">Guardar</button>
                <button type="button" class="small-btn btn-gray" onclick="closeModal()">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<script>
function toggle(id){ const el=document.getElementById(id); el.style.display=el.style.display==='none'?'block':'none'; }

const valSections = ['tel','doc','text','num','select','file'];

function onTypeChange(sel, cid){
    valSections.forEach(s => {
        const el = document.getElementById('val_'+s+'_'+cid);
        if(el) el.style.display = 'none';
    });
    const type = sel.value;
    if(type==='tel')      { const el=document.getElementById('val_tel_'+cid);    if(el) el.style.display='block'; }
    if(type==='document') { const el=document.getElementById('val_doc_'+cid);    if(el) el.style.display='block'; }
    if(type==='text'||type==='textarea') { const el=document.getElementById('val_text_'+cid); if(el) el.style.display='block'; }
    if(type==='number')   { const el=document.getElementById('val_num_'+cid);    if(el) el.style.display='block'; }
    if(type==='select')   { const el=document.getElementById('val_select_'+cid); if(el) el.style.display='block'; }
    if(type==='file')     { const el=document.getElementById('val_file_'+cid);   if(el) el.style.display='block'; }
}

function modalTypeChange(sel){
    ['tel','doc','text','num','select','file'].forEach(s => document.getElementById('m_val_'+s).style.display='none');
    const t = sel.value;
    if(t==='tel')      document.getElementById('m_val_tel').style.display='block';
    if(t==='document') document.getElementById('m_val_doc').style.display='block';
    if(t==='text'||t==='textarea') document.getElementById('m_val_text').style.display='block';
    if(t==='number')   document.getElementById('m_val_num').style.display='block';
    if(t==='select')   document.getElementById('m_val_select').style.display='block';
    if(t==='file')     document.getElementById('m_val_file').style.display='block';
}

function openEdit(f){
    document.getElementById('m_id').value          = f.id;
    document.getElementById('m_label').value       = f.field_label;
    document.getElementById('m_type').value        = f.field_type;
    document.getElementById('m_req').value         = f.is_required;
    document.getElementById('m_placeholder').value = f.placeholder || '';
    document.getElementById('m_tooltip').value     = f.tooltip || '';
    document.getElementById('m_options').value     = f.field_options || '';
    document.getElementById('m_regex').value       = f.regex_pattern || '';
    document.getElementById('m_ext').value         = f.allowed_extensions || '';
    if(f.phone_country) document.getElementById('m_phone_country').value = f.phone_country;
    if(f.doc_type)      document.getElementById('m_doc_type').value = f.doc_type;
    document.getElementById('m_min').value  = f.min_length || 0;
    document.getElementById('m_max').value  = f.max_length || 0;
    document.getElementById('m_min2').value = f.min_length || 0;
    document.getElementById('m_max2').value = f.max_length || 0;
    document.getElementById('m_min3').value = f.min_length || 0;
    document.getElementById('m_max3').value = f.max_length || 0;
    document.getElementById('m_min4').value = f.min_length || 0;
    document.getElementById('m_max4').value = f.max_length || 0;
    modalTypeChange(document.getElementById('m_type'));
    // show_if
    try {
        const si = f.show_if ? JSON.parse(f.show_if) : null;
        document.getElementById('m_show_if_field').value = si ? si.field_id : '';
        document.getElementById('m_show_if_value').value = si ? si.value : '';
    } catch(e) {
        document.getElementById('m_show_if_field').value = '';
        document.getElementById('m_show_if_value').value = '';
    }
    document.getElementById('editModal').classList.add('open');
}

function closeModal(){ document.getElementById('editModal').classList.remove('open'); }
document.getElementById('editModal').addEventListener('click', function(e){ if(e.target===this) closeModal(); });
</script>

</body>
</html>