<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}
$page_title = 'Leads - Vale';
$statusLabels = ['new' => 'Nuevo', 'qualified' => 'Calificado', 'booked' => 'Agendado', 'won' => 'Ganado', 'lost' => 'Perdido'];
$statusColors = [
    'new' => ['bg' => 'rgba(224,163,62,.18)', 'fg' => '#9a6a14'],
    'qualified' => ['bg' => 'rgba(34,28,24,.08)', 'fg' => '#555'],
    'booked' => ['bg' => 'rgba(30,122,77,.15)', 'fg' => '#1E7A4D'],
    'won' => ['bg' => 'rgba(30,122,77,.2)', 'fg' => '#1E7A4D'],
    'lost' => ['bg' => 'rgba(192,57,43,.12)', 'fg' => '#C0392B'],
];
ob_start();
?>
<div class="dashboard-container">
    <?php $activeNav = 'clientes'; require __DIR__ . '/partials/sidebar.php'; ?>

    <main class="main-content">
        <?php if (!empty($_SESSION['impersonated_by_admin'])): ?>
            <div style="background:#E0A33E;color:#221C18;padding:.5rem 1rem;font-size:.85rem;display:flex;justify-content:space-between;align-items:center;">
                <span>Estás viendo como <strong><?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'negocio'); ?></strong> (impersonación de admin).</span>
                <a href="/admin/stop-impersonate" style="color:#A8331A;font-weight:600;">Salir de impersonación</a>
            </div>
        <?php endif; ?>
        <header class="header-bar">
            <h2>Clientes</h2>
            <div class="tenant-badge"><?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'Negocio'); ?></div>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 1rem;">
            <?php if (!empty($flash)): ?>
                <div class="alert" style="background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);"><?php echo htmlspecialchars($flash); ?></div>
            <?php endif; ?>

            <!-- Resumen por estado -->
            <div style="display:flex;gap:.75rem;flex-wrap:wrap;margin-bottom:1.5rem;">
                <?php foreach ($statusLabels as $key => $lbl): ?>
                    <div style="background:#fff;border:1px solid var(--color-border);border-radius:10px;padding:.75rem 1.1rem;min-width:96px;box-shadow:var(--shadow-soft);">
                        <div style="font-family:var(--font-headings);font-size:1.5rem;font-weight:600;color:<?php echo $statusColors[$key]['fg']; ?>;"><?php echo (int) $counts[$key]; ?></div>
                        <div style="font-size:.75rem;color:var(--color-text-muted);text-transform:uppercase;letter-spacing:.04em;"><?php echo $lbl; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if (empty($leads)): ?>
                <div class="chat-empty" style="height:48vh;">
                    <svg style="width:56px;height:56px;color:var(--color-border);margin-bottom:1.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a4 4 0 00-3-3.87M9 20H4v-2a4 4 0 013-3.87m6-1a4 4 0 10-8 0 4 4 0 008 0zm6-3a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                    <h3>Todavía no hay leads</h3>
                    <p>Cuando Vale capture un cliente interesado (por WhatsApp o web), aparecerá acá.</p>
                </div>
            <?php else: ?>
                <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;margin:0 -1rem;padding:0 1rem;">
                <table style="width:100%;min-width:580px;border-collapse:collapse;background:#FFF;border-radius:12px;overflow:hidden;box-shadow:var(--shadow-soft);font-size:.9rem;">
                    <thead>
                        <tr style="background:var(--color-tierra);color:#FFF;text-align:left;">
                            <th style="padding:.85rem 1rem;">Cliente</th>
                            <th style="padding:.85rem 1rem;">Canal</th>
                            <th style="padding:.85rem 1rem;">Estado</th>
                            <th style="padding:.85rem 1rem;">Valor est.</th>
                            <th style="padding:.85rem 1rem;">Fecha</th>
                            <th style="padding:.85rem 1rem;">Cambiar estado</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($leads as $lead): ?>
                            <?php
                                $c = $statusColors[$lead['status']] ?? $statusColors['new'];
                                $hasProfile = !empty($lead['cp_email']) || !empty($lead['cp_birthday']) || !empty($lead['cp_notes']) || !empty($lead['cp_preferences']);
                                $prefs = $hasProfile && !empty($lead['cp_preferences']) ? (json_decode($lead['cp_preferences'], true) ?: []) : [];
                                $rowId = 'prof-' . (int) $lead['id'];
                            ?>
                            <tr style="border-top:1px solid var(--color-border);">
                                <td style="padding:.85rem 1rem;">
                                    <div style="display:flex;align-items:center;gap:.5rem;">
                                        <a href="/clientes/<?php echo (int)$lead['contact_id']; ?>" style="font-weight:600;color:var(--color-tierra);text-decoration:none;" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'"><?php echo htmlspecialchars($lead['contact_name'] ?: $lead['contact_phone'] ?: 'Cliente'); ?></a>
                                        <?php if ($hasProfile): ?>
                                            <button onclick="document.getElementById('<?php echo $rowId; ?>').classList.toggle('hidden-row')" title="Ver perfil" style="background:rgba(30,122,77,.12);border:none;border-radius:20px;padding:.15rem .5rem;font-size:.72rem;color:#1E7A4D;cursor:pointer;white-space:nowrap;">Perfil ↓</button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td style="padding:.85rem 1rem;color:var(--color-text-muted);"><?php echo htmlspecialchars(ucfirst($lead['contact_channel'] ?? '')); ?></td>
                                <td style="padding:.85rem 1rem;">
                                    <span class="badge" style="background:<?php echo $c['bg']; ?>;color:<?php echo $c['fg']; ?>;"><?php echo htmlspecialchars($statusLabels[$lead['status']] ?? $lead['status']); ?></span>
                                </td>
                                <td style="padding:.85rem 1rem;"><?php echo $lead['value_estimate'] !== null ? '$' . number_format($lead['value_estimate'], 0) : '—'; ?></td>
                                <td style="padding:.85rem 1rem;white-space:nowrap;color:var(--color-text-muted);"><?php echo htmlspecialchars(date('d/m/Y', strtotime($lead['created_at']))); ?></td>
                                <td style="padding:.6rem 1rem;">
                                    <form method="POST" action="/leads" style="display:flex;gap:.4rem;align-items:center;">
                                        <input type="hidden" name="lead_id" value="<?php echo (int) $lead['id']; ?>">
                                        <select name="status" style="padding:.3rem .5rem;border:1px solid var(--color-border);border-radius:6px;font-size:.8rem;">
                                            <?php foreach ($statusLabels as $sk => $sl): ?>
                                                <option value="<?php echo $sk; ?>" <?php echo $lead['status'] === $sk ? 'selected' : ''; ?>><?php echo $sl; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="submit" style="padding:.3rem .6rem;font-size:.8rem;border:none;border-radius:6px;background:var(--color-barro);color:#fff;cursor:pointer;">Guardar</button>
                                    </form>
                                </td>
                            </tr>
                            <?php if ($hasProfile): ?>
                            <tr id="<?php echo $rowId; ?>" class="hidden-row" style="background:rgba(30,122,77,.04);">
                                <td colspan="6" style="padding:.75rem 1rem .75rem 2.5rem;">
                                    <div style="display:flex;flex-wrap:wrap;gap:1.5rem;font-size:.85rem;">
                                        <?php if (!empty($lead['cp_email'])): ?>
                                            <div><span style="color:var(--color-text-muted);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;">Email</span><br><?php echo htmlspecialchars($lead['cp_email']); ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($lead['cp_birthday'])): ?>
                                            <div><span style="color:var(--color-text-muted);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;">Cumpleaños</span><br><?php echo htmlspecialchars($lead['cp_birthday']); ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($lead['cp_notes'])): ?>
                                            <div style="max-width:340px;"><span style="color:var(--color-text-muted);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;">Notas</span><br><?php echo nl2br(htmlspecialchars($lead['cp_notes'])); ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($prefs)): ?>
                                            <div>
                                                <span style="color:var(--color-text-muted);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;">Preferencias</span><br>
                                                <div style="display:flex;flex-wrap:wrap;gap:.3rem;margin-top:.25rem;">
                                                    <?php foreach ($prefs as $k => $v): ?>
                                                        <span style="background:rgba(30,122,77,.1);color:#1E7A4D;border-radius:20px;padding:.15rem .55rem;font-size:.78rem;"><?php echo htmlspecialchars(str_replace('_',' ',$k)); ?>: <?php echo htmlspecialchars($v); ?></span>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            <?php endif; ?>
        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
// CSS para perfil expandible
$content .= '<style>.hidden-row{display:none !important;}</style>';
require dirname(__DIR__) . '/views/layout.php';
