<?php
/**
 * TechShop Perú - Panel Admin Aislado: Gestión de Usuarios
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

require_admin();
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        set_flash('error', 'Token inválido.');
    } else {
        $user_id = (int)($_POST['user_id'] ?? 0);
        $rol = in_array($_POST['rol'] ?? '', ['cliente','admin'], true) ? $_POST['rol'] : 'cliente';
        $activo = isset($_POST['activo']) ? 1 : 0;

        if ($user_id !== (int)$_SESSION['usuario_id']) {
            $stmt = $db->prepare('UPDATE usuarios SET rol = ?, activo = ? WHERE id = ?');
            $stmt->execute([$rol, $activo, $user_id]);
            set_flash('success', 'Usuario actualizado correctamente.');
        } else {
            set_flash('warning', 'No puedes modificar tus propios permisos de administrador.');
        }
    }
    csrf_regenerate();
    redirect('panel-admin-tech/usuarios.php');
}

$stmt = $db->query('SELECT id, nombres, apellidos, email, rol, activo, fecha_registro FROM usuarios ORDER BY id DESC');
$usuarios = $stmt->fetchAll();

$page_title = 'Gestión de Usuarios';
require_once __DIR__ . '/views/layout.php';
?>

<div class="table-responsive bg-white rounded shadow-sm p-3">
  <table class="table table-hover align-middle mb-0">
    <thead class="table-light">
      <tr><th>Nombre</th><th>Email</th><th>Rol</th><th>Registro</th><th>Estado</th><th>Acción</th></tr>
    </thead>
    <tbody>
      <?php foreach ($usuarios as $u): ?>
      <tr>
        <td class="fw-bold"><?= e($u['nombres'] . ' ' . $u['apellidos']) ?></td>
        <td><?= e($u['email']) ?></td>
        <td><span class="badge <?= $u['rol'] === 'admin' ? 'bg-primary' : 'bg-secondary' ?>"><?= strtoupper(e($u['rol'])) ?></span></td>
        <td><?= format_fecha($u['fecha_registro']) ?></td>
        <td><?= $u['activo'] ? '<span class="badge bg-success">Activo</span>' : '<span class="badge bg-danger">Inactivo</span>' ?></td>
        <td>
          <?php if ((int)$u['id'] !== (int)$_SESSION['usuario_id']): ?>
          <form method="POST" class="d-flex gap-2 align-items-center">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
            <select name="rol" class="form-select form-select-sm" style="width:auto;">
              <option value="cliente" <?= $u['rol'] === 'cliente' ? 'selected' : '' ?>>Cliente</option>
              <option value="admin" <?= $u['rol'] === 'admin' ? 'selected' : '' ?>>Admin</option>
            </select>
            <div class="form-check form-switch ms-1">
              <input class="form-check-input" type="checkbox" name="activo" <?= $u['activo'] ? 'checked' : '' ?>>
            </div>
            <button type="submit" class="btn btn-sm btn-primary">Guardar</button>
          </form>
          <?php else: ?>
          <span class="badge bg-light text-dark border">Tu sesión</span>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
