<?php
require_once __DIR__ . '/../app/lib/auth.php';
require_once __DIR__ . '/../app/lib/util.php';
require_login();
require_role(['admin']);

$user = current_user();
$flash_success = flash_get('success');
$flash_error = flash_get('error');

if ($_SERVER['REQUEST_METHOD']==='POST') {
  $action = $_POST['action'] ?? '';
  if ($action==='create') {
    $username = trim($_POST['username'] ?? '');
    $pass = (string)($_POST['password'] ?? '');
    $role = $_POST['role'] ?? 'empleado';
    if ($username==='' || $pass==='') {
      flash_set('error','Completa usuario y clave.');
      redirect('users.php');
    }
    $hash = password_hash($pass, PASSWORD_DEFAULT);
    try {
      q("INSERT INTO users(username,password_hash,role,active) VALUES(?,?,?,1)", [$username,$hash,$role]);
      flash_set('success','Usuario creado.');
    } catch (Exception $e) {
      flash_set('error','Error: '.$e->getMessage());
    }
    redirect('users.php');
  }
  if ($action==='toggle') {
    $id = (int)($_POST['id'] ?? 0);
    $u = one("SELECT active FROM users WHERE id=?", [$id]);
    if ($u) {
      $new = ((int)$u['active']===1) ? 0 : 1;
      q("UPDATE users SET active=? WHERE id=?", [$new,$id]);
      flash_set('success','Actualizado.');
    }
    redirect('users.php');
  }
  if ($action==='reset') {
    $id = (int)($_POST['id'] ?? 0);
    $newPass = (string)($_POST['newpass'] ?? '');
    if ($newPass==='') { flash_set('error','Escribe nueva clave.'); redirect('users.php'); }
    $hash = password_hash($newPass, PASSWORD_DEFAULT);
    q("UPDATE users SET password_hash=? WHERE id=?", [$hash,$id]);
    flash_set('success','Clave actualizada.');
    redirect('users.php');
  }
}

$users = all("SELECT id, username, role, active, created_at FROM users ORDER BY id");
ob_start();
?>
<div class="card p-3">
  <div class="d-flex justify-content-between align-items-center">
    <h4 class="mb-0">Usuarios</h4>
    <a class="btn btn-warning btn-sm" href="dashboard.php">Regresar</a>
  </div>

  <hr>
  <h5>Crear usuario</h5>
  <form method="post" class="mb-3">
    <input type="hidden" name="action" value="create">
    <div class="form-row">
      <div class="form-group col-md-4">
        <input class="form-control" name="username" placeholder="Usuario" required>
      </div>
      <div class="form-group col-md-4">
        <input class="form-control" type="password" name="password" placeholder="Clave" required>
      </div>
      <div class="form-group col-md-4">
        <select class="form-control" name="role">
          <option value="empleado">empleado</option>
          <option value="monitor">monitor</option>
          <option value="admin">admin</option>
        </select>
      </div>
    </div>
    <button class="btn btn-success btn-sm">Crear</button>
  </form>

  <h5>Listado</h5>
  <div class="table-responsive">
    <table class="table table-sm table-bordered">
      <thead><tr><th>ID</th><th>Usuario</th><th>Rol</th><th>Activo</th><th>Acciones</th></tr></thead>
      <tbody>
      <?php foreach($users as $u): ?>
        <tr>
          <td><?= h($u['id']) ?></td>
          <td><?= h($u['username']) ?></td>
          <td><?= h($u['role']) ?></td>
          <td><?= ((int)$u['active']===1)?'Sí':'No' ?></td>
          <td style="min-width:360px;">
            <form method="post" class="d-inline">
              <input type="hidden" name="action" value="toggle">
              <input type="hidden" name="id" value="<?= h($u['id']) ?>">
              <button class="btn btn-warning btn-sm"><?= ((int)$u['active']===1)?'Desactivar':'Activar' ?></button>
            </form>
            <form method="post" class="d-inline">
              <input type="hidden" name="action" value="reset">
              <input type="hidden" name="id" value="<?= h($u['id']) ?>">
              <input class="form-control form-control-sm d-inline" style="width:160px;" name="newpass" placeholder="Nueva clave">
              <button class="btn btn-danger btn-sm">Reset</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php
$content = ob_get_clean();
$title="Usuarios";
require __DIR__ . '/../app/views/layout.php';
