<?php
require_once __DIR__ . '/../auth.php';
if (function_exists('require_login')) require_login('login.php');
if (function_exists('require_any_perm')) require_any_perm(['can_view_dashboard_stats','can_view_dashboard_summary']);
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../ua_unified_stats_lib.php';
require_once __DIR__ . '/../stats_snapshot_lib.php';
require_once __DIR__ . '/../billing_cycle_lib.php';
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }
header('Content-Type: application/json; charset=utf-8');
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
  echo json_encode([
    'ok'=>false,'reason'=>'db_not_ready','ppp_active'=>0,'total'=>0,'online'=>0,'offline'=>0,
    'financial_cut'=>0,'disabled'=>0,'unsafe_speed'=>0,'open_all_mode'=>0,
    'online_source'=>'none','disabled_source'=>'none',
    'billing'=>['invoice_generated_pending'=>0,'pending_limit_approvals'=>0,'pending_cut_approvals'=>0,'cycle_label'=>'']
  ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}
mysqli_report(MYSQLI_REPORT_OFF);
$force = ((string)($_GET['force'] ?? '') === '1');
$out = ua_app_stats_snapshot($conn, 8, $force);
$out['billing'] = ['invoice_generated_pending'=>0,'pending_limit_approvals'=>0,'pending_cut_approvals'=>0,'cycle_label'=>''];
try {
  if ($force && function_exists('billing_cycle_generate_current')) billing_cycle_generate_current($conn, false);
  if (function_exists('billing_dashboard_stats')) $out['billing'] = billing_dashboard_stats($conn);
} catch (Throwable $e) {
  $out['billing_error'] = $e->getMessage();
}
echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
