yazrkisvs3vvvsv33svrhetrjsvyvsvvyjsvsvs
tavsuysvssvvjvvyjyjkvsvqd
qfogsvvsvsegjdgdfgdskhgdksvqsvshdqsd
<?php
require_once 'auth.php'; requireLogin();
$db = getDB();
$user = currentUser();
$accion = $_GET['accion'] ?? (isset($_GET['nuevo']) ? 'nuevo' : 'lista');

// Migración segura: tabla para historial de etapas
try {
    $db->exec("CREATE TABLE IF NOT EXISTS dimark_stage_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        prospecto_id INT NOT NULL,
        estado VARCHAR(50) NOT NULL,
        usuario_id INT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (prospecto_id) REFERENCES dimark_prospectos(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) {}

// Agregar columnas pais y ciudad si no existen
try { $db->exec("ALTER TABLE dimark_prospectos ADD COLUMN pais VARCHAR(100)"); } catch(Exception $e) {}
try { $db->exec("ALTER TABLE dimark_prospectos ADD COLUMN ciudad VARCHAR(100)"); } catch(Exception $e) {}

// ── EXPORTAR CSV ────────────────────────────────────────────────
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $asesor_sql = isAdmin() ? '' : ' AND p.asesor_id=' . intval($user['id']);
    $rows = $db->query("SELECT p.empresa,p.contacto,p.cargo,p.telefono,p.email,p.sector,p.canal,p.estado,p.plan_interes,p.fecha_followup,p.proximo_paso,p.notas,u.nombre as asesor,p.created_at FROM dimark_prospectos p LEFT JOIN dimark_usuarios u ON p.asesor_id=u.id WHERE 1=1 {$asesor_sql} ORDER BY p.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="prospectos_'.date('Ymd').'.csv"');
    echo "\xEF\xBB\xBF"; // BOM UTF-8
    $out = fopen('php://output','w');
    fputcsv($out, ['Empresa','Contacto','Cargo','Teléfono','Email','Sector','Canal','Estado','Plan','Follow-up','Próximo paso','Notas','Asesor','Creado'], ';');
    foreach ($rows as $r) fputcsv($out, array_values($r), ';');
    fclose($out); exit;
}

// ── NUEVA ACTIVIDAD ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_accion'] ?? '') === 'actividad') {
    csrf_check();
    $pid = intval($_POST['prospecto_id'] ?? 0);
    $tipo = $_POST['tipo'] ?? 'nota';
    $tipos_ok = ['contacto','seguimiento','demo','propuesta','cierre','nota'];
    if ($pid && in_array($tipo, $tipos_ok)) {
        $db->prepare("INSERT INTO dimark_actividades (prospecto_id, usuario_id, tipo, descripcion) VALUES (?,?,?,?)")
           ->execute([$pid, $user['id'], $tipo, clean($_POST['descripcion'] ?? '')]);
    }
    header("Location: prospectos.php?accion=ver&id={$pid}"); exit;
}

// ── CREAR / EDITAR ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $id = intval($_POST['id'] ?? 0);
    $data = [
        'empresa'        => clean($_POST['empresa'] ?? ''),
        'contacto'       => clean($_POST['contacto'] ?? ''),
        'cargo'          => clean($_POST['cargo'] ?? ''),
        'telefono'       => clean($_POST['telefono'] ?? ''),
        'email'          => clean($_POST['email'] ?? ''),
        'sector'         => $_POST['sector'] ?? 'ecommerce',
        'canal'          => $_POST['canal'] ?? 'whatsapp',
        'estado'         => $_POST['estado'] ?? 'prospecto',
        'plan_interes'   => $_POST['plan_interes'] ?? '',
        'notas'          => clean($_POST['notas'] ?? ''),
        'proximo_paso'   => clean($_POST['proximo_paso'] ?? ''),
        'fecha_followup' => $_POST['fecha_followup'] ?: null,
        'pais'           => clean($_POST['pais'] ?? ''),
        'ciudad'         => clean($_POST['ciudad'] ?? ''),
        'asesor_id'      => $user['id'],
    ];
    if ($id > 0) {
        // Obtener estado anterior para detectar cambio de etapa
        $old_estado = $db->prepare("SELECT estado FROM dimark_prospectos WHERE id=?");
        $old_estado->execute([$id]);
        $old_estado = $old_estado->fetchColumn();

        $sql = "UPDATE dimark_prospectos SET empresa=?,contacto=?,cargo=?,telefono=?,email=?,sector=?,canal=?,estado=?,plan_interes=?,notas=?,proximo_paso=?,fecha_followup=?,pais=?,ciudad=? WHERE id=?";
        $stmt = $db->prepare($sql);
        $stmt->execute([...array_values(array_slice($data,0,14)), $id]);

        // Registrar cambio de etapa en historial
        if ($data['estado'] !== $old_estado) {
            try {
                $db->prepare("INSERT INTO dimark_stage_history (prospecto_id, estado, usuario_id) VALUES (?,?,?)")
                   ->execute([$id, $data['estado'], $user['id']]);
            } catch (Exception $e) {}
        }

        // Si ganado, crear cliente
        if ($data['estado'] === 'ganado') {
            $existe = $db->prepare("SELECT id FROM dimark_clientes WHERE prospecto_id=?"); $existe->execute([$id]);
            if (!$existe->fetch()) {
                $cs = $db->prepare("INSERT INTO dimark_clientes (prospecto_id,empresa,contacto,telefono,email,sector,plan,precio_mes,fecha_inicio,canal_origen,asesor_id) VALUES (?,?,?,?,?,?,?,?,CURDATE(),?,?)");
                $precio = ['desafiante'=>800000,'confiado'=>1700000,'dinamico'=>2500000][$data['plan_interes']] ?? 1700000;
                $cs->execute([$id,$data['empresa'],$data['contacto'],$data['telefono'],$data['email'],$data['sector'],$data['plan_interes'],$precio,$data['canal'],$user['id']]);
            }
        }
    } else {
        $sql = "INSERT INTO dimark_prospectos (empresa,contacto,cargo,telefono,email,sector,canal,estado,plan_interes,notas,proximo_paso,fecha_followup,pais,ciudad,asesor_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt = $db->prepare($sql);
        $stmt->execute(array_values($data));
        // Registrar etapa inicial en historial
        $new_id = intval($db->lastInsertId());
        try {
            $db->prepare("INSERT INTO dimark_stage_history (prospecto_id, estado, usuario_id) VALUES (?,?,?)")
               ->execute([$new_id, $data['estado'], $user['id']]);
        } catch (Exception $e) {}
    }
    header('Location: prospectos.php'); exit;
}

// ── ELIMINAR ────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_accion'] ?? '') === 'eliminar') {
    csrf_check();
    $db->prepare("DELETE FROM dimark_prospectos WHERE id=?")->execute([intval($_POST['id'] ?? 0)]);
    header('Location: prospectos.php'); exit;
}

// ── VER / EDITAR FORM ───────────────────────────────────────────
$editing = null;
if (in_array($accion, ['ver','editar']) && isset($_GET['id'])) {
    $stmt = $db->prepare("SELECT * FROM dimark_prospectos WHERE id=?");
    $stmt->execute([intval($_GET['id'])]);
    $editing = $stmt->fetch();
}

$page_title    = $accion === 'lista' ? 'Prospectos' : ($editing ? clean($editing['empresa']) : 'Nuevo prospecto');
$page_subtitle = $accion === 'lista' ? 'Todos los prospectos registrados' : 'Ficha de prospecto';
ob_start(); ?>
<?php if($accion==='lista'): ?>
<a href="prospectos.php?export=csv" class="btn"><i class="ti ti-download"></i> CSV</a>
<a href="prospectos.php?nuevo=1" class="btn btn-primary"><i class="ti ti-plus"></i> Nuevo</a>
<?php endif; ?>
<?php $page_actions = ob_get_clean();
require_once 'layout.php';

$sectores = ['ecommerce'=>'🛒 Ecommerce','clinicas'=>'🏥 Clínicas / Salud','b2b'=>'⚙️ B2B Servicios','inmobiliarias'=>'🏢 Inmobiliarias','hoteles'=>'🏨 Hoteles / Turismo','restaurantes'=>'🍽️ Restaurantes','educacion'=>'🎓 Educación','retail'=>'👗 Retail / Moda'];
$canales  = ['whatsapp'=>'WhatsApp','meta_ads'=>'Meta Ads','linkedin'=>'LinkedIn','referidos'=>'Referidos','influencers'=>'Influencers','partnerships'=>'Partnerships','otro'=>'Otro'];
$estados  = ['prospecto'=>'Prospecto','contactado'=>'Contactado','demo_agendada'=>'Demo agendada','demo_realizada'=>'Demo realizada','negociacion'=>'Negociación','propuesta_enviada'=>'Propuesta enviada','ganado'=>'Ganado','perdido'=>'Perdido'];
$planes   = [''=>'Sin definir','desafiante'=>'Solo Ads ($800K COP)','confiado'=>'Ads + Contenido + Landing ($1.7M COP)','dinamico'=>'Ecosistema Completo ($2.5M COP)'];
$badge_est= ['prospecto'=>'b-gray','contactado'=>'b-gray','demo_agendada'=>'b-amber','demo_realizada'=>'b-blue','negociacion'=>'b-amber','propuesta_enviada'=>'b-purple','ganado'=>'b-green','perdido'=>'b-red'];
?>

<?php if($accion === 'lista'): ?>
<?php
$asesor_sql  = isAdmin() ? '' : ' AND asesor_id=' . intval($user['id']);
$cnt_total    = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE 1=1 {$asesor_sql}")->fetchColumn();
$cnt_activos  = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE estado NOT IN ('ganado','perdido') {$asesor_sql}")->fetchColumn();
$cnt_ganados  = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE estado='ganado' {$asesor_sql}")->fetchColumn();
$cnt_perdidos = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE estado='perdido' {$asesor_sql}")->fetchColumn();
$cnt_demos    = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE estado IN ('demo_agendada','demo_realizada') {$asesor_sql}")->fetchColumn();
$cnt_fu_hoy   = $db->query("SELECT COUNT(*) FROM dimark_prospectos WHERE fecha_followup <= CURDATE() AND estado NOT IN ('ganado','perdido') {$asesor_sql}")->fetchColumn();
?>
<div class="metrics-grid" style="margin-bottom:14px">
  <div class="metric"><div class="metric-n"><?=$cnt_total?></div><div class="metric-l">Total prospectos</div></div>
  <div class="metric"><div class="metric-n"><?=$cnt_activos?></div><div class="metric-l">Activos</div></div>
  <div class="metric"><div class="metric-n <?=$cnt_demos>0?'amber':''?>"><?=$cnt_demos?></div><div class="metric-l">En demo</div></div>
  <div class="metric"><div class="metric-n green"><?=$cnt_ganados?></div><div class="metric-l">Ganados</div></div>
  <div class="metric"><div class="metric-n red"><?=$cnt_perdidos?></div><div class="metric-l">Perdidos</div></div>
  <div class="metric"><div class="metric-n <?=$cnt_fu_hoy>0?'red':''?>"><?=$cnt_fu_hoy?></div><div class="metric-l">Follow-ups urgentes</div></div>
</div>
<?php
// Breakdowns globales (respetan filtro de asesor)
$por_sector = $db->query("SELECT sector, COUNT(*) as cnt FROM dimark_prospectos WHERE 1=1 {$asesor_sql} GROUP BY sector ORDER BY cnt DESC")->fetchAll();
$por_canal  = $db->query("SELECT canal,  COUNT(*) as cnt FROM dimark_prospectos WHERE 1=1 {$asesor_sql} GROUP BY canal  ORDER BY cnt DESC")->fetchAll();
$por_estado = $db->query("SELECT estado, COUNT(*) as cnt FROM dimark_prospectos WHERE 1=1 {$asesor_sql} GROUP BY estado ORDER BY cnt DESC")->fetchAll();
$max_s = max(array_merge([1], array_column($por_sector, 'cnt')));
$max_c = max(array_merge([1], array_column($por_canal,  'cnt')));
$max_e = max(array_merge([1], array_column($por_estado, 'cnt')));
$sector_labels = ['ecommerce'=>'🛒 Ecommerce','clinicas'=>'🏥 Clínicas / Salud','b2b'=>'⚙️ B2B Servicios','inmobiliarias'=>'🏢 Inmobiliarias','hoteles'=>'🏨 Hoteles / Turismo','restaurantes'=>'🍽️ Restaurantes','educacion'=>'🎓 Educación','retail'=>'👗 Retail / Moda','servicios'=>'⚙️ Servicios'];
$canal_labels  = ['whatsapp'=>'WhatsApp','meta_ads'=>'Meta Ads','linkedin'=>'LinkedIn','referidos'=>'Referidos','influencers'=>'Influencers','partnerships'=>'Partnerships','otro'=>'Otro'];
$estado_colors = ['prospecto'=>'#888780','contactado'=>'#888780','demo_agendada'=>'#BA7517','demo_realizada'=>'#185FA5','negociacion'=>'#BA7517','propuesta_enviada'=>'#534AB7','ganado'=>'#0F6E56','perdido'=>'#A32D2D'];
?>
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:14px">

  <!-- Por industria -->
  <div class="card" style="padding:12px 14px">
    <div class="section-label" style="margin:0 0 8px">Por industria</div>
    <?php foreach($por_sector as $row):
      $pct = round($row['cnt'] / $max_s * 100);
      $lbl = $sector_labels[$row['sector']] ?? $row['sector'];
    ?>
    <a href="prospectos.php?sector=<?=$row['sector']?>" style="text-decoration:none;display:block;margin-bottom:7px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:2px">
        <span style="font-size:12px;color:var(--text)"><?=$lbl?></span>
        <span style="font-size:12px;font-weight:600;color:var(--text)"><?=$row['cnt']?></span>
      </div>
      <div style="height:4px;background:var(--off);border-radius:2px;overflow:hidden">
        <div style="height:100%;width:<?=$pct?>%;background:#1D9E75;border-radius:2px"></div>
      </div>
    </a>
    <?php endforeach; ?>
    <?php if(empty($por_sector)): ?><p style="font-size:12px;color:var(--muted)">Sin datos</p><?php endif; ?>
  </div>

  <!-- Por canal -->
  <div class="card" style="padding:12px 14px">
    <div class="section-label" style="margin:0 0 8px">Por canal de origen</div>
    <?php foreach($por_canal as $row):
      $pct = round($row['cnt'] / $max_c * 100);
      $lbl = $canal_labels[$row['canal']] ?? $row['canal'];
    ?>
    <a href="prospectos.php?canal=<?=$row['canal']?>" style="text-decoration:none;display:block;margin-bottom:7px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:2px">
        <span style="font-size:12px;color:var(--text)"><?=$lbl?></span>
        <span style="font-size:12px;font-weight:600;color:var(--text)"><?=$row['cnt']?></span>
      </div>
      <div style="height:4px;background:var(--off);border-radius:2px;overflow:hidden">
        <div style="height:100%;width:<?=$pct?>%;background:#534AB7;border-radius:2px"></div>
      </div>
    </a>
    <?php endforeach; ?>
    <?php if(empty($por_canal)): ?><p style="font-size:12px;color:var(--muted)">Sin datos</p><?php endif; ?>
  </div>

  <!-- Por estado -->
  <div class="card" style="padding:12px 14px">
    <div class="section-label" style="margin:0 0 8px">Por estado</div>
    <?php foreach($por_estado as $row):
      $pct = round($row['cnt'] / $max_e * 100);
      $color = $estado_colors[$row['estado']] ?? '#888';
      $lbl = $estados[$row['estado']] ?? $row['estado'];
    ?>
    <a href="prospectos.php?estado=<?=$row['estado']?>" style="text-decoration:none;display:block;margin-bottom:7px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:2px">
        <span style="font-size:12px;color:var(--text)"><?=$lbl?></span>
        <span style="font-size:12px;font-weight:600;color:<?=$color?>"><?=$row['cnt']?></span>
      </div>
      <div style="height:4px;background:var(--off);border-radius:2px;overflow:hidden">
        <div style="height:100%;width:<?=$pct?>%;background:<?=$color?>;border-radius:2px"></div>
      </div>
    </a>
    <?php endforeach; ?>
    <?php if(empty($por_estado)): ?><p style="font-size:12px;color:var(--muted)">Sin datos</p><?php endif; ?>
  </div>

</div>
<?php
// Filtros
$where = ["estado != 'perdido'"];
$params = [];
if (!isAdmin()) { $where[] = 'asesor_id=?'; $params[] = $user['id']; }
if (!empty($_GET['sector'])) { $where[] = "sector=?"; $params[] = $_GET['sector']; }
if (!empty($_GET['canal']))  { $where[] = "canal=?";  $params[] = $_GET['canal']; }
if (!empty($_GET['estado'])) { $where[] = "estado=?"; $params[] = $_GET['estado']; }
if (!empty($_GET['q']))      { $where[] = "(empresa LIKE ? OR contacto LIKE ?)"; $params[] = "%{$_GET['q']}%"; $params[] = "%{$_GET['q']}%"; }
$sql = "SELECT * FROM dimark_prospectos WHERE ".implode(' AND ',$where)." ORDER BY fecha_followup ASC, created_at DESC";
$stmt = $db->prepare($sql); $stmt->execute($params);
$prospectos = $stmt->fetchAll();
// Cargar historial de etapas en un solo query para todos los prospectos visibles
$hist_by_p = [];
if (!empty($prospectos)) {
    $ids = implode(',', array_map('intval', array_column($prospectos, 'id')));
    try {
        $all_hist = $db->query("SELECT * FROM dimark_stage_history WHERE prospecto_id IN ($ids) ORDER BY prospecto_id, created_at ASC")->fetchAll();
        foreach ($all_hist as $h) $hist_by_p[$h['prospecto_id']][] = $h;
    } catch (Exception $e) {}
}
$sc_map = ['prospecto'=>'#888780','contactado'=>'#5B8FBF','demo_agendada'=>'#BA7517','demo_realizada'=>'#185FA5','negociacion'=>'#C77B2A','propuesta_enviada'=>'#534AB7','ganado'=>'#0F6E56','perdido'=>'#A32D2D'];
$sl_map = ['prospecto'=>'Prospecto','contactado'=>'Contactado','demo_agendada'=>'Demo ag.','demo_realizada'=>'Demo real.','negociacion'=>'Negoc.','propuesta_enviada'=>'Propuesta','ganado'=>'Ganado','perdido'=>'Perdido'];
?>
<!-- Filtros -->
<form method="GET" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
  <input type="text" name="q" placeholder="Buscar empresa o contacto..." value="<?= htmlspecialchars($_GET['q']??'') ?>" style="flex:1;min-width:180px;padding:7px 11px;border:0.5px solid var(--border2);border-radius:8px;font-size:13px">
  <select name="sector" style="padding:7px 10px;border:0.5px solid var(--border2);border-radius:8px;font-size:13px">
    <option value="">Todos los sectores</option>
    <?php foreach($sectores as $k=>$v): ?><option value="<?=$k?>" <?=($_GET['sector']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?>
  </select>
  <select name="canal" style="padding:7px 10px;border:0.5px solid var(--border2);border-radius:8px;font-size:13px">
    <option value="">Todos los canales</option>
    <?php foreach($canales as $k=>$v): ?><option value="<?=$k?>" <?=($_GET['canal']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?>
  </select>
  <select name="estado" style="padding:7px 10px;border:0.5px solid var(--border2);border-radius:8px;font-size:13px">
    <option value="">Todos los estados</option>
    <?php foreach($estados as $k=>$v): ?><option value="<?=$k?>" <?=($_GET['estado']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?>
  </select>
  <button type="submit" class="btn">Filtrar</button>
  <a href="prospectos.php" class="btn">Limpiar</a>
</form>
<div class="table-wrap">
<table>
<thead><tr>
  <th style="width:26%">Empresa</th><th style="width:12%">Sector</th><th style="width:12%">Canal</th>
  <th style="width:16%">Estado</th><th style="width:12%">Follow-up</th><th style="width:12%">Plan</th><th style="width:10%">Acción</th>
</tr></thead>
<tbody>
<?php foreach($prospectos as $p):
  $fu = $p['fecha_followup'];
  $dias = $fu ? (int)((strtotime(date('Y-m-d'))-strtotime($fu))/86400) : null;
  $fu_style = $dias !== null && $dias > 0 ? 'color:#A32D2D;font-weight:500' : ($dias === 0 ? 'color:#0F6E56;font-weight:500' : '');
  $fu_label = $fu ? ($dias===0?'Hoy':($dias>0?"Hace {$dias}d":date('d/m',strtotime($fu)))) : '—';
?>
<tr>
  <td><strong><?=clean($p['empresa'])?></strong><?php if($p['contacto']): ?><br><span style="font-size:11px;color:var(--muted)"><?=clean($p['contacto'])?></span><?php endif; ?></td>
  <td><?=$sectores[$p['sector']]??$p['sector']?></td>
  <td><span class="badge b-green" style="font-size:11px"><?=$canales[$p['canal']]??$p['canal']?></span></td>
  <td><span class="badge <?=$badge_est[$p['estado']]??'b-gray'?>"><?=$estados[$p['estado']]??$p['estado']?></span></td>
  <td style="<?=$fu_style?>"><?=$fu_label?></td>
  <td><?php if($p['plan_interes']): ?><span class="badge b-blue" style="font-size:11px"><?=ucfirst($p['plan_interes'])?></span><?php else: ?>—<?php endif; ?></td>
  <td style="display:flex;gap:4px">
    <?php if($p['telefono']): ?><a href="https://wa.me/<?=preg_replace('/\D/','',$p['telefono'])?>" target="_blank" class="btn" style="font-size:11px;padding:4px 8px;color:#0F6E56" title="WhatsApp"><i class="ti ti-brand-whatsapp"></i></a><?php endif; ?>
    <button onclick="toggleTL(<?=$p['id']?>)" class="btn" style="font-size:11px;padding:4px 8px;color:#534AB7" title="Ver tiempo por etapa"><i class="ti ti-clock"></i></button>
    <a href="prospectos.php?accion=ver&id=<?=$p['id']?>" class="btn" style="font-size:11px;padding:4px 8px"><i class="ti ti-pencil"></i></a>
    <form method="POST" style="display:inline" onsubmit="return confirm('¿Eliminar <?=addslashes(clean($p['empresa']))?> ?')">
      <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
      <input type="hidden" name="_accion" value="eliminar">
      <input type="hidden" name="id" value="<?=$p['id']?>">
      <button type="submit" class="btn" style="font-size:11px;padding:4px 8px;color:#A32D2D"><i class="ti ti-trash"></i></button>
    </form>
  </td>
</tr>
<tr id="tl-<?=$p['id']?>" style="display:none">
  <td colspan="7" style="background:#F7F6FF;padding:10px 16px 12px;border-bottom:0.5px solid var(--border)">
  <?php if(empty($hist_by_p[$p['id']])): ?>
    <span style="font-size:12px;color:var(--muted)">Sin historial aún — guarda un cambio de estado para comenzar a registrar.</span>
  <?php else:
    $ph = $hist_by_p[$p['id']];
    $tsecs = 0;
    foreach($ph as $hi=>$he){ $nxt=isset($ph[$hi+1])?strtotime($ph[$hi+1]['created_at']):time(); $tsecs+=max(0,$nxt-strtotime($he['created_at'])); }
    $td = floor($tsecs/86400);
    echo '<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">';
    echo '<span style="font-size:11px;color:#534AB7;font-weight:600;margin-right:4px">⏱ '.($td>0?"{$td} día".($td!==1?'s':'')." en pipeline":'Ingresó hoy').'</span>';
    foreach($ph as $hi=>$he):
      $nxt=isset($ph[$hi+1])?strtotime($ph[$hi+1]['created_at']):time();
      $s=max(0,$nxt-strtotime($he['created_at']));
      $d=floor($s/86400); $h=floor(($s%86400)/3600);
      $dur=$d>0?"{$d}d":($h>0?"{$h}h":'hoy');
      $is_cur=!isset($ph[$hi+1]);
      $ec=$sc_map[$he['estado']]??'#888'; $el=$sl_map[$he['estado']]??$he['estado'];
      if($hi>0) echo '<span style="color:var(--muted)">›</span>';
      echo "<span style=\"background:{$ec}15;color:{$ec};border:1px solid {$ec}40;border-radius:6px;padding:3px 9px;font-size:11px;font-weight:600;white-space:nowrap\">{$el} <span style=\"font-weight:400;opacity:.75\">".($is_cur?'en curso':$dur)."</span></span>";
    endforeach;
    echo '</div>';
  endif; ?>
  </td>
</tr>
<?php endforeach; ?>
<?php if(empty($prospectos)): ?>
<tr><td colspan="7" style="text-align:center;padding:2rem;color:var(--muted)">Sin prospectos. <a href="prospectos.php?nuevo=1" style="color:var(--black);text-decoration:underline">Agrega el primero →</a></td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
<script>function toggleTL(id){var r=document.getElementById('tl-'+id);r.style.display=(r.style.display==='none'||r.style.display==='')?'table-row':'none';}</script>

<?php else: // FORM nuevo / editar
$p = $editing ?? [];

// ── STEPPER: sólo si estamos editando un prospecto existente ────
if (isset($p['id'])):
    $stage_hist = [];
    try {
        $hist_stmt = $db->prepare("SELECT * FROM dimark_stage_history WHERE prospecto_id=? ORDER BY created_at ASC");
        $hist_stmt->execute([$p['id']]);
        $stage_hist = $hist_stmt->fetchAll();
    } catch (Exception $e) {}
    $stage_map  = [];
    foreach ($stage_hist as $i => $entry) {
        $nxt  = isset($stage_hist[$i+1]) ? strtotime($stage_hist[$i+1]['created_at']) : time();
        $secs = max(0, $nxt - strtotime($entry['created_at']));
        $d = floor($secs/86400); $h = floor(($secs%86400)/3600);
        $dur = $d > 0 ? "{$d}d" . ($h > 0 ? " {$h}h" : '') : ($h > 0 ? "{$h}h" : 'hoy');
        $stage_map[$entry['estado']] = ['fecha'=>$entry['created_at'],'duracion'=>$dur,'es_actual'=>!isset($stage_hist[$i+1]),'secs'=>$secs];
    }
    $total_secs  = array_sum(array_column($stage_map,'secs'));
    $total_days  = floor($total_secs/86400);
    $pipeline_lbl= $total_days > 0 ? "{$total_days} día".($total_days!==1?'s':'')." en pipeline" : "Menos de 1 día";
    $stage_colors_tl = ['prospecto'=>'#888780','contactado'=>'#5B8FBF','demo_agendada'=>'#BA7517',
        'demo_realizada'=>'#185FA5','negociacion'=>'#C77B2A','propuesta_enviada'=>'#534AB7',
        'ganado'=>'#0F6E56','perdido'=>'#A32D2D'];
    $stage_flow = ['prospecto','contactado','demo_agendada','demo_realizada','negociacion','propuesta_enviada','ganado'];
    if (($p['estado']??'') === 'perdido') $stage_flow[] = 'perdido';
    $short = ['prospecto'=>'Prospecto','contactado'=>'Contactado','demo_agendada'=>'Demo ag.',
        'demo_realizada'=>'Demo real.','negociacion'=>'Negoc.','propuesta_enviada'=>'Propuesta',
        'ganado'=>'Ganado','perdido'=>'Perdido'];
?>
<div style="max-width:700px;margin-bottom:16px">
  <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
    <span style="font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)">Recorrido del lead</span>
    <?php if(!empty($stage_hist)): ?><span style="font-size:12px;color:var(--muted)"><?=$pipeline_lbl?></span><?php endif; ?>
  </div>
  <div class="card" style="padding:16px 18px">
  <?php if(empty($stage_hist)): ?>
    <p style="font-size:12px;color:var(--muted);margin:0">Sin historial aún. Cada vez que cambies el estado del prospecto, quedará registrado aquí.</p>
  <?php else: ?>
    <div style="display:flex;align-items:flex-start;overflow-x:auto;padding-bottom:2px">
    <?php foreach($stage_flow as $idx => $s):
      $has   = isset($stage_map[$s]);
      $isCur = $has && $stage_map[$s]['es_actual'];
      $done  = $has && !$isCur;
      $col   = $stage_colors_tl[$s] ?? '#888';
      $lbl   = $short[$s] ?? $s;
    ?>
    <?php if($idx > 0): ?>
      <div style="flex-shrink:0;display:flex;align-items:center;padding:0 2px;margin-top:11px">
        <div style="width:18px;height:2px;border-radius:1px;background:<?=$has?$col:'var(--border2)'?>"></div>
      </div>
    <?php endif; ?>
    <div style="flex-shrink:0;text-align:center;min-width:66px">
      <div style="
        width:26px;height:26px;border-radius:50%;margin:0 auto 5px;
        display:flex;align-items:center;justify-content:center;
        font-size:<?=$done?'12':'11'?>px;font-weight:700;
        <?php if($isCur): echo "background:{$col};color:#fff;box-shadow:0 0 0 3px {$col}44;";
        elseif($done):    echo "background:{$col};color:#fff;";
        else:             echo "background:var(--off);color:var(--muted);border:1.5px solid var(--border2);"; endif; ?>
      ">
        <?= $done ? '✓' : ($isCur ? '●' : ($idx+1)) ?>
      </div>
      <div style="font-size:10px;font-weight:<?=$has?'600':'400'?>;color:<?=$has?$col:'var(--muted)'?>;line-height:1.3;margin-bottom:2px"><?=$lbl?></div>
      <?php if($isCur): ?>
        <div style="font-size:10px;font-weight:600;color:<?=$col?>">en curso</div>
        <div style="font-size:10px;color:var(--muted)"><?=$stage_map[$s]['duracion']?></div>
      <?php elseif($done): ?>
        <div style="font-size:10px;color:var(--muted)"><?=$stage_map[$s]['duracion']?></div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
    </div>
  <?php endif; ?>
  </div>
</div>
<?php endif; // fin stepper ?>

<form method="POST" style="max-width:700px">
  <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
  <input type="hidden" name="id" value="<?=intval($p['id']??0)?>">
  <div class="card" style="margin-bottom:12px">
    <div class="section-label" style="margin-top:0">Información de la empresa</div>
    <div class="form-row">
      <div class="form-group"><label>Empresa *</label><input type="text" name="empresa" value="<?=clean($p['empresa']??'')?>" required placeholder="Nombre del negocio"></div>
      <div class="form-group"><label>Sector *</label>
        <select name="sector"><?php foreach($sectores as $k=>$v): ?><option value="<?=$k?>" <?=($p['sector']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?></select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>Contacto</label><input type="text" name="contacto" value="<?=clean($p['contacto']??'')?>" placeholder="Nombre completo"></div>
      <div class="form-group"><label>Cargo</label><input type="text" name="cargo" value="<?=clean($p['cargo']??'')?>" placeholder="General Manager, CEO..."></div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>Teléfono / WhatsApp</label><input type="text" name="telefono" value="<?=clean($p['telefono']??'')?>" placeholder="+57 300 000 0000"></div>
      <div class="form-group"><label>Email</label><input type="email" name="email" value="<?=clean($p['email']??'')?>" placeholder="contacto@empresa.com"></div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>País</label><input type="text" name="pais" value="<?=clean($p['pais']??'')?>" placeholder="Colombia, México, España..."></div>
      <div class="form-group"><label>Ciudad</label><input type="text" name="ciudad" value="<?=clean($p['ciudad']??'')?>" placeholder="Bogotá, CDMX, Madrid..."></div>
    </div>
  </div>
  <div class="card" style="margin-bottom:12px">
    <div class="section-label" style="margin-top:0">Seguimiento comercial</div>
    <div class="form-row">
      <div class="form-group"><label>Canal de origen *</label>
        <select name="canal"><?php foreach($canales as $k=>$v): ?><option value="<?=$k?>" <?=($p['canal']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?></select>
      </div>
      <div class="form-group"><label>Estado *</label>
        <select name="estado"><?php foreach($estados as $k=>$v): ?><option value="<?=$k?>" <?=($p['estado']??'prospecto')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?></select>
      </div>
    </div>
    <div class="form-row">
      <div class="form-group"><label>Plan de interés</label>
        <select name="plan_interes"><?php foreach($planes as $k=>$v): ?><option value="<?=$k?>" <?=($p['plan_interes']??'')===$k?'selected':''?>><?=$v?></option><?php endforeach; ?></select>
      </div>
      <div class="form-group"><label>Fecha follow-up</label><input type="date" name="fecha_followup" value="<?=$p['fecha_followup']??''?>"></div>
    </div>
    <div class="form-group"><label>Próximo paso</label><input type="text" name="proximo_paso" value="<?=clean($p['proximo_paso']??'')?>" placeholder="Ej: Enviar propuesta, Agendar demo..."></div>
    <div class="form-group"><label>Notas</label><textarea name="notas" placeholder="Observaciones, contexto, intereses..."><?=clean($p['notas']??'')?></textarea></div>
  </div>
  <div style="display:flex;gap:10px">
    <button type="submit" class="btn btn-primary"><i class="ti ti-check"></i> <?=isset($p['id'])?'Actualizar':'Guardar'?> prospecto</button>
    <a href="prospectos.php" class="btn">Cancelar</a>
    <?php if(isset($p['id']) && $p['estado']!=='ganado'): ?>
    <form method="POST" style="display:inline;margin-left:auto" onsubmit="return confirm('¿Eliminar este prospecto?')">
      <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
      <input type="hidden" name="_accion" value="eliminar">
      <input type="hidden" name="id" value="<?=$p['id']?>">
      <button type="submit" class="btn" style="color:#A32D2D"><i class="ti ti-trash"></i> Eliminar</button>
    </form>
    <?php endif; ?>
  </div>
</form>

<?php if(isset($p['id'])): ?>
<?php
$acts = $db->prepare("SELECT a.*, u.nombre as asesor FROM dimark_actividades a LEFT JOIN dimark_usuarios u ON a.usuario_id=u.id WHERE a.prospecto_id=? ORDER BY a.created_at DESC");
$acts->execute([$p['id']]);
$actividades_log = $acts->fetchAll();
$tipo_icons  = ['contacto'=>'ti-phone','seguimiento'=>'ti-message','demo'=>'ti-presentation','propuesta'=>'ti-file-text','cierre'=>'ti-trophy','nota'=>'ti-note'];
$tipo_colors = ['contacto'=>'#185FA5','seguimiento'=>'#888780','demo'=>'#BA7517','propuesta'=>'#534AB7','cierre'=>'#0F6E56','nota'=>'#888780'];
?>
<div class="section-label" style="margin-top:18px">Historial de actividades</div>
<div class="card" style="max-width:700px">
  <form method="POST" style="display:flex;gap:8px;align-items:flex-end;margin-bottom:14px;flex-wrap:wrap">
    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
    <input type="hidden" name="_accion" value="actividad">
    <input type="hidden" name="prospecto_id" value="<?=$p['id']?>">
    <div class="form-group" style="margin:0;flex:0 0 150px">
      <label>Tipo</label>
      <select name="tipo">
        <option value="contacto">📞 Contacto</option>
        <option value="seguimiento">💬 Seguimiento</option>
        <option value="demo">📊 Demo</option>
        <option value="propuesta">📄 Propuesta</option>
        <option value="cierre">🏆 Cierre</option>
        <option value="nota">📝 Nota</option>
      </select>
    </div>
    <div class="form-group" style="margin:0;flex:1;min-width:200px">
      <label>Descripción</label>
      <input type="text" name="descripcion" required placeholder="Ej: Llamada 15 min, interesado en plan Confiado...">
    </div>
    <button type="submit" class="btn btn-primary" style="flex-shrink:0;margin-bottom:1px"><i class="ti ti-plus"></i> Registrar</button>
  </form>
  <?php if(empty($actividades_log)): ?>
    <p style="font-size:13px;color:var(--muted);text-align:center;padding:1rem 0">Sin actividades registradas aún.</p>
  <?php else: ?>
    <?php foreach($actividades_log as $act): ?>
    <div style="display:flex;gap:10px;padding:8px 0;border-bottom:0.5px solid var(--border)">
      <div style="width:28px;height:28px;border-radius:8px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:<?=$tipo_colors[$act['tipo']]??'#888'?>1A">
        <i class="ti <?=$tipo_icons[$act['tipo']]??'ti-note'?>" style="font-size:14px;color:<?=$tipo_colors[$act['tipo']]??'#888'?>"></i>
      </div>
      <div style="flex:1;min-width:0">
        <div style="font-size:13px"><?=clean($act['descripcion'])?></div>
        <div style="font-size:11px;color:var(--muted);margin-top:2px">
          <?=ucfirst($act['tipo'])?> · <?=date('d/m/Y H:i',strtotime($act['created_at']))?>
          <?php if($act['asesor']): ?> · <?=clean($act['asesor'])?><?php endif; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<?php endif; ?>

<?php endif; ?>

<?php require_once 'layout_end.php'; ?>
