<?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, 'message' => 'db_not_ready'], 500);
}

require_login('login.php');
if (function_exists('require_perm')) { @require_perm('can_pppoe_cut_restore'); }
if (!billing_is_super_admin_actor()) {
  billing_json_out(['ok' => false, 'message' => 'super_admin_required'], 403);
}

$input = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($input)) $input = [];
$input = array_replace($_GET, $_POST, $input);

$ids = $input['ids'] ?? [];
if (!is_array($ids)) {
  $ids = [$ids];
}

$queueId = (int)($input['queue_id'] ?? 0);
if ($queueId > 0) {
  $ids[] = $queueId;
}

$ids = array_values(array_unique(array_filter(array_map('intval', $ids), fn($v) => $v > 0)));
$actionType = strtoupper(trim((string)($input['action_type'] ?? '')));

if ($actionType === '' && count($ids) === 1 && function_exists('table_exists') && table_exists($conn, 'billing_action_requests')) {
  $id = (int)$ids[0];
  $res = @$conn->query("SELECT action_type FROM billing_action_requests WHERE id={$id} LIMIT 1");
  if ($res && ($row = $res->fetch_assoc())) {
    $actionType = strtoupper(trim((string)($row['action_type'] ?? '')));
  }
}

if (!in_array($actionType, ['REMINDER', 'LIMIT', 'CUT'], true)) {
  billing_json_out(['ok' => false, 'message' => 'action_type_required'], 422);
}

if (!$ids) {
  billing_json_out(['ok' => false, 'message' => 'ids_required'], 422);
}

$approvedBy = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
$result = billing_approve_requests($conn, $actionType, $ids, $approvedBy);
billing_json_out($result, !empty($result['ok']) ? 200 : 422);
