<?php
require_once 'auth.php'; requireLogin();
$db   = getDB();
$user = currentUser();

$pasos_default = [
    'Acceso a cuentas publicitarias (Meta, Google)',
    'Configuración de píxeles y tracking',
    'Primera reunión de estrategia',
    'Entrega de activos del cliente (logos, fotos, copy)',
    'Lanzamiento de campañas iniciales',
    'Reporte de primera semana',
];

try {
    $db->exec("CREATE TABLE IF NOT EXISTS dimark_onboarding (
        id INT AUTO_INCREMENT PRIMARY KEY,
        cliente_id INT NOT NULL,
        paso VARCHAR(250) NOT NULL,
        orden TINYINT NOT NULL DEFAULT 0,
        completado TINYINT(1) DEFAULT 0,
        completado_at DATETIME,
        completado_por INT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch(Exception $e) {}

// ── TOGGLE PASO ────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_accion']??'') === 'toggle') {
    csrf_check();
    $id  = intval($_POST['id']);
    $cid = intval($_POST['cid']);
    $row = $db->prepare("SELECT completado FROM dimark_onboarding WHERE id=?"); $row->execute([$id]); $row = $row->fetch();
    if ($row) {
        if ($row['completado']) {
            $db->prepare("UPDATE dimark_onboarding SET completado=0, completado_at=NULL, completado_por=NULL WHERE id=?")->execute([$id]);
        } else {
            $db->prepare("UPDATE dimark_onboarding SET completado=1, completado_at=NOW(), completado_por=? WHERE id=?")->execute([$user['id'],$id]);
        }
    }
    header('Location: onboarding.php?cid='.$cid); exit;
}

$cid = intval($_GET['cid']??0);

// Auto-seed pasos por defecto si cliente no tiene pasos
if ($cid) {
    $cnt = $db->prepare("SELECT COUNT(*) FROM dimark_onboarding WHERE cliente_id=?");
    $cnt->execute([$cid]);
    if ((int)$cnt->fetchColumn() === 0) {
        foreach ($pasos_default as $i => $paso) {
            $db->prepare("INSERT INTO dimark_onboarding (cliente_id,paso,orden) VALUES (?,?,?)")
               ->execute([$cid, $paso, $i+1]);
        }
    }
}

$page_title    = 'Onboarding';
$page_subtitle = 'Checklist de incorporación de nuevos clientes';
require_once 'layout.php';

$clientes = $db->query("SELECT id, empresa FROM dimark_clientes ORDER BY empresa")->fetchAll();

// Resumen por cliente
$stmt_res = $db->query("SELECT cliente_id, COUNT(*) as total, SUM(completado) as hechos FROM dimark_onboarding GROUP BY cliente_id");
$resumen = [];
foreach ($stmt_res->fetchAll() as $r) $resumen[$r['cliente_id']] = $r;

$pasos = [];
if ($cid) {
    $s = $db->prepare("SELECT * FROM dimark_onboarding WHERE cliente_id=? ORDER BY orden ASC");
    $s->execute([$cid]); $pasos = $s->fetchAll();
}
?>

<!-- SELECTOR + RESUMEN -->
<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap">
  <form method="GET">
    <select name="cid" style="padding:8px 12px;border:0.5px solid var(--border2);border-radius:8px;font-family:inherit;font-size:13px;min-width:260px" onchange="this.form.submit()">
      <option value="">— Selecciona cliente —</option>
      <?php foreach($clientes as $c):
        $r = $resumen[$c['id']] ?? null;
        $pct = $r && $r['total'] > 0 ? round(100*$r['hechos']/$r['total']) : 0;
      ?>
      <option value="<?=$c['id']?>" <?=$cid==$c['id']?'selected':''?>>
        <?=clean($c['empresa'])?><?=$r ? " — {$pct}%" : ''?>
      </option>
      <?php endforeach; ?>
    </select>
  </form>
</div>

<!-- TABLA RESUMEN -->
<div class="section-label">Estado general</div>
<div class="table-wrap" style="margin-bottom:20px">
<table>
<thead><tr>
  <th style="width:38%">Cliente</th>
  <th style="width:34%">Progreso</th>
  <th style="width:14%">Estado</th>
  <th style="width:14%">Acción</th>
</tr></thead>
<tbody>
<?php foreach($clientes as $c):
  $r   = $resumen[$c['id']] ?? null;
  $tot = $r ? intval($r['total']) : 0;
  $hec = $r ? intval($r['hechos']) : 0;
  $pct = $tot > 0 ? round(100*$hec/$tot) : 0;
  $ok  = $tot > 0 && $hec >= $tot;
?>
<tr>
  <td style="font-weight:500"><?=clean($c['empresa'])?></td>
  <td>
    <?php if($tot > 0): ?>
    <div style="height:5px;background:var(--off);border-radius:3px;overflow:hidden;margin-bottom:3px">
      <div style="height:100%;width:<?=$pct?>%;background:<?=$ok?'#0F6E56':'var(--yellow)'?>;border-radius:3px"></div>
    </div>
    <span style="font-size:11px;color:var(--muted)"><?=$hec?>/<?=$tot?> pasos</span>
    <?php else: ?><span style="font-size:11px;color:var(--muted)">Sin pasos</span><?php endif; ?>
  </td>
  <td><span class="badge <?=$ok?'b-green':($pct>0?'b-amber':'b-gray')?>"><?=$ok?'Completo':($tot>0?"{$pct}%":'Pendiente')?></span></td>
  <td><a href="onboarding.php?cid=<?=$c['id']?>" class="btn" style="font-size:11px;padding:3px 8px"><i class="ti ti-eye"></i> Ver</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

<?php if ($cid && !empty($pasos)):
  $nombre_cli = $db->prepare("SELECT empresa FROM dimark_clientes WHERE id=?"); $nombre_cli->execute([$cid]); $nombre_cli = $nombre_cli->fetchColumn();
  $done  = count(array_filter($pasos, fn($p) => $p['completado']));
  $total = count($pasos);
  $pct   = round(100*$done/$total);
?>
<div class="section-label">Checklist — <?=clean($nombre_cli)?></div>
<div style="height:8px;background:var(--off);border-radius:4px;overflow:hidden;margin-bottom:16px;max-width:500px">
  <div style="height:100%;width:<?=$pct?>%;background:<?=$pct>=100?'#0F6E56':'var(--yellow)'?>;border-radius:4px;transition:width .4s"></div>
</div>
<div class="card" style="padding:0;overflow:hidden">
<?php foreach($pasos as $p): ?>
<div style="display:flex;align-items:center;gap:12px;padding:13px 16px;border-bottom:0.5px solid var(--border)">
  <form method="POST" style="flex-shrink:0">
    <input type="hidden" name="_csrf" value="<?=csrf_token()?>">
    <input type="hidden" name="_accion" value="toggle">
    <input type="hidden" name="id" value="<?=$p['id']?>">
    <input type="hidden" name="cid" value="<?=$cid?>">
    <button type="submit" style="width:20px;height:20px;border-radius:50%;border:2px solid <?=$p['completado']?'#0F6E56':'var(--border2)'?>;background:<?=$p['completado']?'#0F6E56':'#fff'?>;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0">
      <?php if($p['completado']): ?><i class="ti ti-check" style="font-size:10px;color:#fff"></i><?php endif; ?>
    </button>
  </form>
  <div style="flex:1">
    <div style="font-size:13px;font-weight:500;<?=$p['completado']?'text-decoration:line-through;color:var(--muted)':''?>"><?=clean($p['paso'])?></div>
    <?php if($p['completado'] && $p['completado_at']): ?>
    <div style="font-size:11px;color:var(--muted)">Completado <?=date('d/m/Y',strtotime($p['completado_at']))?></div>
    <?php endif; ?>
  </div>
  <span style="width:20px;height:20px;border-radius:50%;background:var(--off);display:flex;align-items:center;justify-content:center;font-size:11px;color:var(--muted);font-weight:600;flex-shrink:0"><?=$p['orden']?></span>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

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