<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DIMARK Brain · Usuarios</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--red:#E8272A;--red-l:rgba(232,39,42,.1);--red-b:rgba(232,39,42,.2);--bg:#0f0f0f;--bg2:#181818;--bg3:#222;--bg4:#2a2a2a;--border:rgba(255,255,255,.07);--border2:rgba(255,255,255,.13);--text:#f0f0f0;--muted:rgba(240,240,240,.42);--green:#22c97a;--yellow:#f5c543;--blue:#4a9ef8;--fh:'Syne',sans-serif;--fb:'DM Sans',sans-serif}
html,body{min-height:100%;background:var(--bg);color:var(--text);font-family:var(--fb);font-size:14px}
nav{display:flex;align-items:center;justify-content:space-between;padding:0 22px;height:54px;background:var(--bg);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:100}
.logo{display:flex;align-items:center;gap:10px;text-decoration:none;color:inherit}
.logo-mark{width:30px;height:30px;background:var(--red);border-radius:7px;display:flex;align-items:center;justify-content:center;font-family:var(--fh);font-weight:700;font-size:14px;color:#fff}
.logo-name{font-family:var(--fh);font-weight:700;font-size:15px}
.logo-sub{font-size:10px;letter-spacing:1.6px;text-transform:uppercase;color:var(--red)}
.nav-right{display:flex;align-items:center;gap:10px}
.nav-link{padding:5px 12px;border-radius:6px;font-size:13px;color:var(--muted);text-decoration:none;border:1px solid transparent;transition:all .15s}
.nav-link:hover{color:var(--text);background:var(--bg3)}
.nav-link.active{color:var(--text);background:var(--bg3);border-color:var(--border2)}
.av{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:500;cursor:pointer}
main{max-width:960px;margin:0 auto;padding:28px 22px}
.ph{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px}
.pt{font-family:var(--fh);font-size:20px;font-weight:700}
.ps{font-size:12px;color:var(--muted);margin-top:2px}
.btn{padding:8px 16px;border-radius:7px;font-size:13px;cursor:pointer;font-family:var(--fb);transition:all .15s;border:1px solid}
.btn-primary{background:var(--red);border-color:var(--red);color:#fff}
.btn-primary:hover{opacity:.85}
.btn-ghost{background:none;border-color:var(--border2);color:var(--text)}
.btn-ghost:hover{background:var(--bg3)}
.btn-sm{padding:5px 10px;font-size:12px}
.card{background:var(--bg2);border:1px solid var(--border);border-radius:11px;padding:18px 20px;margin-bottom:16px}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{text-align:left;font-size:10px;font-weight:500;color:var(--muted);text-transform:uppercase;letter-spacing:.7px;padding:0 0 10px;border-bottom:1px solid var(--border)}
.tbl td{padding:10px 0;border-bottom:1px solid rgba(255,255,255,.03);vertical-align:middle}
.tbl tr:last-child td{border-bottom:none}
.pill{display:inline-block;padding:2px 9px;border-radius:14px;font-size:11px}
.pill-admin{background:rgba(232,39,42,.12);color:var(--red)}
.pill-client{background:rgba(74,158,248,.12);color:var(--blue)}
.pill-ok{background:rgba(34,201,122,.1);color:var(--green)}
.pill-off{background:rgba(255,255,255,.05);color:var(--muted)}
.av-sm{width:32px;height:32px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;font-family:var(--fh)}
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:500;display:none;align-items:center;justify-content:center}
.modal-bg.open{display:flex}
.modal{background:var(--bg2);border:1px solid var(--border2);border-radius:14px;padding:26px;width:480px;max-width:94vw;max-height:90vh;overflow-y:auto}
.modal-title{font-family:var(--fh);font-size:16px;font-weight:700;margin-bottom:18px}
.mf{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}
.mf label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.7px}
.mf input,.mf select{background:var(--bg3);border:1px solid var(--border2);border-radius:7px;padding:8px 11px;font-size:13px;color:var(--text);font-family:var(--fb);outline:none;width:100%}
.mf input:focus,.mf select:focus{border-color:rgba(232,39,42,.5)}
.mf select option{background:var(--bg3)}
.modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:6px}
.alert{padding:10px 14px;border-radius:8px;font-size:13px;margin-bottom:16px}
.alert-ok{background:rgba(34,201,122,.1);border:1px solid rgba(34,201,122,.25);color:var(--green)}
.alert-err{background:rgba(232,39,42,.1);border:1px solid rgba(232,39,42,.25);color:#f87171}
.client-checks{display:flex;flex-direction:column;gap:6px;margin-top:6px;max-height:160px;overflow-y:auto}
.cc-item{display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:6px;cursor:pointer;transition:background .15s}
.cc-item:hover{background:var(--bg4)}
.cc-item input{accent-color:var(--red);width:15px;height:15px;flex-shrink:0}
::-webkit-scrollbar{width:4px}
::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
</style>
</head>
<body>
<?php
require_once __DIR__ . '/auth.php';
dm_require_admin();

$user = dm_user();
$msg = '';
$msgType = '';

// ——— ACCIONES POST ———
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'create_user') {
        $name     = trim($_POST['name'] ?? '');
        $email    = strtolower(trim($_POST['email'] ?? ''));
        $password = trim($_POST['password'] ?? '');
        $role     = in_array($_POST['role'] ?? '', ['admin','client']) ? $_POST['role'] : 'client';
        $color    = trim($_POST['color'] ?? '#4a9ef8');
        $clients_sel = array_map('intval', $_POST['client_ids'] ?? []);

        if (!$name || !$email || !$password) {
            $msg = 'Nombre, email y contraseña son obligatorios.'; $msgType = 'err';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $msg = 'Email inválido.'; $msgType = 'err';
        } elseif (strlen($password) < 6) {
            $msg = 'La contraseña debe tener al menos 6 caracteres.'; $msgType = 'err';
        } else {
            try {
                $hash = password_hash($password, PASSWORD_BCRYPT);
                $pdo->prepare('INSERT INTO dm_users (name,email,password,role,avatar_color) VALUES (?,?,?,?,?)')
                    ->execute([$name, $email, $hash, $role, $color]);
                $new_id = (int)$pdo->lastInsertId();
                // Asignar clientes
                foreach ($clients_sel as $cid) {
                    $pdo->prepare('INSERT IGNORE INTO dm_user_clients (user_id,client_id) VALUES (?,?)')->execute([$new_id, $cid]);
                }
                dm_log($user['id'], null, 'create_user', "Usuario creado: {$email} ({$role})");
                $msg = "Usuario {$name} creado correctamente."; $msgType = 'ok';
            } catch (PDOException $e) {
                $msg = str_contains($e->getMessage(), 'Duplicate') ? 'Ese email ya está registrado.' : 'Error al crear usuario.';
                $msgType = 'err';
            }
        }
    }

    if ($action === 'toggle_user') {
        $uid = (int)($_POST['uid'] ?? 0);
        if ($uid && $uid !== $user['id']) {
            $pdo->prepare('UPDATE dm_users SET active = 1-active WHERE id = ?')->execute([$uid]);
            dm_log($user['id'], null, 'toggle_user', "Toggle usuario ID {$uid}");
        }
    }

    if ($action === 'delete_user') {
        $uid = (int)($_POST['uid'] ?? 0);
        if ($uid && $uid !== $user['id']) {
            $pdo->prepare('DELETE FROM dm_users WHERE id = ?')->execute([$uid]);
            dm_log($user['id'], null, 'delete_user', "Eliminado usuario ID {$uid}");
            $msg = 'Usuario eliminado.'; $msgType = 'ok';
        }
    }

    if ($action === 'assign_clients') {
        $uid = (int)($_POST['uid'] ?? 0);
        $cids = array_map('intval', $_POST['client_ids'] ?? []);
        if ($uid) {
            $pdo->prepare('DELETE FROM dm_user_clients WHERE user_id = ?')->execute([$uid]);
            foreach ($cids as $cid) {
                $pdo->prepare('INSERT IGNORE INTO dm_user_clients (user_id,client_id) VALUES (?,?)')->execute([$uid, $cid]);
            }
            $msg = 'Clientes asignados.'; $msgType = 'ok';
        }
    }
}

// ——— CARGAR DATOS ———
$users   = $pdo ? $pdo->query('SELECT * FROM dm_users ORDER BY role, name')->fetchAll() : [];
$clients = $pdo ? $pdo->query('SELECT id, name, color FROM dm_clients WHERE active=1 ORDER BY name')->fetchAll() : [];

// Mapa user → clientes asignados
$user_clients = [];
if ($pdo) {
    $rows = $pdo->query('SELECT user_id, client_id FROM dm_user_clients')->fetchAll();
    foreach ($rows as $r) $user_clients[$r['user_id']][] = $r['client_id'];
}
?>

<nav>
  <a class="logo" href="index.php">
    <div class="logo-mark">D</div>
    <div><div class="logo-name">DIMARK</div><div class="logo-sub">Super Cerebro</div></div>
  </a>
  <div class="nav-right">
    <a href="index.php"    class="nav-link">Dashboard</a>
    <a href="users.php"    class="nav-link active">Usuarios</a>
    <a href="clients.php"  class="nav-link">Clientes</a>
    <a href="logout.php"   class="nav-link">Salir</a>
    <div class="av" style="background:<?= htmlspecialchars($user['color']) ?>"><?= strtoupper(substr($user['name'],0,2)) ?></div>
  </div>
</nav>

<main>
  <div class="ph">
    <div>
      <div class="pt">Gestión de usuarios</div>
      <div class="ps"><?= count($users) ?> usuarios registrados</div>
    </div>
    <button class="btn btn-primary" onclick="document.getElementById('modalNew').classList.add('open')">+ Nuevo usuario</button>
  </div>

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

  <?php if (!$pdo): ?>
  <div class="alert alert-err">Sin conexión a base de datos. Completa la configuración en <a href="setup.php" style="color:inherit;font-weight:500">setup.php</a>.</div>
  <?php else: ?>

  <div class="card">
    <table class="tbl">
      <thead>
        <tr>
          <th>Usuario</th>
          <th>Email</th>
          <th>Rol</th>
          <th>Clientes asignados</th>
          <th>Último acceso</th>
          <th>Estado</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($users as $u):
          $assigned = $user_clients[$u['id']] ?? [];
          $assignedClients = array_filter($clients, fn($c) => in_array($c['id'], $assigned));
        ?>
        <tr>
          <td>
            <div style="display:flex;align-items:center;gap:9px">
              <div class="av-sm" style="background:<?= htmlspecialchars($u['avatar_color']) ?>22;color:<?= htmlspecialchars($u['avatar_color']) ?>"><?= strtoupper(substr($u['name'],0,2)) ?></div>
              <span style="font-weight:500"><?= htmlspecialchars($u['name']) ?></span>
              <?php if ($u['id'] == $user['id']): ?><span style="font-size:10px;color:var(--muted)"> (tú)</span><?php endif ?>
            </div>
          </td>
          <td style="color:var(--muted)"><?= htmlspecialchars($u['email']) ?></td>
          <td><span class="pill pill-<?= $u['role'] ?>"><?= $u['role'] === 'admin' ? 'Admin' : 'Cliente' ?></span></td>
          <td>
            <?php if ($u['role'] === 'admin'): ?>
              <span style="font-size:12px;color:var(--muted)">Todos</span>
            <?php elseif (empty($assignedClients)): ?>
              <span style="font-size:12px;color:var(--muted)">Sin asignar</span>
            <?php else: ?>
              <div style="display:flex;gap:4px;flex-wrap:wrap">
                <?php foreach ($assignedClients as $ac): ?>
                <span style="font-size:11px;padding:2px 7px;border-radius:4px;background:<?= htmlspecialchars($ac['color']) ?>20;color:<?= htmlspecialchars($ac['color']) ?>"><?= htmlspecialchars($ac['name']) ?></span>
                <?php endforeach ?>
              </div>
            <?php endif ?>
          </td>
          <td style="font-size:12px;color:var(--muted)"><?= $u['last_login'] ? date('d/m/Y H:i', strtotime($u['last_login'])) : 'Nunca' ?></td>
          <td><span class="pill <?= $u['active'] ? 'pill-ok' : 'pill-off' ?>"><?= $u['active'] ? 'Activo' : 'Inactivo' ?></span></td>
          <td>
            <div style="display:flex;gap:5px">
              <?php if ($u['role'] === 'client'): ?>
              <button class="btn btn-ghost btn-sm" onclick="openAssign(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['name'])) ?>',[<?= implode(',',$assigned) ?>])">Clientes</button>
              <?php endif ?>
              <?php if ($u['id'] !== $user['id']): ?>
              <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="toggle_user">
                <input type="hidden" name="uid" value="<?= $u['id'] ?>">
                <button type="submit" class="btn btn-ghost btn-sm"><?= $u['active'] ? 'Desactivar' : 'Activar' ?></button>
              </form>
              <form method="POST" style="display:inline" onsubmit="return confirm('¿Eliminar a <?= htmlspecialchars(addslashes($u['name'])) ?>?')">
                <input type="hidden" name="action" value="delete_user">
                <input type="hidden" name="uid" value="<?= $u['id'] ?>">
                <button type="submit" class="btn btn-ghost btn-sm" style="color:#f87171">Eliminar</button>
              </form>
              <?php endif ?>
            </div>
          </td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>
  <?php endif ?>
</main>

<!-- MODAL NUEVO USUARIO -->
<div class="modal-bg" id="modalNew" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal">
    <div class="modal-title">Nuevo usuario</div>
    <form method="POST">
      <input type="hidden" name="action" value="create_user">
      <div class="mf"><label>Nombre completo</label><input type="text" name="name" placeholder="Ej: Juan Pérez" required></div>
      <div class="mf"><label>Email</label><input type="email" name="email" placeholder="juan@empresa.com" required></div>
      <div class="mf"><label>Contraseña</label><input type="password" name="password" placeholder="Mínimo 6 caracteres" required></div>
      <div class="mf"><label>Rol</label>
        <select name="role" id="newRoleSelect" onchange="toggleClientSel(this.value)">
          <option value="client">Cliente — solo ve sus cuentas</option>
          <option value="admin">Admin — acceso total</option>
        </select>
      </div>
      <div class="mf"><label>Color de avatar</label>
        <div style="display:flex;gap:7px;margin-top:4px" id="newColorPicker">
          <?php foreach(['#4a9ef8','#22c97a','#f5c543','#9b7ff4','#f97316','#E8272A'] as $c): ?>
          <div onclick="pickNewColor(this,'<?= $c ?>')" data-color="<?= $c ?>" style="width:22px;height:22px;border-radius:50%;background:<?= $c ?>;cursor:pointer;border:2px solid transparent;transition:border-color .15s"></div>
          <?php endforeach ?>
        </div>
        <input type="hidden" name="color" id="newColorVal" value="#4a9ef8">
      </div>
      <div class="mf" id="clientSelWrap">
        <label>Clientes asignados</label>
        <div class="client-checks">
          <?php foreach ($clients as $c): ?>
          <label class="cc-item">
            <input type="checkbox" name="client_ids[]" value="<?= $c['id'] ?>">
            <span style="width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($c['color']) ?>;flex-shrink:0"></span>
            <span style="font-size:13px"><?= htmlspecialchars($c['name']) ?></span>
          </label>
          <?php endforeach ?>
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('modalNew').classList.remove('open')">Cancelar</button>
        <button type="submit" class="btn btn-primary">Crear usuario</button>
      </div>
    </form>
  </div>
</div>

<!-- MODAL ASIGNAR CLIENTES -->
<div class="modal-bg" id="modalAssign" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal">
    <div class="modal-title" id="assignTitle">Asignar clientes</div>
    <form method="POST">
      <input type="hidden" name="action" value="assign_clients">
      <input type="hidden" name="uid" id="assignUid">
      <div class="mf">
        <label>Clientes que puede ver este usuario</label>
        <div class="client-checks" id="assignChecks">
          <?php foreach ($clients as $c): ?>
          <label class="cc-item" id="acc-<?= $c['id'] ?>">
            <input type="checkbox" name="client_ids[]" value="<?= $c['id'] ?>" class="acheck" data-id="<?= $c['id'] ?>">
            <span style="width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($c['color']) ?>;flex-shrink:0"></span>
            <span style="font-size:13px"><?= htmlspecialchars($c['name']) ?></span>
          </label>
          <?php endforeach ?>
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('modalAssign').classList.remove('open')">Cancelar</button>
        <button type="submit" class="btn btn-primary">Guardar asignación</button>
      </div>
    </form>
  </div>
</div>

<script>
function toggleClientSel(role){
  document.getElementById('clientSelWrap').style.display = role==='admin'?'none':'block';
}
function pickNewColor(el, color){
  document.querySelectorAll('#newColorPicker div').forEach(e=>e.style.outline='none');
  el.style.outline='2px solid #fff';
  document.getElementById('newColorVal').value=color;
}
function openAssign(uid, name, assigned){
  document.getElementById('assignUid').value=uid;
  document.getElementById('assignTitle').textContent='Clientes para '+name;
  document.querySelectorAll('.acheck').forEach(cb=>{
    cb.checked = assigned.includes(parseInt(cb.dataset.id));
  });
  document.getElementById('modalAssign').classList.add('open');
}
// Init color picker
document.querySelector('#newColorPicker div').style.outline='2px solid #fff';
</script>
</body>
</html>
