<?php

session_start();

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

// Crear columnas telefonia si no existen
$conn->query("ALTER TABLE leads ADD COLUMN IF NOT EXISTS in_cartera TINYINT DEFAULT 0");
$conn->query("ALTER TABLE leads ADD COLUMN IF NOT EXISTS extra_data JSON NULL");

include("../includes/hierarchy.php");

/*
|--------------------------------------------------------------------------
| USUARIOS VISIBLES
|--------------------------------------------------------------------------
*/

$visible_users = $_SESSION['user_id'];

if(function_exists('getVisibleUsers')){

    $users_array =
    getVisibleUsers(
        $conn,
        $_SESSION['user_id']
    );

    if(
        is_array($users_array)
        &&
        count($users_array) > 0
    ){

        $visible_users =
        implode(
            ',',
            array_map(
                'intval',
                $users_array
            )
        );

    }

}
requirePermission('can_view_leads');
/*
|--------------------------------------------------------------------------
| VALIDAR LOGIN
|--------------------------------------------------------------------------
*/

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

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

}

/*
|--------------------------------------------------------------------------
| TABLAS
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS leads (
    id INT AUTO_INCREMENT PRIMARY KEY,
    document_type VARCHAR(100),
    document_number VARCHAR(255),
    full_name VARCHAR(255) NOT NULL,
    phone VARCHAR(100),
    email VARCHAR(255),
    campaign_id INT NULL,
    office_id INT NULL,
    advisor_id INT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS campaigns (
    id INT AUTO_INCREMENT PRIMARY KEY,
    campaign_name VARCHAR(255),
    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),
    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,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS lead_custom_values (
    id INT AUTO_INCREMENT PRIMARY KEY,
    lead_id INT,
    field_id INT,
    field_value TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS LEADS
|--------------------------------------------------------------------------
*/

$required_columns = [

    'document_type' => 'VARCHAR(100)',
    'document_number' => 'VARCHAR(255)',
    'full_name' => 'VARCHAR(255)',
    'phone' => 'VARCHAR(100)',
    'email' => 'VARCHAR(255)',
    'campaign_id' => 'INT NULL',
    'office_id' => 'INT NULL',
    'advisor_id' => 'INT NULL'

];

foreach($required_columns as $column => $type){

    $check = $conn->query("
    SHOW COLUMNS
    FROM leads
    LIKE '$column'
    ");

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

        $conn->query("
        ALTER TABLE leads
        ADD COLUMN $column $type
        ");

    }

}

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS CUSTOM_FIELDS
|--------------------------------------------------------------------------
*/

$custom_fields_columns = [

    'field_options' => 'TEXT NULL',
    'field_order' => 'INT DEFAULT 0'

];

foreach($custom_fields_columns as $column => $type){

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

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

        $conn->query("
        ALTER TABLE custom_fields
        ADD COLUMN $column $type
        ");

    }

}

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

/*
|--------------------------------------------------------------------------
| USUARIO ACTUAL
|--------------------------------------------------------------------------
*/

$current_user_id =
intval($_SESSION['user_id']);

$is_backoffice =
isset($_SESSION['role'])
&&
$_SESSION['role'] == 'backoffice';

/*
|--------------------------------------------------------------------------
| CAMPAÑAS DEL USUARIO
|--------------------------------------------------------------------------
*/

$user_campaigns = [];

if(!$is_backoffice){

    $campaignsQuery = $conn->query("
    SELECT campaign_id
    FROM user_campaigns
    WHERE user_id = '$current_user_id'
    ");

    while($uc = $campaignsQuery->fetch_assoc()){

        $user_campaigns[] =
        $uc['campaign_id'];

    }

}

/*
|--------------------------------------------------------------------------
| CAMPAÑA SELECCIONADA
|--------------------------------------------------------------------------
*/

$selected_campaign = 0;

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

    $selected_campaign =
    intval($_GET['campaign_id']);

}

/*
|--------------------------------------------------------------------------
| BUSCADOR
|--------------------------------------------------------------------------
*/

$search = "";

$where_conditions = [];

if($selected_campaign > 0){

    $where_conditions[] =
    "leads.campaign_id = '$selected_campaign'";

}

/*
|--------------------------------------------------------------------------
| FILTRO JERÁRQUICO
|--------------------------------------------------------------------------
*/

// Todos ven solo cartera
$where_conditions[] = "leads.in_cartera = 1";

if(
    !isset($_SESSION['can_manage_users'])
    ||
    $_SESSION['can_manage_users'] != 1
){

    $where_conditions[] =
    "(
        leads.advisor_id IN ($visible_users)
        OR leads.assigned_user_id IN ($visible_users)
    )";

}

if($selected_campaign > 0){

    $where_conditions[] =
    "leads.campaign_id = '$selected_campaign'";

}

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

    $search =
    trim($_GET['search']);

    if($search != ""){

        $safe_search =
        $conn->real_escape_string($search);

        $where_conditions[] = "
        (
            leads.document_number LIKE '%$safe_search%'
            OR leads.full_name LIKE '%$safe_search%'
            OR leads.phone LIKE '%$safe_search%'
        )
        ";

    }

}

$where = "";

if(count($where_conditions) > 0){

    $where =
    "WHERE " . implode(" AND ", $where_conditions);

}

/*
|--------------------------------------------------------------------------
| CREAR LEAD
|--------------------------------------------------------------------------
*/

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

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

    $document_type = '';
$document_number = '';
$full_name = '';
$phone = '';
$email = '';

/*
|--------------------------------------------------------------------------
| TOMAR DATOS DESDE CAMPOS PERSONALIZADOS
|--------------------------------------------------------------------------
*/

$custom_fields_query = $conn->query("
SELECT *
FROM custom_fields
WHERE module_name = 'leads'
AND campaign_id = '$campaign_id'
");

while($cf = $custom_fields_query->fetch_assoc()){

    $field_key =
    'custom_'.$cf['id'];

    $value =
    trim($_POST[$field_key] ?? '');

    $label =
    strtolower(trim($cf['field_label']));

    /*
    |--------------------------------------------------------------------------
    | DETECTAR CAMPOS PRINCIPALES
    |--------------------------------------------------------------------------
    */

    if(
    strpos($label,'nombre') !== false
    ||
    strpos($label,'apellidos') !== false
){

    if(empty($full_name)){

        $full_name = $value;

    }

}

if(
    strpos($label,'telefono') !== false
    ||
    strpos($label,'teléfono') !== false
    ||
    strpos($label,'celular') !== false
    ||
    strpos($label,'movil') !== false
    ||
    strpos($label,'móvil') !== false
){

    if(empty($phone)){

        $phone = $value;

    }

}

if(
    strpos($label,'correo') !== false
    ||
    strpos($label,'email') !== false
){

    if(empty($email)){

        $email = $value;

    }

}

if(
    strpos($label,'dni') !== false
    ||
    strpos($label,'documento') !== false
    ||
    strpos($label,'cedula') !== false
    ||
    strpos($label,'cédula') !== false
    ||
    strpos($label,'nie') !== false
    ||
    strpos($label,'pasaporte') !== false
    ||
    strpos($label,'cif') !== false
){

    if(empty($document_number)){

        $document_number = $value;

    }

}

}

    if(
        $campaign_id <= 0
    ){

        $error =
        "Debes seleccionar campaña.";

    } else {

        $stmt = $conn->prepare("
        INSERT INTO leads
(
    campaign_id,
    advisor_id,
    assigned_user_id,
    office_id,
    document_type,
    document_number,
    full_name,
    phone,
    email
)
VALUES
(
    ?, ?, ?, ?, ?, ?, ?, ?, ?
)
        ");

        $office_id =
        intval($_SESSION['office_id'] ?? 0);

        $assigned_user_id =
$current_user_id;

$stmt->bind_param(
    "iiiisssss",
    $campaign_id,
    $current_user_id,
    $assigned_user_id,
    $office_id,
    $document_type,
    $document_number,
    $full_name,
    $phone,
    $email
);

        if($stmt->execute()){

            $lead_id =
            $stmt->insert_id;

            /*
            |--------------------------------------------------------------------------
            | GUARDAR CAMPOS PERSONALIZADOS
            |--------------------------------------------------------------------------
            */

            $custom_fields_query = $conn->query("
            SELECT *
            FROM custom_fields
            WHERE module_name = 'leads'
            AND campaign_id = '$campaign_id'
            ORDER BY field_order ASC, id ASC
            ");

            while($field = $custom_fields_query->fetch_assoc()){

                $field_key =
                'custom_'.$field['id'];

                $field_value = '';

/*
|--------------------------------------------------------------------------
| SUBIR ARCHIVOS
|--------------------------------------------------------------------------
*/

if($field['field_type'] == 'file'){

    if(
        isset($_FILES[$field_key])
        &&
        $_FILES[$field_key]['error'] == 0
    ){

        $allowed_extensions =
        strtolower(
            trim(
                $field['allowed_extensions'] ?? ''
            )
        );

        $allowed_array = [];

        if($allowed_extensions != ''){

            $allowed_array =
            array_map(
                'trim',
                explode(',', $allowed_extensions)
            );

        }

        $original_name =
        $_FILES[$field_key]['name'];

        $tmp_name =
        $_FILES[$field_key]['tmp_name'];

        $file_size =
        $_FILES[$field_key]['size'];

        $extension =
        strtolower(
            pathinfo(
                $original_name,
                PATHINFO_EXTENSION
            )
        );

        /*
        |--------------------------------------------------------------------------
        | VALIDAR EXTENSION
        |--------------------------------------------------------------------------
        */

        if(
            !empty($allowed_array)
            &&
            !in_array($extension, $allowed_array)
        ){

            $error =
            "Archivo no permitido: ".$original_name;

        } else {

            /*
            |--------------------------------------------------------------------------
            | VALIDAR PESO MAXIMO 10MB
            |--------------------------------------------------------------------------
            */

            if($file_size > 10485760){

                $error =
                "Archivo demasiado pesado.";

            } else {

                $new_name =
                time().'_'.uniqid().'.'.$extension;

                $upload_path =
                '../uploads/custom_fields/'.$new_name;

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

                    $field_value =
                    '/uploads/custom_fields/'.$new_name;

                }

            }

        }

    }

} else {

    $field_value =
    trim($_POST[$field_key] ?? '');

}

                $stmt_custom =
                $conn->prepare("
                INSERT INTO lead_custom_values
                (
                    lead_id,
                    field_id,
                    field_value
                )
                VALUES (?, ?, ?)
                ");

                $stmt_custom->bind_param(
                    "iis",
                    $lead_id,
                    $field['id'],
                    $field_value
                );

                $stmt_custom->execute();

            }

            $success =
            "Lead creado correctamente.";

        } else {

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

        }

    }

}

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

$custom_fields = [];

if($selected_campaign > 0){

    $fields_query = $conn->query("
    SELECT *
    FROM custom_fields
    WHERE module_name = 'leads'
    AND campaign_id = '$selected_campaign'
    ORDER BY field_order ASC, id ASC
    ");

    while($field = $fields_query->fetch_assoc()){

        $custom_fields[] =
        $field;

    }

}

/*
|--------------------------------------------------------------------------
| LISTAR LEADS
|--------------------------------------------------------------------------
*/

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

LEFT JOIN campaigns
ON campaigns.id = leads.campaign_id

$where

ORDER BY leads.id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Leads
</title>

<link rel="stylesheet" href="/assets/css/style.css">

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-header{
    margin-bottom:30px;
}

.page-title{
    font-size:42px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.page-subtitle{
    color:#6b7280;
    font-size:16px;
}

.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(240px,1fr));
    gap: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;
}

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

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

.empty-box{
    padding:50px;
    text-align:center;
    color:#94a3b8;
}

.action-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:38px;
    padding:0 16px;
    border-radius:12px;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

.whatsapp-btn{
    background:#dcfce7;
    color:#166534;
}

.contract-btn{
    background:#dbeafe;
    color:#1d4ed8;
}

.edit-btn{
    background:#fef3c7;
    color:#92400e;
}

.actions-wrap{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.search-form{
    margin-bottom:25px;
    display:flex;
    gap:14px;
}

.search-input{
    flex:1;
    height:52px;
    border:none;
    background:#f3f5fa;
    border-radius:14px;
    padding:0 18px;
    font-size:15px;
}

.search-btn{
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 24px;
    background:#02122c;
    color:#ffffff;
    font-weight:700;
    cursor:pointer;
}

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-header">

        <div class="page-title">
            Leads
        </div>

        <div class="page-subtitle">
            Gestión de prospectos y oportunidades
        </div>

    </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="GET">

            <div class="form-grid">

                <div class="form-group">

                    <label>
                        Seleccionar campaña
                    </label>

                    <select
                        name="campaign_id"
                        class="form-control"
                        onchange="this.form.submit()"
                    >

                        <option value="0">
                            Seleccionar campaña
                        </option>

                        <?php

                        if($is_backoffice){

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

                        } else {

                            $campaigns_select = $conn->query("
                            SELECT campaigns.*
                            FROM campaigns
                            INNER JOIN user_campaigns
                            ON user_campaigns.campaign_id = campaigns.id
                            WHERE user_campaigns.user_id = '$current_user_id'
                            ORDER BY campaigns.campaign_name ASC
                            ");

                        }

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

                        ?>

                            <option
                                value="<?= $campaign['id'] ?>"
                                <?= $selected_campaign == $campaign['id'] ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars($campaign['campaign_name']) ?>
                            </option>

                        <?php endwhile; ?>

                    </select>

                </div>

            </div>

        </form>

    </div>

    <?php if($selected_campaign > 0): ?>

    <div class="white-card">

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

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

            <input
                type="hidden"
                name="campaign_id"
                value="<?= $selected_campaign ?>"
            >

           <div class="form-grid">

    <?php foreach($custom_fields as $field):
        $show_if_attr  = !empty($field['show_if']) ? 'data-show-if="'.htmlspecialchars($field['show_if']).'"' : '';
        $show_if_style = !empty($field['show_if']) ? 'style="display:none"' : '';
    ?>

        <div class="form-group" <?= $show_if_attr ?> <?= $show_if_style ?>>

            <label>
                <?= htmlspecialchars($field['field_label']) ?>
                <?php if(!empty($field['tooltip'])): ?><span title="<?= htmlspecialchars($field['tooltip']) ?>" style="cursor:help;color:#94a3b8">&#9432;</span><?php endif; ?>
            </label>

            <?php if($field['field_type'] == 'select'): ?>

    <select
        name="custom_<?= $field['id'] ?>"
        class="form-control"
        <?= $field['is_required'] == 1 ? 'required' : '' ?>
    >

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

        <?php

        $options =
        preg_split(
            '/\r\n|\r|\n/',
            $field['field_options']
        );

        foreach($options as $option):

            $option = trim($option);

            if($option == ''){
                continue;
            }

        ?>

            <option value="<?= htmlspecialchars($option) ?>">
                <?= htmlspecialchars($option) ?>
            </option>

        <?php endforeach; ?>

    </select>

<?php elseif($field['field_type'] == 'textarea'): ?>

    <textarea
        name="custom_<?= $field['id'] ?>"
        class="form-control"
        <?= $field['is_required'] == 1 ? 'required' : '' ?>
        minlength="<?= intval($field['min_length']) ?>"
        maxlength="<?= intval($field['max_length']) > 0 ? intval($field['max_length']) : '' ?>"
    ></textarea>

<?php elseif($field['field_type'] == 'file'): ?>

    <input
        type="file"
        name="custom_<?= $field['id'] ?>"
        class="form-control"
        <?= $field['is_required'] == 1 ? 'required' : '' ?>
    >

    <?php if(!empty($field['allowed_extensions'])): ?>

        <small>
            Permitidos:
            <?= htmlspecialchars($field['allowed_extensions']) ?>
        </small>

    <?php endif; ?>

<?php elseif($field['field_type'] == 'tel'): ?>

    <input
        type="tel"
        name="custom_<?= $field['id'] ?>"
        class="form-control"
        <?= $field['is_required'] == 1 ? 'required' : '' ?>
        minlength="<?= intval($field['min_length']) ?>"
        maxlength="<?= intval($field['max_length']) > 0 ? intval($field['max_length']) : '' ?>"
        placeholder="+34 600000000"
    >

<?php else: ?>

    <input
        type="<?= htmlspecialchars($field['field_type']) ?>"
        name="custom_<?= $field['id'] ?>"
        class="form-control"
        <?= $field['is_required'] == 1 ? 'required' : '' ?>
        minlength="<?= intval($field['min_length']) ?>"
        maxlength="<?= intval($field['max_length']) > 0 ? intval($field['max_length']) : '' ?>"
    >

<?php endif; ?>

        </div>

    <?php endforeach; ?>

</div>

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

        </form>

    </div>

    <?php endif; ?>

    <div class="white-card">

        <form
            method="GET"
            class="search-form"
        >

            <input
                type="hidden"
                name="campaign_id"
                value="<?= $selected_campaign ?>"
            >

            <input
                type="text"
                name="search"
                class="search-input"
                placeholder="Buscar por documento, nombre o teléfono..."
                value="<?= htmlspecialchars($search) ?>"
            >

            <button
                type="submit"
                class="search-btn"
            >
                Buscar
            </button>

        </form>

        <table class="crm-table">

            <thead>

                <tr>

                    <th>ID</th>
<th>Campaña</th>
<th>Nombre</th>
<?php
// Mostrar columna Documento solo si la campaña tiene un campo tipo documento
// o si no hay campaña seleccionada (vista general)
$show_document_col = false;
if($selected_campaign <= 0){
    $show_document_col = true; // vista general: mostrar siempre
} else {
    foreach($custom_fields as $cf){
        $lbl = strtolower(trim($cf['field_label']));
        if(
            strpos($lbl,'documento') !== false ||
            strpos($lbl,'cedula')    !== false ||
            strpos($lbl,'cédula')    !== false ||
            strpos($lbl,'dni')       !== false ||
            strpos($lbl,'nie')       !== false ||
            strpos($lbl,'pasaporte') !== false ||
            strpos($lbl,'cif')       !== false
        ){
            $show_document_col = true;
            break;
        }
    }
    // Si no hay ningún campo custom tipo documento, usar document_number nativo solo si tiene datos
    if(!$show_document_col){
        $has_docs = $conn->query("
            SELECT 1 FROM leads
            WHERE campaign_id = '$selected_campaign'
            AND in_cartera = 1
            AND document_number != ''
            AND document_number IS NOT NULL
            LIMIT 1
        ");
        if($has_docs && $has_docs->num_rows > 0){
            $show_document_col = true;
        }
    }
}
?>
<?php if($show_document_col): ?><th>Documento</th><?php endif; ?>
<th>Teléfono</th>
<th>Email</th>
<th>Campos personalizados</th>
<th>WhatsApp</th>
<th>Acciones</th>

                </tr>

            </thead>

            <tbody>

                <?php if($leads->num_rows > 0): ?>

                    <?php while($lead = $leads->fetch_assoc()): ?>

                        <tr>

                            <td>
                                #<?= $lead['id'] ?>
                            </td>

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

                            <?php

$lead_name =
$lead['full_name'] ?? '';

$lead_phone =
$lead['phone'] ?? '';

$custom_values_query = $conn->query("
SELECT
    custom_fields.field_label,
    lead_custom_values.field_value
FROM lead_custom_values

INNER JOIN custom_fields
ON custom_fields.id = lead_custom_values.field_id

WHERE lead_custom_values.lead_id = '".$lead['id']."'
");

while($cv = $custom_values_query->fetch_assoc()){

    $label =
    strtolower(trim($cv['field_label']));

    $value =
    trim($cv['field_value']);

    if(
        empty($lead_name)
        &&
        strpos($label,'nombre') !== false
    ){

        $lead_name = $value;

    }

    if(
        empty($lead_phone)
        &&
        (
            strpos($label,'telefono') !== false
            ||
            strpos($label,'teléfono') !== false
            ||
            strpos($label,'celular') !== false
            ||
            strpos($label,'movil') !== false
        )
    ){

        $lead_phone = $value;

    }

}

?>

<td>
    <?= htmlspecialchars($lead_name) ?>
</td>

<?php if($show_document_col): ?>
<td>
    <?= htmlspecialchars($lead['document_number'] ?? '') ?>
</td>
<?php endif; ?>

<td>
    <?= htmlspecialchars($lead_phone) ?>
</td>

<td>
    <?= htmlspecialchars($lead['email'] ?? '') ?>
</td>

<td>

<?php

$extra_fields = $conn->query("
SELECT
    custom_fields.field_label,
    custom_fields.field_type,
    lead_custom_values.field_value
FROM lead_custom_values

INNER JOIN custom_fields
ON custom_fields.id = lead_custom_values.field_id

WHERE lead_custom_values.lead_id = '".$lead['id']."'
");

while($extra = $extra_fields->fetch_assoc()):

?>

<div style="margin-bottom:10px;">

<strong>
<?= htmlspecialchars($extra['field_label']) ?>:
</strong>

<?php if($extra['field_type'] == 'file'): ?>

<a
href="<?= htmlspecialchars($extra['field_value']) ?>"
target="_blank"
>
Ver archivo
</a>

<?php else: ?>

<?= htmlspecialchars($extra['field_value']) ?>

<?php endif; ?>

</div>

<?php endwhile; ?>

</td>

                            <td>

                                <?php

                                $clean_phone =
                                preg_replace(
                                    '/[^0-9]/',
                                    '',
                                    $lead['phone'] ?? ''
                                );

                                ?>

                                <a
                                    href="/pages/open_whatsapp.php?lead_id=<?= $lead['id'] ?>"
                                    target="_blank"
                                    class="action-btn whatsapp-btn"
                                >
                                    WhatsApp
                                </a>

                            </td>

                            <td>

                                <div class="actions-wrap">

    <a
        href="/pages/view_lead.php?id=<?= $lead['id'] ?>"
        class="action-btn whatsapp-btn"
    >
        Ver lead
    </a>

    <a
        href="/pages/edit_lead.php?id=<?= $lead['id'] ?>"
        class="action-btn edit-btn"
    >
        Editar
    </a>

    <a
        href="/pages/contracts.php?lead_id=<?= $lead['id'] ?>"
        class="action-btn contract-btn"
    >
        Crear contrato
    </a>

</div>

                            </td>

                        </tr>

                    <?php endwhile; ?>

                <?php else: ?>

                    <tr>

                        <td colspan="9">

                            <div class="empty-box">
                                No hay leads registrados.
                            </div>

                        </td>

                    </tr>

                <?php endif; ?>

            </tbody>

        </table>

    </div>

</div>

<script>
(function(){
    function applyConditionals(){
        document.querySelectorAll('[data-show-if]').forEach(function(g){
            try{
                var cond=JSON.parse(g.dataset.showIf);
                var t=document.querySelector('[name="custom_'+cond.field_id+'"]');
                if(!t) return;
                function check(){ var show=t.value===cond.value; g.style.display=show?'':'none'; }
                t.addEventListener('change',check);
                t.addEventListener('input',check);
                check();
            }catch(e){}
        });
    }
    document.addEventListener('DOMContentLoaded',applyConditionals);
})();
</script>
</body>
</html>