<?php
// admin/api/api_common.php
// Stage 7: shared JSON/API primitives. Keeps old names (out/api_require_login) for compatibility.

require_once __DIR__ . '/../app_paths.php';

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
if (!headers_sent()) { header('Content-Type: application/json; charset=utf-8'); }

if (!function_exists('api_json_out')) {
  function api_json_out($payload, int $code = 200, ?int $flags = null): void {
    http_response_code($code);
    if (!headers_sent()) { header('Content-Type: application/json; charset=utf-8'); }
    if ($flags === null) $flags = function_exists('ua_json_flags') ? ua_json_flags() : JSON_UNESCAPED_UNICODE;
    echo json_encode($payload, $flags);
    exit;
  }
}


if (!function_exists('api_json_out_clean')) {
  function api_json_out_clean($payload, int $code = 200, ?int $flags = null): void {
    while (ob_get_level()) { @ob_end_clean(); }
    api_json_out($payload, $code, $flags);
  }
}

if (!function_exists('out')) {
  function out($payload, int $code = 200): void {
    api_json_out($payload, $code);
  }
}

if (!function_exists('api_require_login')) {
  function api_require_login(): void {
    if (function_exists('ua_is_logged_in') ? ua_is_logged_in() : (!empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']))) {
      return;
    }
    api_json_out(['ok'=>false,'code'=>'AUTH','msg'=>'Not logged in'], 401, JSON_UNESCAPED_UNICODE);
  }
}

if (!function_exists('api_ensure_db')) {
  function api_ensure_db(bool $fatal = true): ?mysqli {
    if (!function_exists('ensure_db')) {
      require_once __DIR__ . '/../db_bootstrap.php';
    }
    $conn = ensure_db($fatal);
    return ($conn instanceof mysqli) ? $conn : null;
  }
}
