<?php
// includes/api_bootstrap.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../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");

/* TZ + charset MySQL */
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'");
}

/* Helpers JSON */
function json_err($msg, $extra = []) {
  echo json_encode(["success"=>false, "message"=>$msg] + $extra, JSON_UNESCAPED_UNICODE); exit;
}
function json_ok($payload = []) {
  echo json_encode(["success"=>true] + $payload, JSON_UNESCAPED_UNICODE); exit;
}

/* Helper sin mysqlnd: fetch assoc para prepared statements */
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;
  }
}

/* Helper seguro para enteros opcionales (NULL si vacío) */
function as_nullable_int($v) {
  if ($v === null) return null;
  $v = trim((string)$v);
  return ($v === '') ? null : (int)$v;
}

/* Evita notices de salida previa */
if (function_exists('fastcgi_finish_request')) { /* noop */ }
