<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

$page_title  = 'Mi negocio · Vale';
$bizName     = $tenant['name']           ?? $_SESSION['tenant_name'] ?? 'Mi negocio';
$direccion   = $tenant['direccion']      ?? '';
$telefono    = $tenant['telefono']       ?? '';
$descripcion = $tenant['descripcion']    ?? '';
$rubro       = $tenant['rubro']          ?? $tenant['business_type'] ?? '';
$ciudad      = $tenant['ciudad']         ?? '';
$logoUrl     = $tenant['logo_url']       ?? '';
$bannerUrl   = $tenant['banner_url']     ?? '';
$colorP      = $tenant['color_primario'] ?? '#A23D2C';
$colorA      = $tenant['color_acento']   ?? '#DDA02C';
$monogram    = mb_strtoupper(mb_substr($bizName, 0, 1, 'UTF-8'));
$publicSlug  = $tenant['public_slug']    ?? '';

$extra_head = <<<'CSS'
<style>
.ng-section{background:#fff;border:1px solid var(--color-border);border-radius:14px;padding:1.5rem;margin-bottom:1.25rem;box-shadow:var(--shadow-soft)}
.ng-section-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:1.1rem}
.ng-section-head h3{margin:0;font-size:1.15rem}
.ng-ask-vale{display:inline-flex;align-items:center;gap:7px;background:var(--color-barro);color:#fff;border:none;border-radius:9px;padding:8px 16px;font-family:var(--font-body);font-size:.9rem;font-weight:600;cursor:pointer;transition:background .15s}
.ng-ask-vale:hover{background:var(--color-barro-hover)}
.ng-toggle-form{font-size:.8rem;color:var(--color-text-muted);cursor:pointer;text-decoration:underline;background:none;border:none;font-family:var(--font-body)}
.svc-list{list-style:none;display:flex;flex-direction:column;gap:8px}
.svc-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid var(--color-border);border-radius:10px;background:#FDFAF6}
.svc-name{font-weight:600;font-size:.95rem;flex:1}
.svc-meta{font-size:.8rem;color:var(--color-text-muted);white-space:nowrap}
.svc-del{background:none;border:none;color:var(--color-text-muted);cursor:pointer;padding:4px;border-radius:6px;line-height:1;transition:color .15s}
.svc-del:hover{color:var(--color-rojo)}
.staff-list{display:flex;flex-wrap:wrap;gap:8px}
.staff-chip{display:flex;align-items:center;gap:7px;padding:7px 13px;border:1px solid var(--color-border);border-radius:99px;font-size:.9rem;font-weight:600;background:#FDFAF6}
.form-collapsible{display:none;margin-top:1rem;padding-top:1rem;border-top:1px solid var(--color-border)}
.form-collapsible.open{display:block}
.flash-msg{background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);padding:.7rem 1rem;border-radius:9px;font-size:.9rem;font-weight:500;margin-bottom:1.25rem}
.empty-hint{text-align:center;padding:1.25rem 0;color:var(--color-text-muted);font-size:.9rem}
/* branding */
.brand-preview{display:flex;gap:16px;flex-wrap:wrap;align-items:flex-start;margin-bottom:1.25rem}
.brand-logo{width:64px;height:64px;border-radius:12px;background:#F5EDDF;display:flex;align-items:center;justify-content:center;overflow:hidden;flex:none}
.brand-logo img{width:100%;height:100%;object-fit:cover}
.brand-logo .mono{font-family:var(--font-headings);font-size:28px;color:var(--color-barro)}
.brand-banner{width:136px;height:64px;border-radius:10px;background:linear-gradient(135deg,#ECDDCB,#E0CDB3);overflow:hidden;flex:none}
.brand-banner img{width:100%;height:100%;object-fit:cover}
.brand-upload{display:flex;flex-direction:column;gap:.5rem}
.upload-btn{display:inline-flex;align-items:center;gap:7px;background:#F5EDDF;border:1.5px solid var(--color-border);color:var(--color-barro);border-radius:8px;padding:.5rem 1rem;font-family:var(--font-body);font-size:.82rem;font-weight:600;cursor:pointer;transition:.15s}
.upload-btn:hover{border-color:var(--color-barro)}
.color-row{display:flex;gap:1rem;flex-wrap:wrap;align-items:flex-end;margin-top:.75rem}
.color-field{display:flex;flex-direction:column;gap:.3rem}
.color-field label{font-size:.8rem;font-weight:600;color:var(--color-text-muted)}
.color-swatch{width:42px;height:42px;border-radius:8px;border:1.5px solid var(--color-border);cursor:pointer;padding:0;overflow:hidden}
.extract-btn{background:var(--color-barro);color:#fff;border:none;border-radius:8px;padding:.5rem 1rem;font-family:var(--font-body);font-size:.82rem;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:background .15s}
.extract-btn:hover{background:var(--color-barro-hover)}
.extract-btn:disabled{opacity:.6;cursor:not-allowed}
</style>
CSS;

ob_start();
?>
<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;align-items:center;">
                <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; ?>

        <header class="header-bar">
            <h2>Mi negocio</h2>
            <div class="tenant-badge"><?= htmlspecialchars($bizName) ?></div>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;max-width:820px">

            <?php if ($flash): ?>
                <div class="flash-msg"><?= htmlspecialchars($flash) ?></div>
            <?php endif; ?>

            <!-- Pedile a Vale banner -->
            <div style="background:linear-gradient(135deg,#3B2F27,#2A221D);border-radius:14px;padding:1.25rem 1.5rem;margin-bottom:1.25rem;color:#fff;display:flex;align-items:center;gap:16px;">
                <div style="flex:1">
                    <div style="font-family:var(--font-headings);font-size:1.1rem;font-weight:600;color:var(--color-oro);margin-bottom:4px">Configurá hablando con Vale</div>
                    <div style="font-size:.9rem;opacity:.75">Decile "agregá corte de niño a $150" o "cambiá el horario del sábado" y lo hace sola.</div>
                </div>
                <button class="ng-ask-vale" onclick="vcOpen()">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10z"/></svg>
                    Hablar con Vale
                </button>
            </div>

            <!-- Info del negocio -->
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Información del negocio</h3>
                    <button class="ng-toggle-form" onclick="toggleForm('form-info')">o editá a mano</button>
                </div>
                <div>
                    <p style="font-size:.95rem;font-weight:600"><?= htmlspecialchars($bizName) ?></p>
                    <?php if ($rubro): ?><p style="font-size:.85rem;color:var(--color-text-muted);margin-top:2px">Rubro: <?= htmlspecialchars(ucfirst($rubro)) ?></p><?php endif; ?>
                    <?php if ($ciudad): ?><p style="font-size:.85rem;color:var(--color-text-muted);margin-top:2px"><?= htmlspecialchars($ciudad) ?></p><?php endif; ?>
                    <?php if ($descripcion): ?><p style="font-size:.9rem;margin-top:8px"><?= htmlspecialchars($descripcion) ?></p><?php endif; ?>
                    <?php if ($direccion): ?><p style="font-size:.85rem;color:var(--color-text-muted);margin-top:6px"><?= htmlspecialchars($direccion) ?></p><?php endif; ?>
                    <?php if ($telefono): ?><p style="font-size:.85rem;color:var(--color-text-muted);margin-top:4px"><?= htmlspecialchars($telefono) ?></p><?php endif; ?>
                    <?php if (!$descripcion && !$ciudad && !$direccion && !$telefono): ?>
                        <p class="empty-hint">Pedile a Vale que complete esta info, o usá el formulario.</p>
                    <?php endif; ?>
                </div>
                <div class="form-collapsible" id="form-info">
                    <form method="POST" action="/negocio">
                        <input type="hidden" name="action" value="update_info">
                        <div class="form-group">
                            <label>Nombre</label>
                            <input class="form-control" type="text" name="name" value="<?= htmlspecialchars($bizName) ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Descripción corta</label>
                            <textarea class="form-control" name="descripcion" rows="2"><?= htmlspecialchars($descripcion) ?></textarea>
                        </div>
                        <div style="display:flex;gap:1rem;flex-wrap:wrap">
                            <div class="form-group" style="flex:1;min-width:180px">
                                <label>Ciudad</label>
                                <input class="form-control" type="text" name="ciudad" value="<?= htmlspecialchars($ciudad) ?>" placeholder="Ej: Managua">
                            </div>
                            <div class="form-group" style="flex:1;min-width:180px">
                                <label>Dirección</label>
                                <input class="form-control" type="text" name="direccion" value="<?= htmlspecialchars($direccion) ?>">
                            </div>
                            <div class="form-group" style="flex:1;min-width:140px">
                                <label>Teléfono</label>
                                <input class="form-control" type="text" name="telefono" value="<?= htmlspecialchars($telefono) ?>">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary" style="font-size:.9rem;padding:.6rem 1.2rem">Guardar</button>
                    </form>
                </div>
            </div>

            <!-- Marca: logo, portada, colores -->
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Marca y colores</h3>
                    <?php if ($publicSlug): ?>
                        <a href="/n/<?= htmlspecialchars($publicSlug) ?>" target="_blank"
                           style="font-size:.8rem;color:var(--color-text-muted);font-weight:600;text-decoration:underline">
                            Ver página pública ↗
                        </a>
                    <?php endif; ?>
                </div>

                <!-- Preview -->
                <div class="brand-preview">
                    <div>
                        <p style="font-size:.75rem;color:var(--color-text-muted);font-weight:600;margin-bottom:6px">Logo</p>
                        <div class="brand-logo">
                            <?php if ($logoUrl): ?>
                                <img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo">
                            <?php else: ?>
                                <span class="mono"><?= htmlspecialchars($monogram) ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div>
                        <p style="font-size:.75rem;color:var(--color-text-muted);font-weight:600;margin-bottom:6px">Portada</p>
                        <div class="brand-banner">
                            <?php if ($bannerUrl): ?>
                                <img src="<?= htmlspecialchars($bannerUrl) ?>" alt="Portada">
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="brand-upload">
                        <form method="POST" action="/negocio" enctype="multipart/form-data" style="margin:0">
                            <input type="hidden" name="action" value="upload_asset">
                            <input type="hidden" name="asset_type" value="logo">
                            <label class="upload-btn">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                                <?= $logoUrl ? 'Cambiar logo' : 'Subir logo' ?>
                                <input type="file" name="asset" accept="image/jpeg,image/png,image/webp" required
                                       style="display:none" onchange="this.form.submit()">
                            </label>
                            <p style="font-size:.72rem;color:var(--color-text-muted)">JPG/PNG/WebP · máx 2 MB</p>
                        </form>
                        <form method="POST" action="/negocio" enctype="multipart/form-data" style="margin:0">
                            <input type="hidden" name="action" value="upload_asset">
                            <input type="hidden" name="asset_type" value="banner">
                            <label class="upload-btn">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                                <?= $bannerUrl ? 'Cambiar portada' : 'Subir portada' ?>
                                <input type="file" name="asset" accept="image/jpeg,image/png,image/webp" required
                                       style="display:none" onchange="this.form.submit()">
                            </label>
                            <p style="font-size:.72rem;color:var(--color-text-muted)">JPG/PNG/WebP · máx 5 MB</p>
                        </form>
                    </div>
                </div>

                <!-- Colores -->
                <div style="border-top:1px solid var(--color-border);padding-top:1rem">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.75rem;flex-wrap:wrap;gap:.5rem">
                        <p style="font-size:.9rem;font-weight:600;margin:0">Colores de marca</p>
                        <?php if ($logoUrl): ?>
                            <button class="extract-btn" id="extractBtn" onclick="extractColors()" type="button">
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10z"/></svg>
                                Extraer con IA
                            </button>
                        <?php endif; ?>
                    </div>
                    <form method="POST" action="/negocio" id="colorsForm">
                        <input type="hidden" name="action" value="update_colors">
                        <div class="color-row">
                            <div class="color-field">
                                <label for="cpPrimary">Principal</label>
                                <input class="color-swatch" type="color" id="cpPrimary" name="color_primario"
                                       value="<?= htmlspecialchars($colorP) ?>">
                            </div>
                            <div class="color-field">
                                <label for="cpAccent">Acento</label>
                                <input class="color-swatch" type="color" id="cpAccent" name="color_acento"
                                       value="<?= htmlspecialchars($colorA) ?>">
                            </div>
                            <!-- preview swatch en vivo -->
                            <div id="ctaPreview" style="display:flex;align-items:center;gap:8px;padding:.5rem 1rem;border-radius:10px;font-size:.8rem;font-weight:600;background:<?= htmlspecialchars($colorP) ?>;color:#fff;transition:.2s;align-self:flex-end">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>
                                Vista previa
                            </div>
                            <button type="submit" class="btn btn-primary" style="font-size:.85rem;padding:.55rem 1.1rem;align-self:flex-end">
                                Guardar
                            </button>
                        </div>
                    </form>
                    <p style="font-size:.75rem;color:var(--color-text-muted);margin-top:.5rem">
                        Los colores se aplican automáticamente a tu página pública y tarjeta en el directorio.
                    </p>
                </div>
            </div>

            <!-- Servicios -->
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Servicios (<?= count($services) ?>)</h3>
                    <div style="display:flex;align-items:center;gap:10px">
                        <button class="ng-ask-vale" onclick="vcOpen()" style="padding:7px 13px;font-size:.85rem">Pedile a Vale</button>
                        <button class="ng-toggle-form" onclick="toggleForm('form-svc')">o agregá a mano</button>
                    </div>
                </div>

                <?php if (empty($services)): ?>
                    <p class="empty-hint">Todavía no hay servicios. Pedile a Vale que los cargue por vos.</p>
                <?php else: ?>
                    <ul class="svc-list">
                        <?php foreach ($services as $s): ?>
                        <li class="svc-item">
                            <div style="flex:1">
                                <div class="svc-name"><?= htmlspecialchars($s['name']) ?></div>
                                <div class="svc-meta">
                                    <?php
                                        $parts = [];
                                        if ($s['duration_min']) $parts[] = $s['duration_min'] . ' min';
                                        if ($s['price_min'] !== null) $parts[] = '$' . number_format((float)$s['price_min'], 0);
                                        echo htmlspecialchars(implode(' · ', $parts));
                                    ?>
                                </div>
                            </div>
                            <form method="POST" action="/negocio" style="margin:0" onsubmit="return confirm('¿Archivar este servicio?')">
                                <input type="hidden" name="action" value="delete_service">
                                <input type="hidden" name="service_id" value="<?= (int)$s['id'] ?>">
                                <button type="submit" class="svc-del" title="Archivar">
                                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/></svg>
                                </button>
                            </form>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>

                <div class="form-collapsible" id="form-svc">
                    <form method="POST" action="/negocio">
                        <input type="hidden" name="action" value="add_service">
                        <div style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:flex-end">
                            <div class="form-group" style="flex:2;min-width:160px;margin-bottom:0">
                                <label>Nombre del servicio</label>
                                <input class="form-control" type="text" name="nombre" required placeholder="Ej: Corte clásico">
                            </div>
                            <div class="form-group" style="flex:1;min-width:90px;margin-bottom:0">
                                <label>Duración (min)</label>
                                <input class="form-control" type="number" name="duracion_min" min="5" placeholder="30">
                            </div>
                            <div class="form-group" style="flex:1;min-width:90px;margin-bottom:0">
                                <label>Precio ($)</label>
                                <input class="form-control" type="number" name="precio" min="0" step="0.01" placeholder="0">
                            </div>
                            <button type="submit" class="btn btn-primary" style="font-size:.9rem;padding:.7rem 1rem;margin-bottom:0">Agregar</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Horarios -->
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Horarios de atención</h3>
                    <div style="display:flex;align-items:center;gap:10px">
                        <button class="ng-ask-vale" onclick="vcOpen()" style="padding:7px 13px;font-size:.85rem">Pedile a Vale</button>
                        <button class="ng-toggle-form" onclick="toggleForm('form-horas')">o editá a mano</button>
                    </div>
                </div>
                <?php if ($horasTexto): ?>
                    <p style="font-size:.95rem;color:var(--color-tierra)"><?= htmlspecialchars($horasTexto) ?></p>
                <?php else: ?>
                    <p class="empty-hint">Sin horarios configurados. Pedile a Vale que los cargue.</p>
                <?php endif; ?>
                <div class="form-collapsible" id="form-horas">
                    <form method="POST" action="/negocio">
                        <input type="hidden" name="action" value="update_hours">
                        <div class="form-group" style="margin-bottom:.75rem">
                            <label>Horario en texto libre</label>
                            <input class="form-control" type="text" name="horarios" value="<?= htmlspecialchars($horasTexto) ?>" placeholder="Ej: Lun a Sáb 9am–6pm">
                        </div>
                        <button type="submit" class="btn btn-primary" style="font-size:.9rem;padding:.6rem 1.2rem">Guardar</button>
                    </form>
                </div>
            </div>

            <!-- Staff -->
            <?php if (!empty($staff)): ?>
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Staff (<?= count($staff) ?>)</h3>
                    <button class="ng-ask-vale" onclick="vcOpen()" style="padding:7px 13px;font-size:.85rem">Pedile a Vale</button>
                </div>
                <div class="staff-list">
                    <?php foreach ($staff as $m): ?>
                    <div class="staff-chip">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                        <?= htmlspecialchars($m['nombre'] ?? $m['name'] ?? '') ?>
                        <?php if (!empty($m['rol'])): ?><span style="font-weight:400;color:var(--color-text-muted)">· <?= htmlspecialchars($m['rol']) ?></span><?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php else: ?>
            <div class="ng-section">
                <div class="ng-section-head">
                    <h3>Staff</h3>
                    <button class="ng-ask-vale" onclick="vcOpen()" style="padding:7px 13px;font-size:.85rem">Pedile a Vale</button>
                </div>
                <p class="empty-hint">Decile a Vale "agregá a Marvin como barbero" para agregar tu equipo.</p>
            </div>
            <?php endif; ?>

        </div><!-- /scroll -->
    </main>
</div>

<?php require __DIR__ . '/partials/vale_chat.php'; ?>

<script>
function toggleForm(id) {
    var el = document.getElementById(id);
    if (el) el.classList.toggle('open');
}

// Preview de color en vivo
(function(){
    var cp = document.getElementById('cpPrimary');
    var preview = document.getElementById('ctaPreview');
    if (!cp || !preview) return;
    cp.addEventListener('input', function(){
        preview.style.background = cp.value;
    });
})();

// Extraer colores con IA
function extractColors() {
    var btn = document.getElementById('extractBtn');
    if (!btn) return;
    btn.disabled = true;
    btn.textContent = 'Extrayendo…';
    fetch('/negocio', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=extract_colors'
    })
    .then(function(r){ return r.json(); })
    .then(function(data){
        btn.disabled = false;
        btn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10z"/></svg> Extraer con IA';
        if (data.ok && data.colors) {
            var cp = document.getElementById('cpPrimary');
            var ca = document.getElementById('cpAccent');
            var preview = document.getElementById('ctaPreview');
            if (cp && data.colors.primary) { cp.value = data.colors.primary; if (preview) preview.style.background = data.colors.primary; }
            if (ca && data.colors.accent)  { ca.value = data.colors.accent;  }
            // Auto-guardar colores extraídos
            document.getElementById('colorsForm').submit();
        } else {
            alert(data.error || 'No se pudo extraer la paleta.');
        }
    })
    .catch(function(){
        btn.disabled = false;
        btn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10z"/></svg> Extraer con IA';
        alert('Error de conexión.');
    });
}
</script>

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