<?php

session_start();

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

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

}

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

requirePermission('can_create_leads');

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

$user_id = $_SESSION['user_id'];

$columns = [
    'status' => "VARCHAR(100) NULL",
    'city' => "VARCHAR(255) NULL",
    'created_by' => "INT NULL",
    'imported_at' => "DATETIME NULL",
    'import_batch' => "VARCHAR(255) NULL",
    'updated_at' => "TIMESTAMP NULL"
];

foreach($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");
    }
}

$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");
$conn->query("CREATE TABLE IF NOT EXISTS lead_import_campaigns (id INT AUTO_INCREMENT PRIMARY KEY, import_batch VARCHAR(255), campaign_id INT, INDEX(import_batch), INDEX(campaign_id))");

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

if(isset($_GET['delete_batch'])){
    $batch = $conn->real_escape_string($_GET['delete_batch']);
    $leads_delete = $conn->query("SELECT id FROM leads WHERE import_batch = '$batch'");
    while($lead = $leads_delete->fetch_assoc()){
        $lead_id = intval($lead['id']);
        $conn->query("DELETE FROM lead_custom_values WHERE lead_id = '$lead_id'");
    }
    $conn->query("DELETE FROM lead_imports WHERE import_batch = '$batch'");
    $conn->query("DELETE FROM leads WHERE import_batch = '$batch'");
    header("Location: import_leads.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| PASO 1: LEER HEADERS DEL CSV Y MOSTRAR MAPEO
|--------------------------------------------------------------------------
*/

$csv_headers  = [];
$csv_tmp_path = '';
$show_mapping = false;

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['preview_csv'])){
    if(!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] != 0){
        $error = "Debes subir un archivo CSV.";
    } else {
        $tmp_name  = $_FILES['csv_file']['tmp_name'];
        $extension = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        if($extension != 'csv'){
            $error = "Solo se permiten archivos CSV.";
        } else {
            $saved_tmp = sys_get_temp_dir() . '/csv_import_' . session_id() . '.csv';
            move_uploaded_file($tmp_name, $saved_tmp);
            $handle     = fopen($saved_tmp, "r");
            $first_line = fgets($handle);
            rewind($handle);
            $delimiter  = substr_count($first_line, ";") > substr_count($first_line, ",") ? ";" : ",";
            $raw_headers = fgetcsv($handle, 5000, $delimiter);
            fclose($handle);
            if($raw_headers){
                foreach($raw_headers as $h) $csv_headers[] = trim($h);
                $csv_tmp_path = $saved_tmp;
                $show_mapping = true;
            } else {
                $error = "No se pudieron leer las columnas del CSV.";
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| PASO 2: IMPORTAR CON MAPEO CONFIRMADO
|--------------------------------------------------------------------------
*/

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

    $campaign_ids = array_filter(array_map('intval', $_POST['campaign_ids'] ?? []));
    $office_ids   = array_filter(array_map('intval', $_POST['office_ids']   ?? []));

    if(empty($campaign_ids)){
        $error = 'Selecciona al menos una campaña.';
    } else {

        $office_id    = !empty($office_ids) ? $office_ids[0] : 0;
        $status       = trim($_POST['status']);
        $import_batch = 'BASE_' . date('Ymd_His');
        $saved_tmp    = trim($_POST['csv_tmp_path']);
        $column_map   = $_POST['column_map'] ?? [];
        $extra_include = $_POST['extra_include'] ?? [];
        $extra_labels  = $_POST['extra_label']   ?? [];

        // Mapa de campos extra: csv_col => etiqueta personalizada
        $extra_map = [];
        foreach($extra_include as $col){
            $label = trim($extra_labels[$col] ?? $col);
            if($label !== '') $extra_map[$col] = $label;
        }

        if(!file_exists($saved_tmp)){
            $error = "El archivo temporal expiró. Vuelve a subir el CSV.";
        } else {

            $handle     = fopen($saved_tmp, "r");
            $first_line = fgets($handle);
            rewind($handle);
            $delimiter  = substr_count($first_line, ";") > substr_count($first_line, ",") ? ";" : ",";
            $raw_headers = fgetcsv($handle, 5000, $delimiter);
            $headers    = array_map('trim', $raw_headers);

            $map_inverted = [];
            foreach($column_map as $crm_field => $csv_header){
                if($csv_header !== '') $map_inverted[trim($csv_header)] = $crm_field;
            }

            $imported    = 0;
            $duplicates  = 0;
            $campaign_id = $campaign_ids[0];

            while(($row = fgetcsv($handle, 5000, $delimiter)) !== false){

                $data = [];
                foreach($headers as $index => $header){
                    $value = isset($row[$index]) ? trim($row[$index]) : '';
                    $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8, ISO-8859-1, Windows-1252');
                    $data[$header] = $value;
                }

                $full_name = $phone = $email = $city = '';

                foreach($map_inverted as $csv_col => $crm_field){
                    $val = $data[$csv_col] ?? '';
                    if($crm_field === 'full_name') $full_name = $val;
                    if($crm_field === 'phone')     $phone     = $val;
                    if($crm_field === 'email')     $email     = $val;
                    if($crm_field === 'city')      $city      = $val;
                }

                if(!$full_name) $full_name = $data['nombre'] ?? $data['name'] ?? $data['full_name'] ?? '';
                if(!$phone)     $phone     = $data['telefono'] ?? $data['telefono_1'] ?? $data['movil'] ?? $data['phone'] ?? '';
                if(!$email)     $email     = $data['email'] ?? '';
                if(!$city)      $city      = $data['ciudad'] ?? $data['city'] ?? '';

                $full_name = trim($full_name);
                $phone     = trim($phone);
                $email     = trim($email);
                $city      = trim($city);

                if($full_name == '' && $phone == '' && $email == '') continue;

                // Solo guardar campos extra marcados con etiqueta personalizada
                $extra = [];
                foreach($extra_map as $csv_col => $label){
                    $val = $data[$csv_col] ?? '';
                    if($val !== '') $extra[$label] = $val;
                }
                $extra_json = !empty($extra) ? json_encode($extra, JSON_UNESCAPED_UNICODE) : null;

                $phone_safe = $conn->real_escape_string($phone);
                $email_safe = $conn->real_escape_string($email);
                $duplicate  = false;

                if($phone != '' || $email != ''){
                    $dup = $conn->query("SELECT id FROM leads WHERE ('$phone_safe'!='' AND phone='$phone_safe') OR ('$email_safe'!='' AND email='$email_safe') LIMIT 1");
                    $duplicate = $dup && $dup->num_rows > 0;
                }

                if($duplicate){
                    $duplicates++;
                } else {
                    $stmt = $conn->prepare("INSERT INTO leads (full_name,phone,email,city,campaign_id,office_id,status,created_by,imported_at,import_batch,in_cartera,extra_data) VALUES (?,?,?,?,?,?,?,?,NOW(),?,0,?)");
                    $stmt->bind_param("ssssiiisss", $full_name,$phone,$email,$city,$campaign_id,$office_id,$status,$user_id,$import_batch,$extra_json);
                    if($stmt->execute()) $imported++;
                }
            }

            fclose($handle);
            @unlink($saved_tmp);

            $batch_safe = $conn->real_escape_string($import_batch);
            $conn->query("INSERT INTO lead_imports (import_batch,campaign_id,office_id,total_leads,duplicates_found,uploaded_by) VALUES ('$batch_safe','$campaign_id','$office_id','$imported','$duplicates','$user_id')");
            foreach($campaign_ids as $cid){
                $conn->query("INSERT IGNORE INTO lead_import_campaigns (import_batch,campaign_id) VALUES ('$batch_safe','$cid')");
            }
            $success = "Importación completada. Nuevos: $imported | Duplicados: $duplicates";
        }
    }
}

/*
|--------------------------------------------------------------------------
| IMPORTAR CSV (legado - flujo directo sin mapeo)
|--------------------------------------------------------------------------
*/

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

    if(!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] != 0){
        $error = "Debes subir un archivo CSV.";
    } else {

        $campaign_ids = array_filter(array_map('intval', $_POST['campaign_ids'] ?? []));
        $office_ids   = array_filter(array_map('intval', $_POST['office_ids']   ?? []));

        if(empty($campaign_ids)){
            $error = 'Selecciona al menos una campaña.';
        } else {

            $campaign_id = $campaign_ids[0];
            $office_id   = !empty($office_ids) ? $office_ids[0] : 0;
            $status      = trim($_POST['status']);
            $import_batch = 'BASE_' . date('Ymd_His');
            $tmp_name    = $_FILES['csv_file']['tmp_name'];
            $extension   = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));

            if($extension != 'csv'){
                $error = "Solo se permiten archivos CSV.";
            } else {

                $handle = fopen($tmp_name, "r");
                if(!$handle){
                    $error = "No se pudo abrir el archivo CSV.";
                } else {

                    $first_line = fgets($handle);
                    rewind($handle);
                    $delimiter = substr_count($first_line, ";") > substr_count($first_line, ",") ? ";" : ",";
                    $headers = fgetcsv($handle, 5000, $delimiter);

                    if(!$headers){
                        $error = "No se pudieron leer las columnas.";
                    } else {

                        $headers = array_map(function($h){
                            $h = trim(strtolower($h));
                            return str_replace(['á','é','í','ó','ú'],['a','e','i','o','u'],$h);
                        }, $headers);

                        $imported = 0; $duplicates = 0;

                        while(($row = fgetcsv($handle, 5000, $delimiter)) !== false){

                            $data = [];
                            foreach($headers as $index => $header){
                                $value = isset($row[$index]) ? trim($row[$index]) : '';
                                $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8, ISO-8859-1, Windows-1252');
                                $data[$header] = $value;
                            }

                            $full_name = $data['nombre'] ?? $data['name'] ?? $data['full_name'] ?? '';
                            $phone     = $data['telefono'] ?? $data['telefono_1'] ?? $data['movil'] ?? $data['phone'] ?? '';
                            $email     = $data['email'] ?? '';
                            $city      = $data['ciudad'] ?? $data['city'] ?? '';

                            $full_name = trim($full_name); $phone = trim($phone);
                            $email = trim($email); $city = trim($city);

                            if($full_name == '' && $phone == '' && $email == '') continue;

                            $known = ['nombre','name','full_name','telefono','telefono_1','movil','phone','email','ciudad','city'];
                            $extra = [];
                            foreach($data as $k => $v){ if(!in_array($k,$known) && $v!=='') $extra[$k]=$v; }
                            $extra_json = !empty($extra) ? json_encode($extra, JSON_UNESCAPED_UNICODE) : null;

                            $phone_safe = $conn->real_escape_string($phone);
                            $email_safe = $conn->real_escape_string($email);
                            $duplicate  = false;

                            if($phone != '' || $email != ''){
                                $dup = $conn->query("SELECT id FROM leads WHERE ('$phone_safe'!='' AND phone='$phone_safe') OR ('$email_safe'!='' AND email='$email_safe') LIMIT 1");
                                $duplicate = $dup && $dup->num_rows > 0;
                            }

                            if($duplicate){
                                $duplicates++;
                            } else {
                                $stmt = $conn->prepare("INSERT INTO leads (full_name,phone,email,city,campaign_id,office_id,status,created_by,imported_at,import_batch,in_cartera,extra_data) VALUES (?,?,?,?,?,?,?,?,NOW(),?,0,?)");
                                $stmt->bind_param("ssssiiisss",$full_name,$phone,$email,$city,$campaign_id,$office_id,$status,$user_id,$import_batch,$extra_json);
                                if($stmt->execute()) $imported++;
                            }
                        }

                        fclose($handle);

                        $batch_safe = $conn->real_escape_string($import_batch);
                        $conn->query("INSERT INTO lead_imports (import_batch,campaign_id,office_id,total_leads,duplicates_found,uploaded_by) VALUES ('$batch_safe','$campaign_id','$office_id','$imported','$duplicates','$user_id')");
                        foreach($campaign_ids as $cid){
                            $conn->query("INSERT IGNORE INTO lead_import_campaigns (import_batch,campaign_id) VALUES ('$batch_safe','$cid')");
                        }
                        $success = "Importación completada. Nuevos: $imported | Duplicados: $duplicates";
                    }
                }
            }
        }
    }
}

$imports = $conn->query("SELECT * FROM lead_imports ORDER BY created_at DESC");

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Importar Leads</title>
<link rel="stylesheet" href="/assets/css/style.css">
<style>
.content-area{ margin-left:260px; padding:40px; }
.page-title{ font-size:42px; font-weight:800; color:#02122c; margin-bottom:10px; }
.page-subtitle{ color:#64748b; margin-bottom:30px; }
.white-card{ background:#ffffff; border-radius:24px; padding:30px; margin-bottom:25px; box-shadow:0 10px 30px rgba(15,23,42,.06); }
.form-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:20px; }
.form-group{ display:flex; flex-direction:column; }
.form-group label{ margin-bottom:10px; font-size:14px; font-weight:700; color:#475569; }
.form-control{ height:54px; border:none; border-radius:16px; background:#f1f5f9; padding:0 18px; font-size:15px; }
input[type=file]{ padding:14px; height:auto; }
.btn-save{ margin-top:25px; height:54px; border:none; border-radius:16px; padding:0 28px; background:linear-gradient(90deg,#5b4bff,#7b61ff); color:#ffffff; font-weight:700; cursor:pointer; font-size:15px; }
.success-box{ background:#dcfce7; color:#166534; padding:15px; border-radius:14px; margin-bottom:20px; font-weight:600; }
.error-box{ background:#fee2e2; color:#991b1b; padding:15px; border-radius:14px; margin-bottom:20px; font-weight:600; }
.crm-table{ width:100%; border-collapse:collapse; }
.crm-table th{ text-align:left; padding:16px; border-bottom:2px solid #e2e8f0; font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; }
.crm-table td{ padding:16px; border-bottom:1px solid #e2e8f0; font-size:14px; }
.action-btn{ display:inline-flex; align-items:center; justify-content:center; padding:10px 14px; border-radius:12px; text-decoration:none; font-size:13px; font-weight:700; }
.check-list{ background:#f1f5f9; border-radius:16px; padding:14px 18px; max-height:180px; overflow-y:auto; }
.check-item{ display:flex; align-items:center; gap:10px; margin-bottom:10px; cursor:pointer; font-size:14px; font-weight:600; color:#02122c; }
.check-item input[type=checkbox]{ width:18px; height:18px; accent-color:#5b4bff; cursor:pointer; flex-shrink:0; }
</style>
</head>
<body>

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

<div class="content-area">

<div class="page-title">Importar Leads</div>
<div class="page-subtitle">Subida masiva de bases CSV</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; ?>

<!-- FORMULARIO INICIAL -->
<div class="white-card">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="preview_csv" value="1">

<div class="form-grid">

    <div class="form-group">
        <label>Archivo CSV</label>
        <input type="file" name="csv_file" class="form-control" accept=".csv" required>
    </div>

    <div class="form-group">
        <label>Campañas (puedes seleccionar varias)</label>
        <div class="check-list">
        <?php
        $camps_arr = [];
        while($campaign = $campaigns->fetch_assoc()) $camps_arr[] = $campaign;
        foreach($camps_arr as $campaign):
        ?>
        <label class="check-item">
            <input type="checkbox" name="campaign_ids[]" value="<?= $campaign['id'] ?>">
            <?= htmlspecialchars($campaign['campaign_name']) ?>
        </label>
        <?php endforeach; ?>
        </div>
    </div>

    <div class="form-group">
        <label>Oficinas (puedes seleccionar varias)</label>
        <div class="check-list">
        <?php
        $offs_arr = [];
        while($office = $offices->fetch_assoc()) $offs_arr[] = $office;
        foreach($offs_arr as $office):
        ?>
        <label class="check-item">
            <input type="checkbox" name="office_ids[]" value="<?= $office['id'] ?>">
            <?= htmlspecialchars($office['office_name']) ?>
        </label>
        <?php endforeach; ?>
        </div>
    </div>

    <div class="form-group">
        <label>Estado inicial</label>
        <select name="status" class="form-control">
            <option value="Nuevo">Nuevo</option>
            <option value="Contactado">Contactado</option>
            <option value="Validacion">Validación</option>
        </select>
    </div>

</div>

<button type="submit" class="btn-save">Previsualizar y mapear columnas</button>
</form>
</div>

<!-- MAPPING UI -->
<?php if($show_mapping): ?>
<div class="white-card" id="mapping-card">

    <div style="display:flex;align-items:center;gap:14px;margin-bottom:28px">
        <div style="width:52px;height:52px;background:#ede9fe;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:24px">🗂️</div>
        <div>
            <div style="font-size:22px;font-weight:800;color:#02122c">Mapear columnas del CSV</div>
            <div style="font-size:14px;color:#64748b">Asigna cada columna de tu base a su campo correspondiente</div>
        </div>
    </div>

    <form method="POST">
    <input type="hidden" name="import_confirm" value="1">
    <input type="hidden" name="csv_tmp_path" value="<?= htmlspecialchars($csv_tmp_path) ?>">

    <!-- Campañas + Oficinas + Estado en 3 columnas -->
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;margin-bottom:28px">
        <div>
            <div style="font-size:13px;font-weight:700;color:#475569;text-transform:uppercase;margin-bottom:10px">Campañas</div>
            <div class="check-list">
            <?php $cm=$conn->query("SELECT * FROM campaigns ORDER BY campaign_name ASC"); while($c=$cm->fetch_assoc()): ?>
            <label class="check-item">
                <input type="checkbox" name="campaign_ids[]" value="<?= $c['id'] ?>">
                <?= htmlspecialchars($c['campaign_name']) ?>
            </label>
            <?php endwhile; ?>
            </div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:#475569;text-transform:uppercase;margin-bottom:10px">Oficinas</div>
            <div class="check-list">
            <?php $om=$conn->query("SELECT * FROM offices ORDER BY office_name ASC"); while($o=$om->fetch_assoc()): ?>
            <label class="check-item">
                <input type="checkbox" name="office_ids[]" value="<?= $o['id'] ?>">
                <?= htmlspecialchars($o['office_name']) ?>
            </label>
            <?php endwhile; ?>
            </div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:#475569;text-transform:uppercase;margin-bottom:10px">Estado inicial</div>
            <select name="status" class="form-control">
                <option value="Nuevo">Nuevo</option>
                <option value="Contactado">Contactado</option>
                <option value="Validacion">Validación</option>
            </select>
        </div>
    </div>

    <!-- Campos fijos -->
    <div style="font-size:13px;font-weight:700;color:#475569;text-transform:uppercase;margin-bottom:12px">Campos principales</div>
    <div style="background:#f8fafc;border-radius:16px;overflow:hidden;margin-bottom:24px">
        <div style="display:grid;grid-template-columns:1fr 1fr;padding:12px 20px;background:#02122c;font-size:12px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px">
            <span>Campo del CRM</span><span>Columna del CSV</span>
        </div>
        <?php
        $crm_fields = ['full_name'=>'Nombre completo','phone'=>'Teléfono principal','email'=>'Email','city'=>'Ciudad'];
        $suggestions = [
            'full_name'=>['nombre','name','full_name','cliente','contacto','apellido'],
            'phone'=>['telefono','telefono_1','movil','phone','tel','celular','mobile'],
            'email'=>['email','correo','mail','e-mail'],
            'city'=>['ciudad','city','localidad','provincia','municipio'],
        ];
        $already_mapped = [];
        foreach($crm_fields as $field_key => $field_label):
            $auto = '';
            foreach($csv_headers as $h){
                $h_low = strtolower($h);
                foreach($suggestions[$field_key] as $sug){
                    if(strpos($h_low,$sug)!==false){ $auto=$h; $already_mapped[]=$h; break 2; }
                }
            }
        ?>
        <div style="display:grid;grid-template-columns:1fr 1fr;padding:14px 20px;border-bottom:1px solid #e2e8f0;align-items:center">
            <div>
                <div style="font-size:14px;font-weight:700;color:#02122c"><?= $field_label ?></div>
                <div style="font-size:12px;color:#64748b">Campo del CRM</div>
            </div>
            <div>
                <select name="column_map[<?= $field_key ?>]" style="width:100%;height:42px;border:1px solid #e2e8f0;background:#fff;border-radius:10px;padding:0 12px;font-size:14px">
                    <option value="">-- No mapear --</option>
                    <?php foreach($csv_headers as $h): ?>
                    <option value="<?= htmlspecialchars($h) ?>" <?= $h===$auto?'selected':'' ?>><?= htmlspecialchars($h) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Campos adicionales del CSV -->
    <?php $extra_headers = array_values(array_filter($csv_headers, function($h) use ($already_mapped){ return !in_array($h,$already_mapped); })); ?>
    <?php if(!empty($extra_headers)): ?>
    <div style="font-size:13px;font-weight:700;color:#475569;text-transform:uppercase;margin-bottom:12px">
        Campos adicionales del CSV
        <span style="font-size:11px;font-weight:500;color:#94a3b8;text-transform:none;margin-left:8px">
            Marca los que quieras incluir y cómo los verá el agente durante la llamada
        </span>
    </div>
    <div style="background:#f8fafc;border-radius:16px;overflow:hidden;margin-bottom:24px">
        <div style="display:grid;grid-template-columns:40px 1fr 1fr;padding:12px 20px;background:#374151;font-size:12px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px">
            <span></span><span>Columna del CSV</span><span>Nombre para el agente</span>
        </div>
        <?php foreach($extra_headers as $h): ?>
        <div style="display:grid;grid-template-columns:40px 1fr 1fr;padding:12px 20px;border-bottom:1px solid #e2e8f0;align-items:center;gap:12px">
            <div>
                <input type="checkbox" name="extra_include[]" value="<?= htmlspecialchars($h) ?>"
                    id="ei_<?= md5($h) ?>"
                    style="width:18px;height:18px;accent-color:#5b4bff;cursor:pointer"
                    onchange="var row=this.closest('div').parentElement;var inp=row.querySelector('input[type=text]');inp.disabled=!this.checked;if(this.checked)inp.focus();">
            </div>
            <div>
                <label for="ei_<?= md5($h) ?>" style="font-size:14px;font-weight:600;color:#02122c;cursor:pointer">
                    <?= htmlspecialchars($h) ?>
                </label>
            </div>
            <div>
                <input type="text" name="extra_label[<?= htmlspecialchars($h) ?>]"
                    value="<?= htmlspecialchars($h) ?>"
                    style="width:100%;height:38px;border:1px solid #e2e8f0;background:#f1f5f9;border-radius:10px;padding:0 12px;font-size:13px"
                    placeholder="Nombre visible..." disabled>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div style="display:flex;gap:12px">
        <button type="submit" class="btn-save" style="margin-top:0">Importar base</button>
        <a href="import_leads.php" style="height:54px;border-radius:16px;padding:0 24px;background:#e2e8f0;color:#02122c;font-weight:700;font-size:15px;display:inline-flex;align-items:center;text-decoration:none">Cancelar</a>
    </div>

    </form>
</div>
<?php endif; ?>

<!-- BASES IMPORTADAS -->
<div class="white-card">
<h3 style="margin-bottom:25px;font-size:20px;font-weight:800;color:#02122c">Bases subidas</h3>
<table class="crm-table">
    <thead>
        <tr>
            <th>Base</th><th>Campaña</th><th>Oficina</th>
            <th>Leads</th><th>Duplicados</th><th>Fecha</th><th>Acciones</th>
        </tr>
    </thead>
    <tbody>
    <?php while($import = $imports->fetch_assoc()):
        $campaign_name = '-'; $office_name = '-';
        $cq = $conn->query("SELECT campaign_name FROM campaigns WHERE id='".intval($import['campaign_id'])."' LIMIT 1");
        if($cq && $cq->num_rows > 0) $campaign_name = $cq->fetch_assoc()['campaign_name'];
        $oq = $conn->query("SELECT office_name FROM offices WHERE id='".intval($import['office_id'])."' LIMIT 1");
        if($oq && $oq->num_rows > 0) $office_name = $oq->fetch_assoc()['office_name'];
    ?>
    <tr>
        <td><strong><?= htmlspecialchars($import['import_batch']) ?></strong></td>
        <td><?= htmlspecialchars($campaign_name) ?></td>
        <td><?= htmlspecialchars($office_name) ?></td>
        <td><?= intval($import['total_leads']) ?></td>
        <td><?= intval($import['duplicates_found']) ?></td>
        <td><?= htmlspecialchars($import['created_at']) ?></td>
        <td>
            <a href="?delete_batch=<?= urlencode($import['import_batch']) ?>"
                class="action-btn" style="background:#fee2e2;color:#991b1b"
                onclick="return confirm('¿Eliminar base completa?')">Eliminar</a>
        </td>
    </tr>
    <?php endwhile; ?>
    </tbody>
</table>
</div>

</div>
</body>
</html>