<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}
$page_title = 'Vale Admin — Usuarios & Roles';
ob_start();
?>
<div class="dashboard-container">
    <?php $adminNav = 'users'; require __DIR__ . '/sidebar.php'; ?>

    <main class="main-content">
        <header class="header-bar">
            <h2>Usuarios &amp; Roles</h2>
        </header>

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

            <?php if (!empty($usersNotice)): ?>
                <div class="alert" style="background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);margin-bottom:1rem;">
                    <?php echo htmlspecialchars($usersNotice); ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($usersError)): ?>
                <div class="alert alert-error" style="margin-bottom:1rem;">
                    <?php echo htmlspecialchars($usersError); ?>
                </div>
            <?php endif; ?>

            <!-- ── Super-admins ─────────────────────────────────────────────── -->
            <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.5rem;margin-bottom:1.5rem;box-shadow:var(--shadow-soft);">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;gap:1rem;flex-wrap:wrap;">
                    <h3 style="margin:0;">Super-admins <span style="font-size:.8rem;color:var(--color-text-muted);font-weight:400;">(tabla admins)</span></h3>
                    <button class="btn btn-primary" onclick="document.getElementById('formNewAdmin').classList.toggle('hidden')" style="font-size:.85rem;">+ Nuevo admin</button>
                </div>

                <form id="formNewAdmin" method="POST" action="/admin/users" class="hidden"
                      style="background:var(--color-bg-alt);border:1px solid var(--color-border);border-radius:10px;padding:1rem;margin-bottom:1rem;display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:.6rem;align-items:end;">
                    <input type="hidden" name="action" value="create_admin">
                    <div>
                        <label style="font-size:.75rem;font-weight:600;color:var(--color-text-muted);display:block;margin-bottom:.3rem;">Nombre</label>
                        <input type="text" name="name" class="form-control" placeholder="Nombre" required>
                    </div>
                    <div>
                        <label style="font-size:.75rem;font-weight:600;color:var(--color-text-muted);display:block;margin-bottom:.3rem;">Email</label>
                        <input type="email" name="email" class="form-control" placeholder="email@ejemplo.com" required>
                    </div>
                    <div>
                        <label style="font-size:.75rem;font-weight:600;color:var(--color-text-muted);display:block;margin-bottom:.3rem;">Contraseña</label>
                        <input type="password" name="password" class="form-control" placeholder="Mínimo 10 caracteres" minlength="10" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Crear</button>
                </form>

                <?php if (empty($admins)): ?>
                    <p style="color:var(--color-text-muted);font-size:.9rem;">No hay admins registrados.</p>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                        <table class="admin-table" style="width:100%;border-collapse:collapse;font-size:.875rem;">
                            <thead>
                                <tr style="border-bottom:2px solid var(--color-border);">
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Nombre</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Email</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Creado</th>
                                    <th style="padding:.5rem .75rem;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($admins as $adm): ?>
                                    <tr style="border-bottom:1px solid var(--color-border);">
                                        <td style="padding:.6rem .75rem;font-weight:600;">
                                            <?php echo htmlspecialchars($adm['name'] ?? '—'); ?>
                                            <?php if ((int)$adm['id'] === (int)($_SESSION['admin_id'] ?? 0)): ?>
                                                <span style="font-size:.7rem;background:#e8f5e9;color:#2e7d32;border-radius:4px;padding:1px 6px;margin-left:6px;">tú</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding:.6rem .75rem;color:var(--color-text-muted);"><?php echo htmlspecialchars($adm['email']); ?></td>
                                        <td style="padding:.6rem .75rem;color:var(--color-text-muted);font-size:.8rem;"><?php echo date('d/m/Y', strtotime($adm['created_at'])); ?></td>
                                        <td style="padding:.6rem .75rem;text-align:right;">
                                            <?php if ((int)$adm['id'] !== (int)($_SESSION['admin_id'] ?? 0)): ?>
                                                <form method="POST" action="/admin/users" style="display:inline;"
                                                      onsubmit="return confirm('¿Eliminar admin <?php echo htmlspecialchars(addslashes($adm['name'] ?? $adm['email'])); ?>? No se puede deshacer.')">
                                                    <input type="hidden" name="action" value="delete_admin">
                                                    <input type="hidden" name="admin_id" value="<?php echo (int)$adm['id']; ?>">
                                                    <button type="submit" class="btn btn-sm" style="color:var(--color-rojo);border-color:var(--color-rojo);font-size:.75rem;padding:4px 10px;">Eliminar</button>
                                                </form>
                                            <?php else: ?>
                                                <span style="font-size:.75rem;color:var(--color-text-muted);">protegido</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>

            <!-- ── Usuarios de tenants ──────────────────────────────────────── -->
            <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.5rem;margin-bottom:1.5rem;box-shadow:var(--shadow-soft);">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;gap:1rem;flex-wrap:wrap;">
                    <h3 style="margin:0;">Usuarios de negocios <span style="font-size:.8rem;color:var(--color-text-muted);font-weight:400;">(tabla users)</span></h3>
                    <div style="display:flex;gap:.5rem;align-items:center;">
                        <input id="userSearch" type="search" class="form-control" placeholder="Buscar por email o negocio…" style="max-width:240px;font-size:.85rem;" oninput="filterUsers(this.value)">
                    </div>
                </div>

                <?php if (empty($tenantUsers)): ?>
                    <p style="color:var(--color-text-muted);font-size:.9rem;">No hay usuarios registrados todavía.</p>
                <?php else: ?>
                    <?php
                    $roleBadge = function(string $role): string {
                        $map = [
                            'owner'   => ['#e3f2fd','#1565c0','Dueño'],
                            'staff'   => ['#fff8e1','#f57f17','Staff'],
                            'seller'  => ['#f3e5f5','#6a1b9a','Vendedor'],
                            'support' => ['#e8f5e9','#2e7d32','Soporte'],
                        ];
                        [$bg, $color, $label] = $map[$role] ?? ['#f5f5f5','#555',$role];
                        return "<span style=\"display:inline-block;background:{$bg};color:{$color};border-radius:5px;padding:2px 8px;font-size:.7rem;font-weight:700;\">{$label}</span>";
                    };
                    ?>
                    <div style="overflow-x:auto;">
                        <table class="admin-table" id="usersTable" style="width:100%;border-collapse:collapse;font-size:.875rem;">
                            <thead>
                                <tr style="border-bottom:2px solid var(--color-border);">
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Nombre</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Email</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Negocio</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Rol actual</th>
                                    <th style="text-align:left;padding:.5rem .75rem;color:var(--color-text-muted);font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;">Creado</th>
                                    <th style="padding:.5rem .75rem;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($tenantUsers as $u): ?>
                                    <tr data-search="<?php echo strtolower(htmlspecialchars(($u['name']??'').' '.$u['email'].' '.($u['tenant_name']??''))); ?>" style="border-bottom:1px solid var(--color-border);">
                                        <td style="padding:.6rem .75rem;font-weight:600;"><?php echo htmlspecialchars($u['name'] ?? '—'); ?></td>
                                        <td style="padding:.6rem .75rem;color:var(--color-text-muted);"><?php echo htmlspecialchars($u['email']); ?></td>
                                        <td style="padding:.6rem .75rem;">
                                            <?php if (!empty($u['tenant_name'])): ?>
                                                <a href="/admin/tenants/<?php echo (int)$u['tenant_id']; ?>" style="color:var(--color-terra);"><?php echo htmlspecialchars($u['tenant_name']); ?></a>
                                            <?php else: ?>
                                                <span style="color:var(--color-text-muted);">sin tenant</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding:.6rem .75rem;"><?php echo $roleBadge($u['role']); ?></td>
                                        <td style="padding:.6rem .75rem;color:var(--color-text-muted);font-size:.8rem;"><?php echo date('d/m/Y', strtotime($u['created_at'])); ?></td>
                                        <td style="padding:.6rem .75rem;text-align:right;">
                                            <form method="POST" action="/admin/users" style="display:inline-flex;gap:.4rem;align-items:center;">
                                                <input type="hidden" name="action" value="change_role">
                                                <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                                                <select name="role" class="form-control" style="padding:4px 8px;font-size:.8rem;height:auto;" onchange="this.form.submit()">
                                                    <?php foreach (['owner','staff','seller','support'] as $r): ?>
                                                        <option value="<?php echo $r; ?>" <?php echo $u['role'] === $r ? 'selected' : ''; ?>>
                                                            <?php echo ucfirst($r); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <p style="font-size:.8rem;color:var(--color-text-muted);margin-top:.75rem;"><?php echo count($tenantUsers); ?> usuarios en total.</p>
                <?php endif; ?>
            </section>

            <!-- ── Nota sobre roles ─────────────────────────────────────────── -->
            <section style="background:#fffdf7;border:1px solid #f0e8c8;border-radius:12px;padding:1.25rem 1.5rem;font-size:.875rem;color:#5c4a1e;">
                <strong style="display:block;margin-bottom:.5rem;">Referencia de roles</strong>
                <table style="border-collapse:collapse;width:100%;">
                    <tr style="border-bottom:1px solid #f0e8c8;"><td style="padding:.35rem .5rem;font-weight:700;width:90px;">super_admin</td><td style="padding:.35rem .5rem;">Acceso cross-tenant. Solo via tabla <code>admins</code>. Sesión completamente separada de <code>users</code>.</td></tr>
                    <tr style="border-bottom:1px solid #f0e8c8;"><td style="padding:.35rem .5rem;font-weight:700;">owner</td><td style="padding:.35rem .5rem;">Dueño del negocio. Ve todo su tenant: dashboard, mensajes, agenda, configuración.</td></tr>
                    <tr style="border-bottom:1px solid #f0e8c8;"><td style="padding:.35rem .5rem;font-weight:700;">staff</td><td style="padding:.35rem .5rem;">Solo accede a la agenda del tenant. Sin acceso a configuración ni a otros tenants.</td></tr>
                    <tr style="border-bottom:1px solid #f0e8c8;"><td style="padding:.35rem .5rem;font-weight:700;">seller</td><td style="padding:.35rem .5rem;">Ve solo los tenants donde <code>tenants.seller_id = sellers.id</code>. Accede a su portal de comisiones.</td></tr>
                    <tr><td style="padding:.35rem .5rem;font-weight:700;">support</td><td style="padding:.35rem .5rem;">Scoped a su propio tenant_id. Para uso de equipos de soporte asignados a un negocio.</td></tr>
                </table>
            </section>

        </div>
    </main>
</div>

<style>
  .hidden { display: none !important; }
  .admin-table tr:hover td { background: #faf8f4; }
</style>

<script>
function filterUsers(q) {
    q = q.trim().toLowerCase();
    document.querySelectorAll('#usersTable tbody tr').forEach(tr => {
        const hay = tr.dataset.search || '';
        tr.style.display = (!q || hay.includes(q)) ? '' : 'none';
    });
}
</script>

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