<?php
session_start();
require_once "../config/conexion.php";

/* Cabeceras anti-caché + JSON */
header("Content-Type: application/json; charset=utf-8");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: 0");

/* Zona horaria y charset */
date_default_timezone_set('America/Lima');
if (isset($conexion) && $conexion instanceof mysqli) {
  @mysqli_set_charset($conexion, 'utf8');
  @mysqli_query($conexion, "SET time_zone = '-05:00'");
}

/* Helper: fetch assoc sin mysqlnd (reemplaza get_result) */
if (!function_exists('stmt_fetch_all_assoc')) {
  function stmt_fetch_all_assoc(mysqli_stmt $stmt): array {
    $stmt->store_result();
    $meta = $stmt->result_metadata();
    if (!$meta) return [];
    $row = [];
    $bind = [];
    while ($field = $meta->fetch_field()) { $bind[] = &$row[$field->name]; }
    call_user_func_array([$stmt, 'bind_result'], $bind);
    $out = [];
    while ($stmt->fetch()) { $out[] = array_map(fn($v) => $v, $row); }
    $stmt->free_result();
    return $out;
  }
}

$accion = $_GET['accion'] ?? '';

if ($accion === 'obtener') {
  $stmt = $conexion->prepare("SELECT id, nombre, usuario, rol, email, estado FROM usuarios");
  $stmt->execute();
  $usuarios = stmt_fetch_all_assoc($stmt);

  // permisos por rol
  $rolSesion = $_SESSION['rol'] ?? '';
  foreach ($usuarios as &$fila) {
    $permisos = [];
    if (in_array($rolSesion, ['Administrador', 'Supervisor'])) {
      $permisos = ['editar', 'eliminar'];
    } elseif ($rolSesion === 'Registrador y Reportes') {
      $permisos = ['editar'];
    }
    $fila['permisos'] = $permisos;
  }

  echo json_encode($usuarios, JSON_UNESCAPED_UNICODE);
  exit;
}

if ($accion === 'obtenerUno') {
  $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
  if ($id <= 0) { echo json_encode(null); exit; }

  $stmt = $conexion->prepare("SELECT id, nombre, usuario, rol, email, estado FROM usuarios WHERE id = ?");
  $stmt->bind_param("i", $id);
  $stmt->execute();
  $fila = stmt_fetch_all_assoc($stmt);
  echo json_encode($fila[0] ?? null, JSON_UNESCAPED_UNICODE);
  exit;
}

echo json_encode(['success'=>false,'message'=>'Acción no válida'], JSON_UNESCAPED_UNICODE);
