<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = htmlspecialchars($contact['name'] ?: 'Cliente') . ' — Vale';

$avatarPalette = ['#A8392A','#C0784A','#1E7A4D','#2E6BA8','#7B4EA6','#B07D2E'];
$nameParts  = array_filter(explode(' ', trim($contact['name'] ?? '')));
$initials   = strtoupper(implode('', array_map(fn($w) => $w[0], array_slice($nameParts, 0, 2)))) ?: '?';
$avatarColor= $avatarPalette[abs(crc32($contact['name'] ?? 'x')) % count($avatarPalette)];

$apptLabel = ['scheduled'=>'Agendado','booked'=>'Agendado','completed'=>'Completado','cancelled'=>'Cancelado','no_show'=>'No asistió'];
$apptDot   = ['scheduled'=>'#1E7A4D','booked'=>'#1E7A4D','completed'=>'#888','cancelled'=>'#C0392B','no_show'=>'#C0392B'];

$totalCitas = count($appointments);
$lastAppt   = $totalCitas ? $appointments[0] : null;

ob_start();
?>
<style>
:root{--rust:#A8392A;--rust-soft:#c9785f;--ink:#33302B;--muted:#897D70;--cream:#F4ECE0;--d2:#0c0a08;--r:18px;}

/* ── Scroll area ── */
.cp-wrap{flex:1;overflow-y:auto;padding:14px 16px 110px;background:linear-gradient(180deg,var(--d2) 0%,#2a1c15 38%,#5b2e22 100%)}

/* ── Back link ── */
.cp-back{display:inline-flex;align-items:center;gap:6px;color:#c2b3a6;text-decoration:none;font-size:13px;font-weight:600;margin-bottom:14px}
.cp-back:hover{color:#fff}

/* ── Hero card ── */
.cp-hero{border:1px solid var(--rust-soft);border-radius:var(--r);background:rgba(0,0,0,.18);padding:22px 18px 18px;margin-bottom:12px;display:flex;flex-direction:column;align-items:center;text-align:center}
.cp-av{width:72px;height:72px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-family:'Fraunces',serif;font-size:28px;font-weight:700;color:#fff;margin-bottom:12px;flex-shrink:0}
.cp-name{font-family:'Fraunces',serif;font-size:22px;font-weight:700;color:#fff;margin:0 0 8px;line-height:1.2}
.cp-pills{display:flex;flex-wrap:wrap;gap:6px;justify-content:center;margin-bottom:14px}
.cp-pill{font-size:12px;color:#c2b3a6;background:rgba(255,255,255,.09);border-radius:20px;padding:4px 10px;font-weight:500}
.cp-pill.hi{background:rgba(168,57,42,.22);color:#f5b39e}
.btn-vale{display:flex;align-items:center;justify-content:center;gap:8px;background:var(--rust);color:#fff;border:none;border-radius:12px;padding:11px 18px;font-size:14px;font-weight:700;text-decoration:none;cursor:pointer;width:100%;font-family:inherit;transition:opacity .15s}
.btn-vale:hover{opacity:.88}

/* ── Form section ── */
.cp-section-title{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.16em;color:#c2b3a6;margin:0 0 12px}
.cp-card{background:var(--cream);border-radius:16px;padding:16px 16px 4px;margin-bottom:12px}
.cp-field{margin-bottom:14px}
.cp-field label{font-size:11.5px;font-weight:700;color:var(--muted);display:block;margin-bottom:5px;text-transform:uppercase;letter-spacing:.05em}
.cp-inp{width:100%;box-sizing:border-box;border:1.5px solid #ddd4c8;border-radius:10px;padding:11px 14px;font-size:15px;font-family:inherit;color:var(--ink);background:#fff;-webkit-appearance:none;transition:border .15s}
.cp-inp:focus{outline:none;border-color:var(--rust)}
.cp-notes{width:100%;box-sizing:border-box;border:1.5px solid #ddd4c8;border-radius:10px;padding:11px 14px;font-size:15px;font-family:inherit;color:var(--ink);background:#fff;resize:vertical;min-height:120px;-webkit-appearance:none;transition:border .15s}
.cp-notes:focus{outline:none;border-color:var(--rust)}

/* ── Pref chips ── */
.pref-chip{display:inline-flex;align-items:center;gap:5px;background:rgba(168,57,42,.12);color:var(--rust);border-radius:20px;padding:5px 11px;font-size:13px;margin:0 4px 6px 0}
.pref-chip button{background:none;border:none;color:var(--rust);cursor:pointer;padding:0;font-size:14px;line-height:1;opacity:.65}
.pref-chip button:hover{opacity:1}
.pref-add{display:flex;gap:8px;margin-top:6px;align-items:center}
.pref-add input{flex:1;min-width:40px;border:1.5px solid #ddd4c8;border-radius:9px;padding:8px 10px;font-size:13px;font-family:inherit;background:#fff;color:var(--ink)}
.pref-add input:focus{outline:none;border-color:var(--rust)}
.btn-ghost{padding:8px 12px;font-size:13px;font-weight:700;border:1.5px solid #ddd4c8;border-radius:9px;background:#fff;color:var(--ink);cursor:pointer;flex-shrink:0}

/* ── Save button ── */
.btn-save{width:100%;padding:14px;background:var(--rust);color:#fff;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;margin-bottom:14px;font-family:inherit;transition:opacity .15s}
.btn-save:hover{opacity:.88}

/* ── Historial ── */
.cp-hist{border:1px solid var(--rust-soft);border-radius:var(--r);padding:15px 18px;background:rgba(0,0,0,.18);margin-bottom:12px}
.cp-hist h3{margin:0 0 12px;color:#fff;font:600 15px/1 'Hanken Grotesk'}
.tl-item{display:flex;align-items:flex-start;gap:12px;padding:10px 0;border-top:1px solid rgba(255,255,255,.1)}
.tl-item:first-of-type{border-top:0;padding-top:0}
.tl-dot{width:11px;height:11px;border-radius:50%;flex-shrink:0;margin-top:3px}
.tl-body{flex:1}
.tl-date{font-size:11.5px;color:#a8978a;margin-bottom:3px}
.tl-svc{font-size:14px;font-weight:600;color:#efe6dc;margin-bottom:4px}
.tl-badge{display:inline-block;border-radius:20px;padding:3px 10px;font-size:11.5px;font-weight:600}

/* ── Flash ── */
.cp-flash{background:rgba(31,168,85,.15);color:#7ddba0;border:1px solid rgba(31,168,85,.25);border-radius:10px;padding:10px 14px;margin-bottom:12px;font-size:14px}

/* ── Desktop fallback ── */
@media(min-width:769px){
  .cp-wrap{padding:24px 32px 40px;max-width:820px}
  .cp-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
  .cp-grid-full{grid-column:1/-1}
}
</style>

<div class="dashboard-container">
    <?php $activeNav = 'negocio'; 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;">
                <span>Viendo como <strong><?= htmlspecialchars($_SESSION['tenant_name'] ?? '') ?></strong></span>
                <a href="/admin/stop-impersonate" style="color:#A8331A;font-weight:600;">Salir</a>
            </div>
        <?php endif; ?>

        <div class="cp-wrap">
            <a href="/clientes" class="cp-back">
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
                Clientes
            </a>

            <?php if ($flash): ?>
                <div class="cp-flash" id="cp-flash"><?= htmlspecialchars($flash) ?></div>
                <script>setTimeout(function(){var t=document.getElementById('cp-flash');if(t){t.style.opacity='0';t.style.transition='opacity .4s';setTimeout(function(){t.remove()},400)}},3000)</script>
            <?php endif; ?>

            <!-- Hero -->
            <div class="cp-hero">
                <div class="cp-av" style="background:<?= $avatarColor ?>"><?= $initials ?></div>
                <h1 class="cp-name"><?= htmlspecialchars($contact['name'] ?: '(Sin nombre)') ?></h1>
                <div class="cp-pills">
                    <?php if (!empty($contact['phone'])): ?>
                        <span class="cp-pill">📞 <?= htmlspecialchars($contact['phone']) ?></span>
                    <?php endif; ?>
                    <?php if (!empty($profile['email'])): ?>
                        <span class="cp-pill">✉ <?= htmlspecialchars($profile['email']) ?></span>
                    <?php endif; ?>
                    <span class="cp-pill"><?= htmlspecialchars(ucfirst($contact['channel'] ?? 'web')) ?></span>
                    <span class="cp-pill">Desde <?= date('d/m/Y', strtotime($contact['created_at'])) ?></span>
                    <?php if ($lastAppt): ?>
                        <span class="cp-pill">Última cita <?= date('d/m/Y', strtotime($lastAppt['scheduled_at'])) ?></span>
                    <?php endif; ?>
                    <?php if ($totalCitas > 0): ?>
                        <span class="cp-pill hi"><?= $totalCitas ?> cita<?= $totalCitas !== 1 ? 's' : '' ?></span>
                    <?php endif; ?>
                </div>
                <a href="/negocio/chat" class="btn-vale">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                    Preguntarle a Vale sobre este cliente
                </a>
            </div>

            <!-- Form -->
            <form method="POST" action="/clientes/<?= (int)$contact_id ?>">
                <input type="hidden" name="action" value="save_all">

                <div class="cp-grid">
                    <!-- Datos de contacto -->
                    <div class="cp-card">
                        <p class="cp-section-title">Datos de contacto</p>
                        <div class="cp-field">
                            <label>Teléfono</label>
                            <input class="cp-inp" type="tel" name="phone" value="<?= htmlspecialchars($contact['phone'] ?? '') ?>" placeholder="+505 8888-8888">
                        </div>
                        <div class="cp-field">
                            <label>Email</label>
                            <input class="cp-inp" type="email" name="email" value="<?= htmlspecialchars($profile['email'] ?? '') ?>" placeholder="correo@ejemplo.com">
                        </div>
                        <div class="cp-field">
                            <label>Cumpleaños</label>
                            <input class="cp-inp" type="date" name="birthday" value="<?= htmlspecialchars($profile['birthday'] ?? '') ?>">
                        </div>
                    </div>

                    <!-- Notas -->
                    <div class="cp-card">
                        <p class="cp-section-title">Notas del expediente</p>
                        <div class="cp-field">
                            <textarea name="notes" class="cp-notes" placeholder="Ej: prefiere turnos de mañana, alergia al látex, lo refirió Ana..."><?= htmlspecialchars($profile['notes'] ?? '') ?></textarea>
                        </div>
                    </div>

                    <!-- Preferencias -->
                    <div class="cp-card cp-grid-full">
                        <p class="cp-section-title">Preferencias</p>
                        <?php if (!empty($prefs)): ?>
                            <div style="margin-bottom:8px">
                                <?php foreach ($prefs as $k => $v): ?>
                                    <span class="pref-chip">
                                        <span><?= htmlspecialchars(str_replace('_',' ',$k)) ?>: <strong><?= htmlspecialchars($v) ?></strong></span>
                                        <form method="POST" action="/clientes/<?= (int)$contact_id ?>" style="margin:0;display:inline">
                                            <input type="hidden" name="action" value="del_pref">
                                            <input type="hidden" name="pref_key" value="<?= htmlspecialchars($k) ?>">
                                            <button type="submit" title="Eliminar">×</button>
                                        </form>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p style="font-size:13px;color:var(--muted);margin:0 0 10px;line-height:1.5">Vale captura preferencias automáticamente en cada conversación.</p>
                        <?php endif; ?>
                        <form method="POST" action="/clientes/<?= (int)$contact_id ?>">
                            <input type="hidden" name="action" value="save_pref">
                            <div class="pref-add">
                                <input type="text" name="pref_key" placeholder="clave">
                                <input type="text" name="pref_val" placeholder="valor">
                                <button type="submit" class="btn-ghost">+</button>
                            </div>
                        </form>
                    </div>
                </div>

                <button type="submit" class="btn-save">Guardar cambios</button>
            </form>

            <!-- Historial -->
            <div class="cp-hist" id="historial">
                <h3>Historial de citas (<?= $totalCitas ?>)</h3>
                <?php if (empty($appointments)): ?>
                    <p style="color:#c2b3a6;font-size:13.5px;margin:0;padding:4px 0 6px">Sin citas registradas todavía.</p>
                <?php else: ?>
                    <?php foreach ($appointments as $a):
                        $dot   = $apptDot[$a['status']] ?? '#888';
                        $label = $apptLabel[$a['status']] ?? $a['status'];
                        $rgb   = sscanf($dot, '#%02x%02x%02x') ?: [136,136,136];
                    ?>
                    <div class="tl-item">
                        <div class="tl-dot" style="background:<?= $dot ?>;box-shadow:0 0 0 3px <?= $dot ?>28"></div>
                        <div class="tl-body">
                            <div class="tl-date"><?= date('d/m/Y · H:i', strtotime($a['scheduled_at'])) ?></div>
                            <div class="tl-svc"><?= htmlspecialchars($a['service_name'] ?? '—') ?></div>
                            <span class="tl-badge" style="background:rgba(<?= implode(',',$rgb) ?>,.15);color:<?= $dot ?>"><?= $label ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/views/layout.php';
