<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/bootstrap.php';
require_login();

if (!can_manage_users()) {
    http_response_code(403);
    exit('No autorizado.');
}

$pageTitle = 'Usuarios';
$currentNav = 'usuarios';

$perfilesAll = db()->query('SELECT id, codigo, nombre FROM perfiles ORDER BY id')->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $uid = (int) ($_POST['id'] ?? 0);
        if ($uid && $uid !== (int) (current_user()['id'] ?? 0)) {
            db()->prepare('DELETE FROM usuarios WHERE id = ?')->execute([$uid]);
            flash('ok', 'Usuario eliminado.');
        }
        redirect('/pages/usuarios.php');
    }
    if ($action === 'save') {
        $email = trim((string) ($_POST['email'] ?? ''));
        $nom = trim((string) ($_POST['nombre'] ?? ''));
        $ape = trim((string) ($_POST['apellidos'] ?? ''));
        $pass = (string) ($_POST['password'] ?? '');
        $activo = isset($_POST['activo']) ? 1 : 0;
        $pids = array_map('intval', $_POST['perfiles'] ?? []);
        $pids = array_filter($pids, fn ($x) => $x > 0);
        if ($email !== '' && $nom !== '' && $pass !== '') {
            $hash = password_hash($pass, PASSWORD_DEFAULT);
            db()->prepare(
                'INSERT INTO usuarios (email, password_hash, nombre, apellidos, activo) VALUES (?,?,?,?,?)'
            )->execute([$email, $hash, $nom, $ape ?: null, $activo]);
            $newId = (int) db()->lastInsertId();
            $ins = db()->prepare('INSERT INTO usuario_perfil (usuario_id, perfil_id) VALUES (?,?)');
            foreach ($pids as $pid) {
                $ins->execute([$newId, $pid]);
            }
            flash('ok', 'Usuario creado.');
            redirect('/pages/usuarios.php');
        }
    }
}

$sql = 'SELECT u.id, u.email, u.nombre, u.apellidos, u.activo,
        GROUP_CONCAT(p.codigo ORDER BY p.codigo SEPARATOR ", ") AS perfiles
        FROM usuarios u
        LEFT JOIN usuario_perfil up ON up.usuario_id = u.id
        LEFT JOIN perfiles p ON p.id = up.perfil_id
        GROUP BY u.id, u.email, u.nombre, u.apellidos, u.activo
        ORDER BY u.nombre';
$lista = db()->query($sql)->fetchAll();

require dirname(__DIR__) . '/includes/layout/header.php';
?>

<?php if (flash('ok')) : ?>
  <div class="alert alert-success"><?= h((string) flash('ok')) ?></div>
<?php endif; ?>

<div class="card" style="margin-bottom:1.5rem;">
  <div class="card-header"><h2>Nuevo usuario</h2></div>
  <form method="post" class="form-grid cols-2">
    <?= csrf_field() ?>
    <input type="hidden" name="action" value="save">
    <div>
      <label class="field" for="email">Email</label>
      <input type="email" id="email" name="email" required autocomplete="off">
    </div>
    <div>
      <label class="field" for="password">Contraseña</label>
      <input type="password" id="password" name="password" required autocomplete="new-password">
    </div>
    <div>
      <label class="field" for="nombre">Nombre</label>
      <input type="text" id="nombre" name="nombre" required>
    </div>
    <div>
      <label class="field" for="apellidos">Apellidos</label>
      <input type="text" id="apellidos" name="apellidos">
    </div>
    <div style="grid-column:1/-1;">
      <span class="field">Perfiles</span>
      <div style="display:flex;flex-wrap:wrap;gap:0.75rem;margin-top:0.35rem;">
        <?php foreach ($perfilesAll as $pf) : ?>
          <label style="display:flex;align-items:center;gap:0.35rem;cursor:pointer;">
            <input type="checkbox" name="perfiles[]" value="<?= (int) $pf['id'] ?>">
            <?= h($pf['nombre']) ?>
          </label>
        <?php endforeach; ?>
      </div>
    </div>
    <div>
      <label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;margin-top:1.5rem;">
        <input type="checkbox" name="activo" value="1" checked> Activo
      </label>
    </div>
    <div class="form-actions" style="grid-column:1/-1;">
      <button type="submit" class="btn btn-primary">Crear usuario</button>
    </div>
  </form>
</div>

<div class="card">
  <div class="card-header"><h2>Cuentas</h2></div>
  <div class="table-wrap">
    <table class="data-table">
      <thead>
        <tr>
          <th>Email</th>
          <th>Nombre</th>
          <th>Perfiles</th>
          <th>Activo</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($lista as $row) : ?>
          <tr>
            <td><?= h($row['email']) ?></td>
            <td><?= h(trim($row['nombre'] . ' ' . ($row['apellidos'] ?? ''))) ?></td>
            <td><?= h($row['perfiles'] ?? '—') ?></td>
            <td><?= (int) $row['activo'] ? 'Sí' : 'No' ?></td>
            <td>
              <?php if ((int) $row['id'] !== (int) (current_user()['id'] ?? 0)) : ?>
                <form method="post" style="display:inline;" onsubmit="return confirm('¿Eliminar usuario?');">
                  <?= csrf_field() ?>
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int) $row['id'] ?>">
                  <button type="submit" class="btn btn-danger" style="padding:0.25rem 0.5rem;font-size:0.8rem;">Eliminar</button>
                </form>
              <?php else : ?>
                <span class="badge badge-muted">Tú</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require dirname(__DIR__) . '/includes/layout/footer.php'; ?>
