<?php
if (!function_exists('sub_status_norm_user')) {
  function sub_status_norm_user(string $user): string {
    $user = trim($user);
    $user = preg_replace('/@.*/', '', $user);
    return trim((string)$user);
  }
}

if (!function_exists('sub_status_ppp_active_map')) {
  function sub_status_ppp_active_map(array $pppCache): array {
    $map = [];
    foreach ((array)($pppCache['rows'] ?? []) as $row) {
      if (!is_array($row)) continue;
      $user = '';
      foreach (['name','NAME','user','USER','username','USERNAME'] as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') {
          $user = (string)$row[$key];
          break;
        }
      }
      $user = sub_status_norm_user($user);
      if ($user === '') continue;
      $map[$user] = $row;
    }
    return $map;
  }
}

if (!function_exists('sub_status_active_has_traffic')) {
  function sub_status_active_has_traffic(array $activeRow): bool {
    $rx = (int)($activeRow['rx_bytes'] ?? $activeRow['rx-bytes'] ?? 0);
    $tx = (int)($activeRow['tx_bytes'] ?? $activeRow['tx-bytes'] ?? 0);
    return ($rx + $tx) > 0;
  }
}

if (!function_exists('sub_status_is_limited')) {
  function sub_status_is_limited(array $row): bool {
    $state = strtoupper(trim((string)($row['speed_state'] ?? '')));
    if (in_array($state, ['LIMIT','LIMITED','REDUCED','THROTTLED'], true)) return true;

    $current = trim((string)($row['current_speed'] ?? ''));
    $base = trim((string)($row['base_speed'] ?? ''));
    if ($current !== '' && $base !== '' && strcasecmp($current, $base) !== 0) return true;

    return false;
  }
}

if (!function_exists('sub_status_is_stopped')) {
  function sub_status_is_stopped(array $row, bool $isDisabled): bool {
    // The caller has already reconciled local flags with the latest verified
    // RouterOS secret. Re-reading stale CUT fields here can revive an obsolete
    // stopped state after the account has been enabled on the router.
    return $isDisabled;
  }
}

if (!function_exists('sub_status_info')) {
  function sub_status_info(bool $isOnline, bool $isDisabled, array $row = [], ?array $activeRow = null): array {
    if (sub_status_is_stopped($row, $isDisabled)) {
      return ['key' => 'stopped', 'class' => 'is-stopped', 'label' => 'متوقف'];
    }
    if (sub_status_is_limited($row)) {
      return ['key' => 'limited', 'class' => 'is-limited', 'label' => 'تخفيض سرعة'];
    }
    if (!$isOnline) {
      return ['key' => 'offline', 'class' => 'is-offline', 'label' => 'غير متصل'];
    }
    // A row in /ppp active proves connectivity even while byte counters are
    // idle or unavailable. Zero traffic must not downgrade an active session.
    if ($activeRow) {
      return ['key' => 'online', 'class' => 'is-online', 'label' => 'متصل بالإنترنت'];
    }
    return ['key' => 'connected', 'class' => 'is-connected', 'label' => 'متصل'];
  }
}
