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

require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/billing_cycle_lib.php';
require_once __DIR__ . '/api/api_common.php';

if (!function_exists('billing_json_out')) {
  function billing_json_out(array $payload, int $code = 200): void {
    api_json_out($payload, $code, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  }
}

$conn = ensure_db(true);
if (!($conn instanceof mysqli)) {
  billing_json_out(['ok' => false, 'items' => [], 'count' => 0, 'message' => 'db_not_ready'], 500);
}

require_login('login.php');

$payload = billing_get_alert_payload($conn);
$items = [];
$pending = $payload['pending'] ?? [];
$cleanup = $payload['cleanup'] ?? [];
$generation = $payload['generation'] ?? [];

if ((int)($generation['pricing_missing'] ?? 0) > 0) {
  $items[] = ['type' => 'pricing_missing', 'count' => (int)$generation['pricing_missing'], 'href' => 'subscribers.php'];
}

if ((int)($pending['reminder'] ?? 0) > 0) {
  $items[] = ['type' => 'reminder', 'count' => (int)$pending['reminder'], 'href' => 'billing_message_requests.php'];
}
if ((int)($pending['limit'] ?? 0) > 0) {
  $items[] = ['type' => 'limit', 'count' => (int)$pending['limit'], 'href' => 'billing_limit_requests.php'];
}
if ((int)($pending['cut'] ?? 0) > 0) {
  $items[] = ['type' => 'cut', 'count' => (int)$pending['cut'], 'href' => 'billing_cut_requests.php'];
}
$payload['items'] = $items;
$payload['count'] = count($items);
billing_json_out($payload);
