<?php
require_once __DIR__ . '/../admin/db_bootstrap.php';
require_once __DIR__ . '/../admin/billing_cycle_lib.php';

$conn = ensure_db(true);
if (!($conn instanceof mysqli)) {
  http_response_code(500);
  exit("DB_NOT_READY\n");
}
$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);
if (($savedToken !== '' && !hash_equals($savedToken, $token)) || ($savedToken === '' && !$isLocal)) {
  http_response_code(403);
  exit("UNAUTHORIZED\n");
}
$result = billing_generate_current_cycle_invoices($conn, false);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
