<?php
/*
 * MAC Vendor / Device Type detector
 * - Built-in seed list for common ISP/customer devices (100+ vendors).
 * - Manual overrides table for exact MAC or prefix corrections.
 * - No external API calls during page load; everything is local and fast.
 */

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

if (!function_exists('macvendor_key')) {
  function macvendor_key(string $macOrPrefix): string {
    return strtoupper(preg_replace('/[^0-9A-F]/', '', trim($macOrPrefix)) ?? '');
  }
}

if (!function_exists('macvendor_prefix6')) {
  function macvendor_prefix6(string $macOrPrefix): string {
    $k = macvendor_key($macOrPrefix);
    return strlen($k) >= 6 ? substr($k, 0, 6) : '';
  }
}

if (!function_exists('macvendor_table_exists')) {
  function macvendor_table_exists(mysqli $conn, string $table): bool {
    static $cache = [];
    if (array_key_exists($table, $cache)) return $cache[$table];
    $t = $conn->real_escape_string($table);
    $rs = @$conn->query("SHOW TABLES LIKE '{$t}'");
    return $cache[$table] = (bool)($rs && $rs->num_rows > 0);
  }
}

if (!function_exists('macvendor_ensure_schema')) {
  function macvendor_ensure_schema(?mysqli $conn = null): void {
    if (!($conn instanceof mysqli)) return;
    static $done = false;
    if ($done) return;
    $done = true;
    @mysqli_report(MYSQLI_REPORT_OFF);
    @ $conn->query("CREATE TABLE IF NOT EXISTS mac_device_overrides (
      id INT UNSIGNED NOT NULL AUTO_INCREMENT,
      mac_key VARCHAR(32) NOT NULL,
      match_type VARCHAR(16) NOT NULL DEFAULT 'prefix',
      vendor_name VARCHAR(120) NOT NULL,
      device_type VARCHAR(120) NULL,
      confidence VARCHAR(20) NOT NULL DEFAULT 'manual',
      notes TEXT NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY(id),
      UNIQUE KEY uniq_mac_key (mac_key),
      KEY idx_vendor (vendor_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
  }
}

if (!function_exists('macvendor_seed_entries')) {
  function macvendor_seed_entries(): array {
    static $seed = null;
    if (is_array($seed)) return $seed;
    $rows = [
      // ISP / wireless / CPE priority prefixes
      ['80AFCA','Cudy','راوتر Cudy / CPE','oui'],
      ['B44BD6','Cudy','راوتر Cudy / CPE','oui'],
      ['D40DAB','Cudy','راوتر Cudy / CPE','oui'],
      ['F4A454','Cudy','راوتر Cudy / CPE','oui'],
      ['007263','Netis','راوتر Netis','oui'],
      ['045EA4','Netis','راوتر Netis','oui'],
      ['048D38','Netis','راوتر Netis','oui'],
      ['64EEB7','Netis','راوتر Netis','oui'],
      ['88BD09','Netis','راوتر Netis','oui'],
      ['BC62CE','Netis','راوتر Netis','oui'],
      ['BCE001','Netis','راوتر Netis','oui'],
      ['DC8E8D','Netis','راوتر Netis','oui'],
      ['E4BEED','Netis','راوتر Netis','oui'],
      ['BC0F9A','D-Link','راوتر D-Link','oui'],
      ['00055D','D-Link','راوتر / سويتش D-Link','seed'],
      ['001195','D-Link','راوتر / سويتش D-Link','seed'],
      ['1C7EE5','D-Link','راوتر D-Link','seed'],
      ['C412F5','D-Link','راوتر D-Link','seed'],
      ['4C5E0C','MikroTik / RouterBOARD','راوتر MikroTik','oui'],
      ['2CC81B','MikroTik / RouterBOARD','راوتر MikroTik','oui'],
      ['E48D8C','MikroTik / RouterBOARD','راوتر MikroTik','oui'],
      ['64D154','MikroTik / RouterBOARD','راوتر MikroTik','seed'],
      ['F4E2C6','Ubiquiti','AirMAX / CPE','seed'],
      ['E43883','Ubiquiti','AirMAX / UniFi','oui'],
      ['24A43C','Ubiquiti','AirMAX / UniFi','seed'],
      ['0418D6','Ubiquiti','AirMAX / UniFi','seed'],
      ['D89EF3','Ubiquiti','AirMAX / UniFi','seed'],
      ['DC9FDB','Ubiquiti','AirMAX / UniFi','seed'],
      ['20B5C6','Mimosa Networks','Mimosa Radio / CPE','seed'],
      ['F4C714','Mimosa Networks','Mimosa Radio / CPE','seed'],
      ['FC5B39','Mimosa Networks','Mimosa Radio / CPE','seed'],
      ['00156D','Cambium Networks','Cambium / Motorola Wireless','seed'],
      ['BCE67C','Cambium Networks','Cambium Wireless','oui'],
      ['58C17A','Cambium Networks','Cambium Wireless','seed'],
      ['000456','Cambium Networks','Cambium Wireless','seed'],
      ['70C94E','LiteOn','Wi-Fi module / CPE','oui'],
      ['2CD05A','LiteOn','Wi-Fi module / CPE','oui'],
      ['50FE0C','AzureWave','Wi-Fi module','oui'],
      ['2CDCD7','AzureWave','Wi-Fi module','oui'],
      ['6C5940','Mercusys','راوتر Mercusys','seed'],
      ['E8DE27','Mercusys','راوتر Mercusys','seed'],
      ['C025E9','TP-Link','راوتر TP-Link','seed'],
      ['14CC20','TP-Link','راوتر TP-Link','seed'],
      ['50C7BF','TP-Link','راوتر TP-Link','seed'],
      ['704F57','TP-Link','راوتر TP-Link','oui'],
      ['7C8BCA','TP-Link','راوتر TP-Link','oui'],
      ['BCD177','TP-Link','راوتر TP-Link','oui'],
      ['C46E1F','TP-Link','راوتر TP-Link','oui'],
      ['C47154','TP-Link','راوتر TP-Link','oui'],
      ['C83A35','Tenda','راوتر Tenda','seed'],
      ['B83A08','Tenda','راوتر Tenda','seed'],
      ['D8D81B','Tenda','راوتر Tenda','seed'],
      ['503EAA','Tenda','راوتر Tenda','seed'],
      ['E47C65','Tenda / Sunstar','راوتر / CPE','oui'],
      ['C83A6B','TOTOLINK','راوتر TOTOLINK','seed'],
      ['001D0F','TOTOLINK / ipTIME','راوتر','seed'],
      ['4C60DE','NETGEAR','راوتر / سويتش NETGEAR','oui'],
      ['A040A0','NETGEAR','راوتر / سويتش NETGEAR','seed'],
      ['B0B98A','NETGEAR','راوتر / سويتش NETGEAR','seed'],
      ['704D7B','ASUS','راوتر ASUS','oui'],
      ['BCEE7B','ASUS','راوتر ASUS','oui'],
      ['88D7F6','ASUS','راوتر ASUS','oui'],
      ['001731','ASUS','راوتر ASUS','seed'],
      ['001E10','Wavlink','راوتر / موسع','seed'],
      ['00E04C','Realtek','كرت شبكة / راوتر اقتصادي','seed'],
      ['A0CEC8','Realtek','كرت شبكة / Wi-Fi','seed'],
      ['001018','Broadcom','كرت شبكة / Wi-Fi','seed'],
      ['70B7E4','Broadcom','كرت شبكة / Wi-Fi','oui'],
      ['001374','Atheros / Qualcomm','Wi-Fi chipset','seed'],
      ['5C63BF','Qualcomm','Wi-Fi / Mobile chipset','seed'],
      ['000AEB','Atheros / Qualcomm','Wi-Fi chipset','seed'],
      ['000CE7','MediaTek / Ralink','Wi-Fi chipset','seed'],
      ['001F1F','MediaTek / Ralink','Wi-Fi chipset','seed'],
      ['2CD1C6','Murata','Wi-Fi module','oui'],
      ['001D43','Intel','كرت شبكة Intel','seed'],
      ['4C5F70','Intel','كرت شبكة Intel','oui'],
      ['70CD0D','Intel','كرت شبكة Intel','oui'],
      ['001B21','Intel','كرت شبكة Intel','seed'],
      ['0016EC','Elitegroup / ECS','لوحة/كرت شبكة','seed'],
      ['001A92','ASRock','لوحة/كرت شبكة','seed'],
      ['3C7C3F','Wistron NeWeb','Wi-Fi module / CPE','seed'],
      ['2CD26B','FN-Link','Wi-Fi module','oui'],
      ['7C8899','FN-Link','Wi-Fi module','oui'],
      ['681268','Quectel','4G/5G module','oui'],
      ['2CC682','Quectel','4G/5G module','oui'],
      ['64F6BB','Fibocom','4G/5G module','oui'],
      ['00113F','Sierra Wireless','4G/5G router/module','seed'],
      ['000CE3','Option','Cellular router/module','seed'],
      ['001A8F','Teltonika','راوتر صناعي','seed'],
      ['E4F14C','Private / Local Admin','عنوان خاص / عشوائي','oui'],

      // Enterprise/networking
      ['00000C','Cisco','راوتر / سويتش Cisco','oui'],
      ['E80AB9','Cisco','راوتر / سويتش Cisco','oui'],
      ['64D989','Cisco','راوتر / سويتش Cisco','oui'],
      ['703509','Cisco','راوتر / سويتش Cisco','oui'],
      ['9CE330','Cisco Meraki','AP / Security Gateway','oui'],
      ['B4DF91','Cisco Meraki','AP / Security Gateway','oui'],
      ['4C734F','Juniper Networks','راوتر / سويتش Juniper','oui'],
      ['60C78D','Juniper Networks','راوتر / سويتش Juniper','oui'],
      ['E4F27C','Juniper Networks','راوتر / سويتش Juniper','oui'],
      ['64E881','HPE / Aruba','سويتش / Access Point','oui'],
      ['88E9A4','HPE / Aruba','سويتش / Access Point','oui'],
      ['704777','Ruckus Wireless','Access Point','oui'],
      ['2CC5D3','Ruckus Wireless','Access Point','oui'],
      ['7478A6','Fortinet','Firewall / AP','oui'],
      ['704CA5','Fortinet','Firewall / AP','oui'],
      ['7C89C1','Palo Alto Networks','Firewall','oui'],
      ['80BA16','Micas Networks','سويتش / CPE','oui'],
      ['902D77','Edgecore','سويتش / OLT','oui'],
      ['7C8D9C','Edgecore','سويتش / OLT','oui'],
      ['00030D','Uniwill / Edgecore legacy','سويتش','seed'],
      ['70C6DD','H3C','سويتش / راوتر H3C','oui'],
      ['BCD0EB','H3C','سويتش / راوتر H3C','oui'],
      ['04A959','H3C','سويتش / راوتر H3C','oui'],
      ['00749C','Ruijie Networks','سويتش / AP Ruijie','oui'],
      ['7042D3','Ruijie Networks','سويتش / AP Ruijie','oui'],
      ['C470AB','Ruijie Networks','سويتش / AP Ruijie','oui'],
      ['70305D','Ubiquoss','FTTx / OLT / CPE','oui'],
      ['BC76F9','Ubiquoss','FTTx / OLT / CPE','oui'],
      ['88DA36','Calix','FTTx / ONT','oui'],
      ['286FB9','Nokia','ONT / Telecom','oui'],
      ['007839','Nokia','ONT / Telecom','oui'],
      ['7C8530','Nokia','ONT / Telecom','oui'],
      ['7C726E','Ericsson','Telecom equipment','oui'],
      ['4C5FD2','Alcatel-Lucent','Telecom equipment','oui'],
      ['78465F','FiberHome','ONT / Router FiberHome','oui'],
      ['70B921','FiberHome','ONT / Router FiberHome','oui'],
      ['70D51E','FiberHome','ONT / Router FiberHome','oui'],
      ['C464B7','FiberHome','ONT / Router FiberHome','oui'],
      ['2CB6C8','Raisecom','Telecom / CPE','oui'],
      ['2CDFE6','Raisecom','Telecom / CPE','oui'],
      ['64DD68','Zyxel','راوتر Zyxel','oui'],
      ['7C7716','Zyxel','راوتر Zyxel','oui'],
      ['88ACC0','Zyxel','راوتر Zyxel','oui'],
      ['BCCF4F','Zyxel','راوتر Zyxel','oui'],
      ['64FA2B','Sagemcom','راوتر Sagemcom','oui'],
      ['64FD96','Sagemcom','راوتر Sagemcom','oui'],
      ['88A6C6','Sagemcom','راوتر Sagemcom','oui'],
      ['B05B99','Sagemcom','راوتر Sagemcom','oui'],
      ['C44FD5','Vantiva / Technicolor','راوتر ISP','oui'],
      ['C4509C','Vantiva / Technicolor','راوتر ISP','oui'],
      ['703E76','Arcadyan','راوتر ISP','oui'],
      ['E43ED7','Arcadyan','راوتر ISP','oui'],
      ['88DE7C','Askey','راوتر ISP','oui'],
      ['001A2A','Arcadyan / Verizon','راوتر ISP','seed'],
      ['000E8F','Sercomm','راوتر / CPE ISP','seed'],
      ['001A2B','Sercomm','راوتر / CPE ISP','seed'],
      ['AC5A14','Arris / CommScope','Cable modem / Router','seed'],
      ['64ED57','CommScope','Cable modem / Router','oui'],
      ['88EF16','CommScope','Cable modem / Router','oui'],
      ['00195E','Motorola / ARRIS','Cable modem / Router','seed'],
      ['000CE5','ARRIS','Cable modem / Router','seed'],
      ['001E46','Pirelli Broadband','راوتر ISP','seed'],
      ['001E2A','Peplink','راوتر Peplink','seed'],
      ['44D9E7','Ubiquiti / UniFi','UniFi / AirMAX','seed'],
      ['000B82','Grandstream','VoIP / Router','seed'],
      ['C074AD','Grandstream','VoIP / Router','seed'],
      ['001565','Yealink','VoIP phone','seed'],
      ['6CFBED','GN Audio','Headset / VoIP','oui'],
      ['BCF292','Poly / Plantronics','VoIP / Headset','oui'],
      ['001873','Polycom','VoIP phone','seed'],

      // Cameras / IoT / smart devices common in networks
      ['64DB8B','Hikvision','كاميرا / NVR','oui'],
      ['88DE39','Hikvision','كاميرا / NVR','oui'],
      ['64FD29','Dahua','كاميرا / NVR','oui'],
      ['C47905','Uniview','كاميرا / NVR','oui'],
      ['001BFE','Zavio','كاميرا IP','seed'],
      ['00408C','Axis Communications','كاميرا IP','seed'],
      ['70C6AC','Bosch','كاميرا / IoT','oui'],
      ['64E833','Espressif','ESP / IoT','oui'],
      ['704BCA','Espressif','ESP / IoT','oui'],
      ['88F155','Espressif','ESP / IoT','oui'],
      ['10061C','Espressif','ESP / IoT','oui'],
      ['00124B','Texas Instruments','IoT / Embedded','seed'],
      ['2CD3AD','Texas Instruments','IoT / Embedded','oui'],
      ['C464E3','Texas Instruments','IoT / Embedded','oui'],
      ['00158D','Jennic / NXP','IoT / Zigbee','seed'],
      ['00124B','Digi / XBee','IoT / Zigbee','seed'],
      ['70C59C','Silicon Labs','IoT / Zigbee','oui'],
      ['4C5BB3','Silicon Labs','IoT / Zigbee','oui'],
      ['0017C8','Sonos','Audio / IoT','seed'],
      ['88DEA9','Roku','Streaming device','oui'],
      ['BCD7D4','Roku','Streaming device','oui'],
      ['64D912','Solidica','IoT / embedded','oui'],
      ['64F2FB','Ezviz','كاميرا / IoT','oui'],

      // Phones / PCs / common clients
      ['001A11','Google','هاتف / Chromecast / Nest','seed'],
      ['703ACB','Google','هاتف / Chromecast / Nest','oui'],
      ['BCDF58','Google','هاتف / Chromecast / Nest','oui'],
      ['F4F5D8','Google','هاتف / Chromecast / Nest','seed'],
      ['0025BC','Apple','iPhone / Mac','seed'],
      ['007D60','Apple','iPhone / Mac','oui'],
      ['BC6778','Apple','iPhone / Mac','oui'],
      ['88E87F','Apple','iPhone / Mac','oui'],
      ['2CB43A','Apple','iPhone / Mac','oui'],
      ['0002B3','Intel','PC / Laptop NIC','seed'],
      ['001122','CIMSYS / Generic','Generic client','seed'],
      ['000D3A','Microsoft','Surface / Xbox','seed'],
      ['70BC10','Microsoft','Surface / Xbox','oui'],
      ['7C6D12','Microsoft','Surface / Xbox','oui'],
      ['00155D','Microsoft','Surface / Xbox','seed'],
      ['0016EA','Dell','PC / Laptop','seed'],
      ['4C7625','Dell','PC / Laptop','oui'],
      ['70B5E8','Dell','PC / Laptop','oui'],
      ['C45AB1','Dell','PC / Laptop','oui'],
      ['001B78','HP','PC / Printer','seed'],
      ['644ED7','HP','PC / Printer','oui'],
      ['BCE92F','HP','PC / Printer','oui'],
      ['C46516','HP','PC / Printer','oui'],
      ['001F29','Hewlett Packard Enterprise','Server / Switch','seed'],
      ['00166F','Samsung','هاتف / TV','seed'],
      ['007204','Samsung','هاتف / TV','oui'],
      ['4C5739','Samsung','هاتف / TV','oui'],
      ['64E7D8','Samsung','هاتف / TV','oui'],
      ['70CE8C','Samsung','هاتف / TV','oui'],
      ['001E10','LG Electronics','TV / Phone','seed'],
      ['64E4A5','LG Electronics','TV / Phone','oui'],
      ['88C9D0','LG Electronics','TV / Phone','oui'],
      ['2CD066','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['4C55B2','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['64DDE9','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['70BBE9','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['88B951','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['C46AB7','Xiaomi','هاتف / راوتر / IoT','oui'],
      ['7C6B9C','OPPO','هاتف OPPO','oui'],
      ['88D50C','OPPO','هاتف OPPO','oui'],
      ['BCE8FA','OPPO','هاتف OPPO','oui'],
      ['702804','Realme','هاتف Realme','oui'],
      ['88AE35','Realme','هاتف Realme','oui'],
      ['E46A35','Realme','هاتف Realme','oui'],
      ['70357B','vivo','هاتف vivo','oui'],
      ['7047E9','vivo','هاتف vivo','oui'],
      ['64EC65','vivo','هاتف vivo','oui'],
      ['C46699','vivo','هاتف vivo','oui'],
      ['2CB68F','Huawei','هاتف / راوتر Huawei','oui'],
      ['4C5499','Huawei','هاتف / راوتر Huawei','oui'],
      ['64F81C','Huawei','هاتف / راوتر Huawei','oui'],
      ['88A0BE','Huawei','هاتف / راوتر Huawei','oui'],
      ['2CB7A1','Huawei Device','هاتف / راوتر Huawei','oui'],
      ['4C617E','Huawei Device','هاتف / راوتر Huawei','oui'],
      ['7040FF','Huawei Device','هاتف / راوتر Huawei','oui'],
      ['BCCD7F','Huawei Device','هاتف / راوتر Huawei','oui'],
      ['98EE8C','ZTE','راوتر / هاتف ZTE','oui'],
      ['64DB38','ZTE','راوتر / هاتف ZTE','oui'],
      ['88C174','ZTE','راوتر / هاتف ZTE','oui'],
      ['F01B24','ZTE','راوتر / هاتف ZTE','oui'],
      ['E44E12','ZTE','راوتر / هاتف ZTE','oui'],
      ['2CB301','Honor','هاتف Honor','oui'],
      ['0CB983','Honor','هاتف Honor','oui'],
      ['0015AF','Azurewave / ASUS laptop','Laptop Wi-Fi','seed'],
      ['001C25','Hon Hai / Foxconn','Laptop / Phone module','seed'],
      ['681401','Hon Hai / Foxconn','Laptop / Phone module','oui'],
      ['BC8556','Hon Hai / Foxconn','Laptop / Phone module','oui'],
      ['001B77','Lenovo','PC / Laptop','seed'],
      ['7C7B1C','Motorola / Lenovo','هاتف Motorola','oui'],
      ['88B4A6','Motorola / Lenovo','هاتف Motorola','oui'],
      ['001D72','Wistron','Laptop / module','seed'],
      ['001E4C','Quanta','Laptop / module','seed'],
      ['C45444','Quanta','Laptop / module','oui'],
      ['001F3C','Pegatron','Laptop / module','seed'],
      ['4C72B9','Pegatron','Laptop / module','oui'],
      ['001E68','Compal','Laptop / module','seed'],
      ['7C8AE1','Compal','Laptop / module','oui'],
      ['BCECA0','Compal','Laptop / module','oui'],
      ['0001E3','Siemens','Industrial / PLC','seed'],
      ['703811','Siemens','Industrial / PLC','oui'],
      ['000E8C','Rockwell Automation','Industrial','seed'],
      ['BCF499','Rockwell Automation','Industrial','oui'],
      ['E48EBB','Rockwell Automation','Industrial','oui'],
      ['000FE2','Hangzhou Hikvision legacy','كاميرا / NVR','seed'],
      ['001F54','Lorex / FLIR','كاميرا','seed'],
      ['000C43','Ralink / MediaTek','Wi-Fi chipset','seed'],
    ];
    $seed = [];
    foreach ($rows as $r) {
      $p = macvendor_prefix6((string)$r[0]);
      if ($p === '' || isset($seed[$p])) continue;
      $seed[$p] = [
        'prefix' => $p,
        'vendor' => (string)$r[1],
        'device_type' => (string)$r[2],
        'confidence' => (string)$r[3],
        'source' => 'builtin',
      ];
    }
    return $seed;
  }
}

if (!function_exists('macvendor_lookup_override')) {
  function macvendor_lookup_override(?mysqli $conn, string $mac): ?array {
    if (!($conn instanceof mysqli)) return null;
    macvendor_ensure_schema($conn);
    if (!macvendor_table_exists($conn, 'mac_device_overrides')) return null;
    $full = macvendor_key($mac);
    if ($full === '') return null;
    $keys = [$full];
    if (strlen($full) >= 8) $keys[] = substr($full, 0, 8);
    if (strlen($full) >= 6) $keys[] = substr($full, 0, 6);
    $keys = array_values(array_unique(array_filter($keys)));
    if (!$keys) return null;
    $in = "'" . implode("','", array_map([$conn, 'real_escape_string'], $keys)) . "'";
    $rs = @$conn->query("SELECT * FROM mac_device_overrides WHERE mac_key IN ({$in}) ORDER BY LENGTH(mac_key) DESC LIMIT 1");
    if (!$rs || !$rs->num_rows) return null;
    $r = $rs->fetch_assoc();
    return [
      'prefix' => macvendor_prefix6((string)($r['mac_key'] ?? '')),
      'vendor' => (string)($r['vendor_name'] ?? ''),
      'device_type' => (string)($r['device_type'] ?? ''),
      'confidence' => (string)($r['confidence'] ?? 'manual'),
      'source' => 'manual',
    ];
  }
}


if (!function_exists('macvendor_clean_type_for_label')) {
  function macvendor_clean_type_for_label(string $vendor, string $type): string {
    $vendor = trim($vendor);
    $type = trim($type);
    if ($type === '') return 'غير محدد';
    if ($vendor === '' || $vendor === 'غير معروف') return $type;

    // Remove repeated vendor words from the device type label.
    // Example: vendor=Cudy, type="راوتر Cudy / CPE" => "راوتر / CPE"
    $tokens = [$vendor];
    $splitTokens = preg_split('/[^A-Za-z0-9]+/u', $vendor) ?: [];
    foreach ($splitTokens as $st) $tokens[] = $st;

    foreach ($tokens as $tok) {
      $tok = trim((string)$tok);
      if ($tok === '' || strlen($tok) < 3) continue;
      $type = preg_replace('/(^|[\s\/\-])' . preg_quote($tok, '/') . '($|[\s\/\-])/iu', '$1$2', $type) ?? $type;
    }

    $type = preg_replace('/\s+/', ' ', $type) ?? $type;
    $type = preg_replace('/\s*\/\s*/u', ' / ', $type) ?? $type;
    $type = preg_replace('/(?:^\s*\/\s*|\s*\/\s*$)/u', '', $type) ?? $type;
    $type = trim($type);
    return $type !== '' ? $type : 'غير محدد';
  }
}

if (!function_exists('macvendor_make_label')) {
  function macvendor_make_label(string $vendor, string $type): string {
    $vendor = trim($vendor) ?: 'غير معروف';
    if ($vendor === 'غير معروف') return 'غير معروف';
    $type = macvendor_clean_type_for_label($vendor, $type);
    if ($type === '' || $type === 'غير محدد' || strtolower($type) === strtolower($vendor)) {
      return $vendor;
    }
    return $vendor . ' / ' . $type;
  }
}

if (!function_exists('macvendor_identify')) {
  function macvendor_identify($connOrMac, ?string $maybeMac = null): array {
    $conn = $connOrMac instanceof mysqli ? $connOrMac : null;
    $mac = $conn ? (string)$maybeMac : (string)$connOrMac;
    $norm = macvendor_norm_mac($mac);
    if ($norm === '') {
      return ['mac'=>'', 'prefix'=>'', 'vendor'=>'غير معروف', 'device_type'=>'غير معروف', 'confidence'=>'none', 'source'=>'none', 'label'=>'غير معروف'];
    }
    $ov = macvendor_lookup_override($conn, $norm);
    if ($ov && trim((string)$ov['vendor']) !== '') {
      $vendor = trim((string)$ov['vendor']);
      $type = trim((string)($ov['device_type'] ?? '')) ?: 'غير محدد';
      return ['mac'=>$norm, 'prefix'=>macvendor_prefix6($norm), 'vendor'=>$vendor, 'device_type'=>$type, 'confidence'=>(string)$ov['confidence'], 'source'=>'manual', 'label'=>macvendor_make_label($vendor, $type)];
    }
    $prefix = macvendor_prefix6($norm);
    $seed = macvendor_seed_entries();
    if ($prefix !== '' && isset($seed[$prefix])) {
      $e = $seed[$prefix];
      $vendor = trim((string)$e['vendor']);
      $type = trim((string)$e['device_type']) ?: 'غير محدد';
      return ['mac'=>$norm, 'prefix'=>$prefix, 'vendor'=>$vendor, 'device_type'=>$type, 'confidence'=>(string)$e['confidence'], 'source'=>'builtin', 'label'=>macvendor_make_label($vendor, $type)];
    }
    return ['mac'=>$norm, 'prefix'=>$prefix, 'vendor'=>'غير معروف', 'device_type'=>'غير معروف', 'confidence'=>'unknown', 'source'=>'builtin', 'label'=>'غير معروف'];
  }
}

if (!function_exists('macvendor_label')) {
  function macvendor_label($connOrMac, ?string $maybeMac = null): string {
    $info = macvendor_identify($connOrMac, $maybeMac);
    return (string)($info['label'] ?? 'غير معروف');
  }
}

if (!function_exists('macvendor_suffix')) {
  function macvendor_suffix($connOrMac, ?string $maybeMac = null): string {
    $info = macvendor_identify($connOrMac, $maybeMac);
    $label = (string)($info['label'] ?? 'غير معروف');
    if ($label === '' || $label === 'غير معروف') return '';
    return ' - نوع الجهاز: ' . $label;
  }
}
