<?php
// admin/ppp_speed_map.php
// Map subscriber speed/package/username to MikroTik PPP profile name.
// Important: words like "مفتوح" should not force UNLIMITED automatically,
// because in this system they may mean open quota, not open speed.

if (!function_exists('ppp_profile_from_username')) {
  function ppp_profile_from_username(string $username = '', string $fallback = ''): string {
    $u = trim($username);
    if ($u !== '' && preg_match('/^ppp\s*(\d+)\s*m/i', $u, $m)) {
      $n = (int)($m[1] ?? 0);
      if ($n > 0) return 'PPPOE-' . $n . 'M';
    }
    return $fallback !== '' ? $fallback : '';
  }
}

if (!function_exists('ppp_profile_from_speed')) {
  function ppp_profile_from_speed(string $speed_name = '', string $package_name = '', string $fallback = 'pppoe-profile'): string {
    $s = strtoupper(trim($speed_name));
    $p = trim($package_name);
    $fb = strtoupper(trim($fallback));

    // If speed_name itself already looks like a MikroTik profile, trust it.
    if ($s !== '' && (strpos($s, 'PPPOE-') === 0 || strpos($s, 'HOTSPOT') === 0)) return $s;

    // If fallback is already a concrete MikroTik profile (including explicit UNLIMITED), trust it.
    if ($fb !== '' && ($fb === 'UNLIMITED' || $fb === 'LASER-UNLIMITED' || strpos($fb, 'PPPOE-') === 0 || strpos($fb, 'HOTSPOT') === 0)) {
      return $fb;
    }

    // Match like 1M, 2M, 4M, 8M, 16M from speed name first.
    if (preg_match('/(\d+)\s*M/i', $s, $m)) {
      $n = (int)$m[1];
      if ($n > 0) return 'PPPOE-' . $n . 'M';
    }

    // Match like 1 Mbps, 2 Mbps.
    if (preg_match('/(\d+)\s*(MBPS|MBS)/i', $s, $m)) {
      $n = (int)$m[1];
      if ($n > 0) return 'PPPOE-' . $n . 'M';
    }

    // If package_name has speed hint like 2M-50G, use it.
    if ($p !== '' && preg_match('/(\d+)\s*M/i', strtoupper($p), $m2)) {
      $n = (int)$m2[1];
      if ($n > 0) return 'PPPOE-' . $n . 'M';
    }

    // Do NOT auto-convert words like "مفتوح" or "غير محدود" to UNLIMITED.
    // In this panel they may describe quota/package, not line speed.
    return $fallback !== '' ? $fallback : 'pppoe-profile';
  }
}
