<?php
if (session_status() === PHP_SESSION_NONE) { @session_start(); }
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/billing_cycle_lib.php';
ensure_db(true); $conn = $GLOBALS['conn']; header('Content-Type: application/json; charset=utf-8');
$token = trim((string)($_GET['token'] ?? '')); $savedToken = (string)get_app_setting($conn, 'automation_token', '');
$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = PHP_SAPI === 'cli' || in_array($remote, ['127.0.0.1', '::1'], true);
$isSuperSession = function_exists('billing_is_super_admin_actor') && billing_is_super_admin_actor();
$authorized = $savedToken !== '' ? hash_equals($savedToken, $token) : ($isLocal || $isSuperSession);
if (!$authorized) { http_response_code(403); echo json_encode(['ok'=>0,'msg'=>'Unauthorized'], JSON_UNESCAPED_UNICODE); exit; }
$generated = billing_generate_current_cycle_invoices($conn, false); $queued = billing_queue_requests($conn);
echo json_encode(['ok'=>1,'msg'=>'done','generated'=>$generated,'queued'=>$queued,'settings'=>billing_get_settings($conn)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
