<?php
/**
 * Dedicated Android subscriber list.
 * Loaded by subscribers.php after authentication and data preparation.
 */
$page_title = 'قائمة المشتركين';
$UA_FORCE_DESIGN_V2 = true;
$UA_PAGE_CSS = ['assets/css/android_subscribers.css'];
$androidPageSize = 12;
$androidPage = max(1, (int)($_GET['page'] ?? 1));
$androidTotalPages = max(1, (int)ceil(max(0, $totalRows) / $androidPageSize));
if ($androidPage > $androidTotalPages) $androidPage = $androidTotalPages;
$androidOffset = ($androidPage - 1) * $androidPageSize;
$androidRows = array_slice($subscribersRows, $androidOffset, $androidPageSize);

$androidQuery = static function(array $changes = []) use ($q, $filter, $sort): string {
  $params = ['q' => $q, 'filter' => $filter, 'sort' => $sort];
  foreach ($changes as $key => $value) {
    if ($value === null || $value === '') unset($params[$key]);
    else $params[$key] = $value;
  }
  if (($params['filter'] ?? 'all') === 'all') unset($params['filter']);
  if (($params['sort'] ?? '') === '') unset($params['sort']);
  if (($params['q'] ?? '') === '') unset($params['q']);
  return $params ? ('?' . http_build_query($params)) : '';
};

require_once __DIR__ . '/header.php';
?>
<div class="content-wrapper android-subscribers" data-android-subscribers>
  <main class="as-main">
    <section class="as-heading-card">
      <div class="as-heading-row">
        <div>
          <span class="as-kicker">إدارة الحسابات</span>
          <h1>قائمة المشتركين</h1>
          <p>عرض واضح وسريع مصمم لشاشة الهاتف</p>
        </div>
        <div class="as-heading-actions">
          <a class="as-contract-button" href="subscriber_contracts.php?ua_android=1" aria-label="عقود المشتركين">
            <i class="fa fa-file-word-o" aria-hidden="true"></i><span>العقود</span>
          </a>
          <a class="as-add-button" href="subscribers_add.php" aria-label="إضافة مشترك جديد">
            <i class="fa fa-user-plus" aria-hidden="true"></i><span>إضافة</span>
          </a>
        </div>
      </div>

      <div class="as-stats" aria-label="إحصاءات المشتركين">
        <div><strong><?= (int)($footerCounts['total'] ?? 0) ?></strong><span>الكل</span></div>
        <div class="is-online"><strong><?= (int)($footerCounts['online'] ?? 0) ?></strong><span>متصل</span></div>
        <div class="is-offline"><strong><?= (int)($footerCounts['offline'] ?? 0) ?></strong><span>غير متصل</span></div>
        <div class="is-disabled"><strong><?= (int)($footerCounts['disabled'] ?? 0) ?></strong><span>مفصول</span></div>
      </div>
    </section>

    <?php if ($flash_success !== '' || $flash_warning !== ''): ?>
      <div class="as-alert <?= $flash_warning !== '' ? 'is-warning' : 'is-success' ?>">
        <i class="fa <?= $flash_warning !== '' ? 'fa-exclamation-triangle' : 'fa-check-circle' ?>"></i>
        <span><?= htmlspecialchars($flash_warning !== '' ? $flash_warning : $flash_success, ENT_QUOTES, 'UTF-8') ?></span>
      </div>
    <?php endif; ?>

    <section class="as-tools-card" aria-label="البحث والتصفية">
      <form class="as-search" action="subscribers.php" method="get">
        <?php if ($filter !== 'all'): ?><input type="hidden" name="filter" value="<?= htmlspecialchars($filter, ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
        <?php if ($sort !== ''): ?><input type="hidden" name="sort" value="<?= htmlspecialchars($sort, ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
        <label for="androidSubscriberSearch">ابحث بالـ ID أو الاسم أو حساب PPPoE أو الهاتف</label>
        <div class="as-search-row">
          <input id="androidSubscriberSearch" type="search" name="q" data-ua-subscriber-search value="<?= htmlspecialchars($q, ENT_QUOTES, 'UTF-8') ?>" placeholder="ID أو كلمة البحث..." autocomplete="off">
          <button type="submit"><i class="fa fa-search"></i><span>بحث</span></button>
          <?php if ($q !== ''): ?><a href="subscribers.php<?= $androidQuery(['q' => null, 'page' => null]) ?>" aria-label="مسح البحث"><i class="fa fa-times"></i></a><?php endif; ?>
        </div>
      </form>

      <nav class="as-filters" aria-label="تصفية حالة المشترك">
        <?php
          $androidFilters = [
            'all' => ['الكل', 'fa-users'],
            'online' => ['متصل', 'fa-wifi'],
            'offline' => ['غير متصل', 'fa-user-times'],
            'disabled' => ['مفصول', 'fa-ban'],
            'limited' => ['محدود', 'fa-tachometer'],
          ];
        ?>
        <?php foreach ($androidFilters as $filterKey => $filterData): ?>
          <a class="<?= $filter === $filterKey ? 'is-active' : '' ?>" href="subscribers.php<?= $androidQuery(['filter' => $filterKey, 'page' => null]) ?>">
            <i class="fa <?= $filterData[1] ?>"></i><span><?= $filterData[0] ?></span>
          </a>
        <?php endforeach; ?>
      </nav>

      <div class="as-sort-row">
        <span><i class="fa fa-sort-amount-desc"></i> ترتيب النتائج</span>
        <select aria-label="ترتيب المشتركين" data-as-sort>
          <option value="subscribers.php<?= $androidQuery(['sort' => null, 'page' => null]) ?>" <?= $sort === '' ? 'selected' : '' ?>>الحالة والاتصال</option>
          <option value="subscribers.php<?= $androidQuery(['sort' => 'alpha', 'page' => null]) ?>" <?= $sort === 'alpha' ? 'selected' : '' ?>>الاسم أبجدياً</option>
          <option value="subscribers.php<?= $androidQuery(['sort' => 'id', 'page' => null]) ?>" <?= $sort === 'id' ? 'selected' : '' ?>>الأحدث إضافة</option>
          <option value="subscribers.php<?= $androidQuery(['sort' => 'usage', 'page' => null]) ?>" <?= $sort === 'usage' ? 'selected' : '' ?>>الأعلى استهلاكاً</option>
          <option value="subscribers.php<?= $androidQuery(['sort' => 'disabled', 'page' => null]) ?>" <?= $sort === 'disabled' ? 'selected' : '' ?>>المفصول أولاً</option>
        </select>
      </div>
    </section>

    <div class="as-results-head">
      <div><strong><?= number_format($totalRows) ?></strong><span> نتيجة</span></div>
      <span>صفحة <?= $androidPage ?> من <?= $androidTotalPages ?></span>
    </div>

    <section class="as-list" aria-live="polite">
      <?php if (!$androidRows): ?>
        <div class="as-empty">
          <i class="fa fa-search"></i>
          <h2>لا توجد نتائج</h2>
          <p>غيّر كلمة البحث أو اختر حالة أخرى.</p>
        </div>
      <?php endif; ?>

      <?php foreach ($androidRows as $sub): ?>
        <?php
          $id = (int)($sub['id'] ?? 0);
          $isOnline = ((int)($sub['is_online'] ?? 0) === 1);
          $pppUser = $hasPppUserCol ? trim((string)($sub['ppp_username'] ?? '')) : '';
          $uJoin = $pppUser !== '' ? $pppUser : trim((string)($sub['username'] ?? ''));
          $uJoin = preg_replace('/@.*/', '', $uJoin);
          $isDisabled = $rowIsDisabled($sub);
          if ($uJoin !== '' && array_key_exists($uJoin, $mtDisabledMap)) $isDisabled = (bool)$mtDisabledMap[$uJoin];
          $servicePaused = (int)($sub['billing_paused'] ?? 0) === 1;
          if ($servicePaused) $isDisabled = true;
          $activeRow = ($uJoin !== '' && isset($pppActiveRowMap[$uJoin]) && is_array($pppActiveRowMap[$uJoin])) ? $pppActiveRowMap[$uJoin] : null;
          $statusInfo = $servicePaused
            ? ['key'=>'service-paused', 'class'=>'is-stopped', 'label'=>'متوقف مؤقتاً']
            : sub_status_info($isOnline, $isDisabled, $sub, $activeRow);
          $statusKey = (string)($statusInfo['key'] ?? ($isOnline ? 'online' : 'offline'));
          $statusLabel = (string)($statusInfo['label'] ?? ($isOnline ? 'متصل' : 'غير متصل'));

          $displayName = trim((string)($sub['full_name'] ?? ''));
          if ($displayName === '' || preg_match('/^SUB#\d+(?:\s+.*)?$/u', $displayName) || preg_match('/^SUB#AUTO\b/iu', $displayName)) {
            $displayName = $pppUser !== '' ? $pppUser : trim((string)($sub['username'] ?? ''));
          }
          if ($displayName === '') $displayName = 'مشترك #' . $id;

          $autoMatch = $rxMatchBySubscriber[$id] ?? [];
          $sectorLabel = trim((string)($sub['airmax_device_name'] ?? ''));
          if ($sectorLabel === '' && is_array($autoMatch)) $sectorLabel = trim((string)($autoMatch['device_name'] ?? ''));
          $manualSectorId = (int)($sub['sector_id'] ?? 0);
          if ($sectorLabel === '' && $manualSectorId > 0 && isset($sectorNameMap[$manualSectorId])) $sectorLabel = trim((string)$sectorNameMap[$manualSectorId]);
          if ($sectorLabel === '') $sectorLabel = 'غير محدد';

          $lastSeenRaw = $hasLastSeen ? trim((string)($sub['last_seen_at'] ?? '')) : '';
          $lastSeenText = $isOnline ? 'الآن' : time_ago($lastSeenRaw);
          $usedBytes = (int)($sub['_used_bytes'] ?? 0);
          $usedGb = $usedBytes / 1073741824;
          $pendingInvoice = $pendingInvoiceBySubscriber[$id] ?? null;
          $pendingInvoiceId = is_array($pendingInvoice) ? (int)($pendingInvoice['id'] ?? 0) : 0;
          $phone = trim((string)($sub['phone'] ?? ''));
        ?>
        <article class="as-subscriber-card is-<?= htmlspecialchars($statusKey, ENT_QUOTES, 'UTF-8') ?>">
          <header class="as-card-head">
            <div class="as-person">
              <span class="as-avatar"><i class="fa fa-user"></i></span>
              <div>
                <h2><?= htmlspecialchars($displayName, ENT_QUOTES, 'UTF-8') ?></h2>
                <p><span>#<?= $id ?></span><?php if ($uJoin !== ''): ?><bdi><?= htmlspecialchars($uJoin, ENT_QUOTES, 'UTF-8') ?></bdi><?php endif; ?></p>
              </div>
            </div>
            <span class="as-status <?= $isDisabled ? 'is-disabled' : ($isOnline ? 'is-online' : 'is-offline') ?>"><i></i><?= htmlspecialchars($statusLabel, ENT_QUOTES, 'UTF-8') ?></span>
          </header>

          <div class="as-details">
            <div><i class="fa fa-map-marker"></i><span>القطاع</span><strong><?= htmlspecialchars($sectorLabel, ENT_QUOTES, 'UTF-8') ?></strong></div>
            <div><i class="fa fa-clock-o"></i><span>آخر ظهور</span><strong><?= htmlspecialchars($lastSeenText, ENT_QUOTES, 'UTF-8') ?></strong></div>
            <div><i class="fa fa-line-chart"></i><span>الاستهلاك</span><strong><bdi><?= number_format($usedGb, 2) ?> GB</bdi></strong></div>
            <div><i class="fa fa-phone"></i><span>الهاتف</span><strong><bdi><?= htmlspecialchars($phone !== '' ? $phone : '—', ENT_QUOTES, 'UTF-8') ?></bdi></strong></div>
          </div>

          <footer class="as-actions">
            <a href="subscribers_view.php?id=<?= $id ?>"><i class="fa fa-eye"></i><span>عرض</span></a>
            <a href="subscribers_edit.php?id=<?= $id ?>"><i class="fa fa-pencil"></i><span>تعديل</span></a>
            <a href="subscribers_history.php?id=<?= $id ?>"><i class="fa fa-history"></i><span>السجل</span></a>
            <a href="subscriber_contracts.php?ua_android=1&amp;subscriber_id=<?= $id ?>#editor"><i class="fa fa-file-word-o"></i><span>عقد</span></a>
            <a href="android_router_setup.php?ua_android=1&amp;subscriber_id=<?= $id ?>"><svg class="ua-router-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 11V5m14 6V5"/><rect x="3" y="11" width="18" height="8" rx="2"/><circle cx="7" cy="15" r="1"/><circle cx="11" cy="15" r="1"/><path d="M15 15h3"/></svg><span>إعداد الراوتر</span></a>
            <?php if ($pendingInvoiceId > 0): ?>
              <a class="is-pay" href="pay_invoice.php?id=<?= $pendingInvoiceId ?>"><i class="fa fa-credit-card"></i><span>تسديد</span></a>
            <?php else: ?>
              <span class="is-muted"><i class="fa fa-check-circle"></i><em>لا مستحقات</em></span>
            <?php endif; ?>
          </footer>
        </article>
      <?php endforeach; ?>
    </section>

    <?php if ($androidTotalPages > 1): ?>
      <nav class="as-pagination" aria-label="صفحات النتائج">
        <?php if ($androidPage > 1): ?><a href="subscribers.php<?= $androidQuery(['page' => $androidPage - 1]) ?>"><i class="fa fa-angle-right"></i><span>السابق</span></a><?php else: ?><span class="is-disabled"><i class="fa fa-angle-right"></i><span>السابق</span></span><?php endif; ?>
        <strong><?= $androidPage ?> / <?= $androidTotalPages ?></strong>
        <?php if ($androidPage < $androidTotalPages): ?><a href="subscribers.php<?= $androidQuery(['page' => $androidPage + 1]) ?>"><span>التالي</span><i class="fa fa-angle-left"></i></a><?php else: ?><span class="is-disabled"><span>التالي</span><i class="fa fa-angle-left"></i></span><?php endif; ?>
      </nav>
    <?php endif; ?>
  </main>
</div>
<script>
document.addEventListener('change', function (event) {
  if (event.target && event.target.matches('[data-as-sort]')) window.location.href = event.target.value;
});
</script>
<?php require_once __DIR__ . '/footer.php'; ?>
