yazrkisvs3vvvsv33svrhetrjsvyvsvvyjsvsvs
tavsuysvssvvjvvyjyjkvsvqd
qfogsvvsvsegjdgdfgdskhgdksvqsvshdqsd
<?php
// importar.php
$page_title    = 'Importar desde Excel';
$page_subtitle = 'Carga el archivo DIMARK_Seguimiento_Comercial_2026.xlsx';
require_once 'layout.php';
$db = getDB();

$msg = '';
$msg_type = '';

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_FILES['excel'])) {
    $file = $_FILES['excel'];
    if ($file['error'] === 0 && pathinfo($file['name'], PATHINFO_EXTENSION) === 'xlsx') {
        // Usar PhpSpreadsheet si está disponible, si no dar instrucción manual
        if (class_exists('\PhpOffice\PhpSpreadsheet\IOFactory')) {
            try {
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
                $imported = 0;
                // Hoja Prospectos (índice 1 = segunda hoja)
                if ($spreadsheet->getSheetCount() > 1) {
                    $sheet = $spreadsheet->getSheet(1);
                    $rows = $sheet->toArray(null, true, true, true);
                    foreach (array_slice($rows, 7) as $row) { // fila 7 en adelante (datos)
                        $empresa = trim($row['B'] ?? '');
                        if (!$empresa) continue;
                        $sector_map = ['🏨 Hoteles'=>'hoteles','🏥 Clínicas'=>'clinicas','🏢 Inmobiliarias'=>'inmobiliarias','🛒 Ecommerce'=>'ecommerce','⚙️ Servicios'=>'servicios'];
                        $canal_map  = ['Outbound WhatsApp'=>'whatsapp','Meta Ads'=>'meta_ads','LinkedIn'=>'linkedin','Referidos'=>'referidos','Influencers'=>'influencers','Partnerships'=>'partnerships'];
                        $sector = $sector_map[$row['C']??''] ?? 'servicios';
                        $canal  = $canal_map[$row['F']??''] ?? 'whatsapp';
                        $estado_map = ['Primer contacto'=>'contactado','Seguimiento'=>'contactado','Demo agendada'=>'demo_agendada','Demo realizada'=>'demo_realizada','En negociación'=>'negociacion','Propuesta enviada'=>'propuesta_enviada','Cliente activo'=>'ganado','Descartado'=>'perdido'];
                        $estado = $estado_map[$row['G']??''] ?? 'contactado';
                        $db->prepare("INSERT IGNORE INTO dimark_prospectos (empresa,contacto,cargo,telefono,email,sector,canal,estado,notas,fecha_followup,asesor_id) VALUES (?,?,?,?,?,?,?,?,?,?,1)")
                           ->execute([$empresa,trim($row['D']??''),trim($row['E']??''),'','',  $sector,$canal,$estado,trim($row['M']??''),null]);
                        $imported++;
                    }
                }
                $msg = "✓ Importación completada: {$imported} prospectos importados.";
                $msg_type = 'success';
            } catch (Exception $e) {
                $msg = "Error al leer el archivo: ".$e->getMessage();
                $msg_type = 'danger';
            }
        } else {
            $msg = "PhpSpreadsheet no está instalado. Ejecuta: composer require phpoffice/phpspreadsheet en el servidor.";
            $msg_type = 'warn';
        }
    } else {
        $msg = "Por favor sube un archivo .xlsx válido.";
        $msg_type = 'danger';
    }
}

$pestanas = [
    ['icon'=>'ti-users','nombre'=>'🤝 Prospectos','destino'=>'Tabla prospectos + pipeline'],
    ['icon'=>'ti-circle-check','nombre'=>'✅ Clientes activos','destino'=>'Tabla clientes'],
    ['icon'=>'ti-gift','nombre'=>'🎁 Referidos','destino'=>'Tabla referidos'],
    ['icon'=>'ti-star','nombre'=>'🌟 Influencers','destino'=>'Tabla influencers'],
    ['icon'=>'ti-building','nombre'=>'🤝 Aliados','destino'=>'Tabla aliados'],
];
?>

<?php if($msg): ?>
<div class="alert alert-<?=$msg_type?>" style="margin-bottom:14px"><i class="ti ti-info-circle"></i> <?=htmlspecialchars($msg)?></div>
<?php endif; ?>

<div class="alert alert-warn" style="margin-bottom:14px">
  <i class="ti ti-info-circle"></i>
  Requiere <strong>PhpSpreadsheet</strong>. Instalar en el servidor con: <code style="background:rgba(0,0,0,.08);padding:2px 6px;border-radius:4px">composer require phpoffice/phpspreadsheet</code>
</div>

<form method="POST" enctype="multipart/form-data" style="max-width:600px">
  <div style="background:var(--off);border:1.5px dashed var(--border2);border-radius:12px;padding:2.5rem;text-align:center;margin-bottom:14px">
    <i class="ti ti-file-spreadsheet" style="font-size:36px;color:var(--muted);display:block;margin-bottom:10px"></i>
    <p style="font-size:14px;font-weight:500;margin-bottom:4px">Arrastra el archivo Excel aquí</p>
    <p style="font-size:12px;color:var(--muted);margin-bottom:14px">DIMARK_Seguimiento_Comercial_2026.xlsx</p>
    <input type="file" name="excel" accept=".xlsx" required style="display:none" id="file-input">
    <label for="file-input" class="btn btn-primary" style="cursor:pointer"><i class="ti ti-upload"></i> Seleccionar archivo</label>
    <span id="file-name" style="font-size:12px;color:var(--muted);display:block;margin-top:8px"></span>
  </div>
  <button type="submit" class="btn btn-primary" style="margin-bottom:16px"><i class="ti ti-database-import"></i> Importar datos</button>
</form>

<div class="section-label">Pestañas que se importan</div>
<div class="table-wrap">
<table>
<thead><tr><th style="width:35%">Pestaña del Excel</th><th style="width:40%">Se importa a</th><th style="width:25%">Estado</th></tr></thead>
<tbody>
<?php foreach($pestanas as $p): ?>
<tr>
  <td><i class="ti <?=$p['icon']?>" style="font-size:14px;vertical-align:-2px;margin-right:6px"></i><?=htmlspecialchars($p['nombre'])?></td>
  <td><?=htmlspecialchars($p['destino'])?></td>
  <td><span class="badge b-gray">Esperando archivo</span></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

<script>
document.getElementById('file-input').addEventListener('change',function(){
  document.getElementById('file-name').textContent = this.files[0]?.name ?? '';
});
</script>

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