<?php
$title = 'Administradores';
require_once __DIR__ . '/../templates/header.php';
require_role('superadmin');
csrf_check();

$err = null;
$notice = null;

// Procesar formulario para agregar admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_admin') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!$name || !$email || !$password) {
        $err = 'Todos los campos son obligatorios.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $err = 'Correo inválido.';
    } else {
        // Verificar que el email no exista
        $existing = pdo()->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
        $existing->execute([$email]);
        if ($existing->fetch()) {
            $err = 'Ya existe un administrador con ese correo.';
        } else {
            // Insertar nuevo admin
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = pdo()->prepare('INSERT INTO users (name, email, password_hash, role, active, created_at) VALUES (?, ?, ?, "admin", 1, NOW())');
            try {
                $stmt->execute([$name, $email, $hash]);
                $newAdminId = pdo()->lastInsertId();

                // Actualizar admin_id para que sea igual a su propio id
                $updateStmt = pdo()->prepare('UPDATE users SET admin_id = ? WHERE id = ?');
                $updateStmt->execute([$newAdminId, $newAdminId]);

                $notice = 'Administrador agregado con éxito y admin_id asignado.';
            } catch (PDOException $e) {
                $err = 'Error al agregar administrador: ' . $e->getMessage();
            }
        }
    }
}

// Manejar eliminación de admin (opcional)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_admin') {
    $delete_id = (int)($_POST['id'] ?? 0);
    if ($delete_id > 0) {
        $stmt = pdo()->prepare('DELETE FROM users WHERE id = ? AND role = "admin"');
        try {
            $stmt->execute([$delete_id]);
            $notice = 'Administrador eliminado.';
        } catch (PDOException $e) {
            $err = 'Error eliminando administrador: ' . $e->getMessage();
        }
    }
}

// Obtener lista de admins
$admins = pdo()->query('SELECT id, name, email, active, created_at FROM users WHERE role = "admin" ORDER BY name')->fetchAll();
?>

<h3>Administradores</h3>

<?php if ($notice): ?>
<div class="alert alert-success"><?= e($notice) ?></div>
<?php endif; ?>
<?php if ($err): ?>
<div class="alert alert-danger"><?= e($err) ?></div>
<?php endif; ?>

<!-- Formulario de nuevo admin -->
<div class="card card-body mb-4">
  <form method="post" novalidate>
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="action" value="add_admin">

    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label" for="name">Nombre</label>
        <input type="text" class="form-control" id="name" name="name" required>
      </div>
      <div class="col-md-4">
        <label class="form-label" for="email">Correo</label>
        <input type="email" class="form-control" id="email" name="email" required>
      </div>
      <div class="col-md-4">
        <label class="form-label" for="password">Contraseña</label>
        <input type="password" class="form-control" id="password" name="password" required>
      </div>
    </div>
    <div class="mt-3">
      <button type="submit" class="btn btn-success">Agregar Administrador</button>
    </div>
  </form>
</div>

<!-- Lista de administradores -->
<table class="table table-striped align-middle">
  <thead>
    <tr>
      <th>Nombre</th>
      <th>Correo</th>
      <th>Activo</th>
      <th>Creado</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($admins as $admin): ?>
    <tr>
      <td><?= e($admin['name']) ?></td>
      <td><?= e($admin['email']) ?></td>
      <td><?= $admin['active'] ? 'Sí' : 'No' ?></td>
      <td><?= e($admin['created_at']) ?></td>
      <td>
        <form method="post" class="d-inline" onsubmit="return confirm('¿Eliminar este administrador?');">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="action" value="delete_admin">
          <input type="hidden" name="id" value="<?= e($admin['id']) ?>">
          <button class="btn btn-sm btn-outline-danger">Eliminar</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
