<?php
// admin/subscriber_view_data_lib.php
// Stage 12: one shared source for subscriber display identity/state used by quick/modal views.

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/ppp_active_cache_lib.php';
if (is_file(__DIR__ . '/subscriber_mikrotik_watch_lib.php')) require_once __DIR__ . '/subscriber_mikrotik_watch_lib.php';
if (is_file(__DIR__ . '/mac_vendor_lib.php')) require_once __DIR__ . '/mac_vendor_lib.php';

if (!function_exists('subscriber_view_norm_user')) {
  function subscriber_view_norm_user(string $u): string {
    if (function_exists('mtwatch_norm_user')) return mtwatch_norm_user($u);
    $u = trim($u);
    $u = preg_replace('/@.*/', '', $u);
    return trim((string)$u);
  }
}

if (!function_exists('subscriber_view_norm_mac')) {
  function subscriber_view_norm_mac(string $mac): string {
    if (function_exists('mtwatch_norm_mac')) return mtwatch_norm_mac($mac);
    $mac = strtoupper(trim($mac));
    $mac = preg_replace('/[^A-F0-9]/', '', $mac) ?? '';
    if (strlen($mac) === 12) return implode(':', str_split($mac, 2));
    return trim($mac);
  }
}

if (!function_exists('subscriber_view_fetch_row')) {
  function subscriber_view_fetch_row(mysqli $conn, int $id, bool $includeDeleted = true): ?array {
    if ($id <= 0) return null;
    $where = 'id=' . (int)$id;
    if (!$includeDeleted && function_exists('col_exists') && col_exists($conn, 'subscribers', 'is_deleted')) {
      $where .= ' AND COALESCE(is_deleted,0)=0';
    }
    $rs = @$conn->query('SELECT * FROM subscribers WHERE ' . $where . ' LIMIT 1');
    if (!$rs || !$rs->num_rows) return null;
    $row = $rs->fetch_assoc();
    return is_array($row) ? $row : null;
  }
}

if (!function_exists('subscriber_view_identity')) {
  function subscriber_view_identity(array $sub): array {
    $pppUser = trim((string)($sub['ppp_username'] ?? ''));
    if ($pppUser === '') $pppUser = trim((string)($sub['username'] ?? ''));

    $pppPass = trim((string)($sub['ppp_password'] ?? ''));
    if ($pppPass === '') $pppPass = trim((string)($sub['password_plain'] ?? ''));
    if ($pppPass === '') $pppPass = trim((string)($sub['sub_password'] ?? ''));

    $pppProfile = trim((string)($sub['ppp_profile'] ?? ''));
    if ($pppProfile === '') $pppProfile = trim((string)($sub['pppoe_profile'] ?? ''));
    if ($pppProfile === '') $pppProfile = trim((string)($sub['mt_profile'] ?? ''));
    if ($pppProfile === '') $pppProfile = trim((string)($sub['profile'] ?? ''));

    $fullName = trim((string)($sub['full_name'] ?? ''));
    if ($fullName === '') $fullName = $pppUser !== '' ? $pppUser : '—';

    $status = trim((string)($sub['status'] ?? ''));
    $isDisabled = (!empty($sub['ppp_is_disabled']) || !empty($sub['mt_disabled']) || (function_exists('mb_stripos') && $status !== '' && mb_stripos($status, 'cut') !== false));

    return [
      'id' => (int)($sub['id'] ?? 0),
      'full_name' => $fullName,
      'username' => (string)($sub['username'] ?? ''),
      'ppp_username' => $pppUser,
      'ppp_username_norm' => subscriber_view_norm_user($pppUser),
      'ppp_password' => $pppPass,
      'ppp_profile' => $pppProfile,
      'status' => $status !== '' ? $status : ($isDisabled ? 'مفصول' : 'نشط'),
      'is_deleted' => !empty($sub['is_deleted']),
      'is_online_db' => !empty($sub['is_online']),
      'is_disabled_db' => $isDisabled,
    ];
  }
}

if (!function_exists('subscriber_view_runtime_state')) {
  function subscriber_view_runtime_state(mysqli $conn, array $sub, bool $allowRefresh = false): array {
    $id = subscriber_view_identity($sub);
    $pppUserNorm = (string)($id['ppp_username_norm'] ?? '');

    $activeRow = [];
    try {
      $cache = function_exists('ua_ppp_cache_rebuild') && $allowRefresh
        ? ua_ppp_cache_rebuild($conn, 10, false)
        : (function_exists('ua_ppp_cache_snapshot') ? ua_ppp_cache_snapshot(86400) : []);
      foreach ((array)($cache['rows'] ?? []) as $r) {
        $ru = subscriber_view_norm_user((string)($r['name'] ?? ''));
        if ($ru !== '' && $ru === $pppUserNorm) { $activeRow = $r; break; }
      }
    } catch (Throwable $e) {}

    $mtReality = [];
    try {
      $map = function_exists('mt_ppp_secret_reality_map_cached') ? mt_ppp_secret_reality_map_cached($conn, 120, $allowRefresh) : [];
      if ($pppUserNorm !== '' && isset($map[$pppUserNorm]) && is_array($map[$pppUserNorm])) $mtReality = $map[$pppUserNorm];
    } catch (Throwable $e) {}

    $currentIp = trim((string)($activeRow['address'] ?? $sub['current_ip'] ?? $sub['ip_address'] ?? ''));
    $currentMac = subscriber_view_norm_mac((string)($activeRow['caller_id'] ?? $sub['current_caller_id'] ?? ''));
    $currentUptime = trim((string)($activeRow['uptime'] ?? $sub['current_uptime'] ?? ''));
    $lastMac = subscriber_view_norm_mac((string)($mtReality['last_caller_id'] ?? $sub['last_caller_id'] ?? ''));
    $lastLogout = trim((string)($mtReality['last_logged_out'] ?? $sub['mt_last_logged_out'] ?? $sub['last_disconnect_at'] ?? ''));
    $lastReason = trim((string)($mtReality['last_disconnect_reason'] ?? $sub['mt_last_disconnect_reason'] ?? ''));

    $isOnline = !empty($activeRow) ? true : (bool)($id['is_online_db'] ?? false);
    $isDisabled = (bool)($id['is_disabled_db'] ?? false);
    if (isset($mtReality['disabled'])) {
      $v = $mtReality['disabled'];
      $isDisabled = ($v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes');
    }

    return [
      'active_row' => $activeRow,
      'mikrotik_reality' => $mtReality,
      'current_ip' => $currentIp,
      'current_mac' => $currentMac,
      'current_uptime' => $currentUptime,
      'last_mac' => $lastMac,
      'last_logout' => $lastLogout,
      'last_reason' => $lastReason,
      'is_online' => $isOnline,
      'is_disabled' => $isDisabled,
    ];
  }
}

if (!function_exists('subscriber_view_load')) {
  function subscriber_view_load(mysqli $conn, int $id, bool $includeDeleted = true, bool $allowRefresh = false): ?array {
    $row = subscriber_view_fetch_row($conn, $id, $includeDeleted);
    if (!$row) return null;
    $identity = subscriber_view_identity($row);
    $runtime = subscriber_view_runtime_state($conn, $row, $allowRefresh);
    return ['row' => $row, 'identity' => $identity, 'runtime' => $runtime];
  }
}
