<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../../app/auth.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/helpers.php';

start_session();
require_login();

// Solo ADMIN o SECRETARIA (ajustá si querés)
if (!(has_role('ADMIN') || has_role('SECRETARIA'))) {
  http_response_code(403);
  die("Acceso no permitido");
}

$pdo = db();
$msg = null;
$createdPass = null;

// Crear usuario
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
  csrf_check();

  $username = trim($_POST['username'] ?? '');
  $ci = trim($_POST['ci'] ?? '');
  $nombres = trim($_POST['nombres'] ?? '');
  $apellidos = trim($_POST['apellidos'] ?? '');
  $tipo = $_POST['tipo'] ?? 'STAFF';
  $roles = $_POST['roles'] ?? [];

  if ($username === '' || $nombres === '' || $apellidos === '') {
    $msg = "Faltan datos obligatorios (username, nombres, apellidos).";
  } else {
    $plain = random_password(10);
    $hash = password_hash($plain, PASSWORD_BCRYPT);

    try {
      $pdo->prepare(
        "INSERT INTO usuarios (username, ci, password_hash, nombres, apellidos, tipo, activo)
         VALUES (?, ?, ?, ?, ?, ?, 1)"
      )->execute([$username, $ci !== '' ? $ci : null, $hash, $nombres, $apellidos, $tipo]);

      $uid = (int)$pdo->lastInsertId();

      // roles
      if (!empty($roles)) {
        $rStmt = $pdo->prepare("SELECT id FROM roles WHERE nombre = ? LIMIT 1");
        $ins = $pdo->prepare("INSERT INTO usuario_roles (usuario_id, rol_id) VALUES (?, ?)");

        foreach ($roles as $rname) {
          $rStmt->execute([$rname]);
          $row = $rStmt->fetch();
          if ($row) {
            $ins->execute([$uid, (int)$row['id']]);
          }
        }
      }

      $msg = "Usuario creado: $username";
      $createdPass = $plain; // mostrar una vez
    } catch (Throwable $e) {
      $msg = "Error al crear: " . $e->getMessage();
    }
  }
}

// Reset password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'reset') {
  csrf_check();
  $uid = (int)($_POST['user_id'] ?? 0);

  if ($uid > 0) {
    $plain = random_password(10);
    $hash = password_hash($plain, PASSWORD_BCRYPT);

    $pdo->prepare("UPDATE usuarios SET password_hash = ? WHERE id = ?")->execute([$hash, $uid]);
    $msg = "Contraseña reseteada para usuario ID $uid";
    $createdPass = $plain;
  }
}

// Datos para pantalla
$rolesAll = $pdo->query("SELECT nombre FROM roles ORDER BY nombre")->fetchAll();
$users = $pdo->query(
  "SELECT id, username, ci, nombres, apellidos, tipo, activo, ultimo_login
   FROM usuarios
   ORDER BY id DESC
   LIMIT 30"
)->fetchAll();

$title = "Admin - Usuarios";
include __DIR__ . '/../../app/views/header.php';
?>

<h1 class="h5 mb-3">Usuarios</h1>

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

<?php if ($createdPass): ?>
  <div class="alert alert-warning">
    <b>Contraseña generada:</b> <?= htmlspecialchars($createdPass) ?><br>
    (copiala ahora; no se vuelve a mostrar)
  </div>
<?php endif; ?>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <h2 class="h6 mb-3">Crear usuario</h2>

    <form method="post" class="row g-2">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">

      <div class="col-12 col-md-4">
        <label class="form-label">Username</label>
        <input class="form-control" name="username" required>
      </div>

      <div class="col-12 col-md-4">
        <label class="form-label">CI (opcional)</label>
        <input class="form-control" name="ci" placeholder="Ej: 1234567">
      </div>

      <div class="col-12 col-md-4">
        <label class="form-label">Tipo</label>
        <select class="form-select" name="tipo">
          <option value="STAFF">STAFF</option>
          <option value="ALUMNO">ALUMNO</option>
          <option value="TUTOR">TUTOR</option>
        </select>
      </div>

      <div class="col-12 col-md-6">
        <label class="form-label">Nombres</label>
        <input class="form-control" name="nombres" required>
      </div>

      <div class="col-12 col-md-6">
        <label class="form-label">Apellidos</label>
        <input class="form-control" name="apellidos" required>
      </div>

      <div class="col-12">
        <label class="form-label">Roles (podés elegir varios)</label>
        <div class="d-flex flex-wrap gap-2">
          <?php foreach ($rolesAll as $r): ?>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="roles[]"
                     value="<?= htmlspecialchars($r['nombre']) ?>" id="r_<?= htmlspecialchars($r['nombre']) ?>">
              <label class="form-check-label" for="r_<?= htmlspecialchars($r['nombre']) ?>">
                <?= htmlspecialchars($r['nombre']) ?>
              </label>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="col-12">
        <button class="btn btn-primary">Crear</button>
        <a class="btn btn-outline-secondary" href="/Comercio/public/admin/vinculos.php">Vínculos Alumno/Tutor</a>
      </div>
    </form>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <h2 class="h6 mb-3">Últimos usuarios</h2>

    <div class="table-responsive">
      <table class="table table-sm table-bordered bg-white">
        <thead class="table-light">
        <tr>
          <th>ID</th><th>Username</th><th>CI</th><th>Nombre</th><th>Tipo</th><th>Activo</th><th>Último login</th><th>Acción</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
          <tr>
            <td><?= (int)$u['id'] ?></td>
            <td><?= htmlspecialchars($u['username']) ?></td>
            <td><?= htmlspecialchars($u['ci'] ?? '-') ?></td>
            <td><?= htmlspecialchars(($u['nombres'] ?? '').' '.($u['apellidos'] ?? '')) ?></td>
            <td><?= htmlspecialchars($u['tipo']) ?></td>
            <td><?= ((int)$u['activo'] === 1) ? 'SI' : 'NO' ?></td>
            <td><?= htmlspecialchars($u['ultimo_login'] ?? '-') ?></td>
            <td>
              <form method="post" style="display:inline">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
                <input type="hidden" name="action" value="reset">
                <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Resetear contraseña?')">
                  Reset pass
                </button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

  </div>
</div>

<?php include __DIR__ . '/../../app/views/footer.php'; ?>
