<?php
@ini_set('display_errors','0');
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../subscriber_reality_lib.php';

try {
  if (function_exists('require_login')) require_login('login.php');
  if (function_exists('require_perm')) require_perm('can_search_dashboard_subscribers');
  if (function_exists('ensure_db')) ensure_db(true);
  $conn = $GLOBALS['conn'] ?? null;
  if (!($conn instanceof mysqli)) throw new RuntimeException('DB not ready');
  @$conn->set_charset('utf8mb4');

  function dash_sub_col_exists(mysqli $conn, string $table, string $col): bool {
    $t = $conn->real_escape_string($table);
    $c = $conn->real_escape_string($col);
    $rs = @$conn->query("SHOW COLUMNS FROM `$t` LIKE '$c'");
    return $rs && $rs->num_rows > 0;
  }
  function dash_like_escape(mysqli $conn, string $v): string {
    return strtr($conn->real_escape_string($v), ['%' => '\\%', '_' => '\\_']);
  }

  $q = trim((string)($_GET['q'] ?? ''));
  $q = preg_replace('/\s+/u', ' ', str_replace("\xC2\xA0", ' ', $q));
  if ($q === '' || (!ctype_digit($q) && mb_strlen($q, 'UTF-8') < 2)) {
    echo json_encode(['ok'=>true, 'items'=>[]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
  }

  $select = ['id'];
  $optional = ['username','ppp_username','full_name','phone','address_area','area','status','is_online','ppp_is_disabled','mt_disabled'];
  foreach ($optional as $col) {
    if (dash_sub_col_exists($conn, 'subscribers', $col)) $select[] = $col;
  }

  $like = '%' . dash_like_escape($conn, $q) . '%';
  $conds = [];
  if (ctype_digit($q)) $conds[] = 'id=' . (int)$q;
  foreach (['username','ppp_username','full_name','phone','address_area','area'] as $col) {
    if (dash_sub_col_exists($conn, 'subscribers', $col)) $conds[] = "`$col` LIKE '$like' ESCAPE '\\\\'";
  }
  if (!$conds) $conds[] = '1=0';
  $where = '(' . implode(' OR ', $conds) . ')';
  if (dash_sub_col_exists($conn, 'subscribers', 'is_deleted')) $where = "COALESCE(is_deleted,0)=0 AND $where";

  $onlineOrder = dash_sub_col_exists($conn, 'subscribers', 'is_online') ? 'COALESCE(is_online,0) DESC,' : '';
  $sql = 'SELECT `' . implode('`,`', $select) . "` FROM subscribers WHERE $where ORDER BY $onlineOrder id DESC LIMIT 10";
  $rs = @$conn->query($sql);
  $items = [];
  $subscriberReality = ua_subscriber_reality_snapshot($conn, 3600);
  if ($rs) {
    while ($r = $rs->fetch_assoc()) {
      $name = trim((string)($r['full_name'] ?? ''));
      $username = trim((string)($r['username'] ?? ''));
      $ppp = trim((string)($r['ppp_username'] ?? ''));
      $phone = trim((string)($r['phone'] ?? ''));
      $addr = trim((string)($r['address_area'] ?? ($r['area'] ?? '')));
      $runtimeState = ua_subscriber_reality_state($r, $subscriberReality);
      $disabled = !empty($runtimeState['is_disabled']);
      $online = !empty($runtimeState['is_online']);
      $needle = $ppp !== '' ? $ppp : ($username !== '' ? $username : ($name !== '' ? $name : (string)($r['id'] ?? '')));
      $items[] = [
        'id' => (int)($r['id'] ?? 0),
        'name' => $name !== '' ? $name : ($username !== '' ? $username : $ppp),
        'username' => $username,
        'ppp_username' => $ppp,
        'phone' => $phone,
        'address' => $addr,
        'online' => $online,
        'disabled' => $disabled,
        'status' => $disabled ? 'مفصول' : ($online ? 'متصل' : 'غير متصل'),
        'url' => 'subscribers.php?filter=all&q=' . rawurlencode($needle),
      ];
    }
  }

  echo json_encode(['ok'=>true, 'items'=>$items], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false, 'message'=>'فشل البحث'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
