<?php

namespace App\Traits;

trait UtilTrait
{
  final public function isIPAddressTrait(string $ip, $type = false): bool
  {
    switch ($type) {
      case 'ipv4':
        $result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
        break;
      case 'ipv6':
        $result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
        break;
      case 'all':
        $result = filter_var($ip, FILTER_VALIDATE_IP);
        break;
      default:
        $result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
        break;
    }
    return $result;
  }

  //IP관련련
  final public function isDomainNameTrait(string $domain): bool
  {
    $pattern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
    return preg_match($pattern_validation, $domain);
  }

  final public function isValidCIDRTrait(string $cidr, $type = "ipv4"): bool
  {
    // 형식: "IP/Prefix" 형태인지 검사
    if (!preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}\/\d{1,2}$/', $cidr)) {
      return false;
    }
    list($ip, $prefix) = explode('/', $cidr);
    // IP 유효성 검사
    if (!$this->isIPAddressTrait($ip, $type)) {
      return false;
    }
    // Prefix는 0~32 사이인지 검사 (IPv4 기준)
    $prefix = (int) $prefix;
    if ($prefix < 0 || $prefix > 32) {
      return false;
    }
    return true;
  }
  final public function isHostNameTrait(string $host): bool
  {
    $pattern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/';
    return preg_match($pattern_validation, $host);
  }
  final public function isMobile()
  {
    // Check the server headers to see if they're mobile friendly
    if (isset($_SERVER["HTTP_X_WAP_PROFILE"])) {
      return true;
    }
    // If the http_accept header supports wap then it's a mobile too
    if (preg_match("/wap\.|\.wap/i", $_SERVER["HTTP_ACCEPT"])) {
      return true;
    }
    // Still no luck? Let's have a look at the user agent on the browser. If it contains
    // any of the following, it's probably a mobile device. Kappow!
    if (isset($_SERVER["HTTP_USER_AGENT"])) {
      $user_agents = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto");
      foreach ($user_agents as $user_string) {
        if (preg_match("/" . $user_string . "/i", $_SERVER["HTTP_USER_AGENT"])) {
          return true;
        }
      }
    }
    // Let's NOT return "mobile" if it's an iPhone, because the iPhone can render normal pages quite well.
    if (preg_match("/iphone/i", $_SERVER["HTTP_USER_AGENT"])) {
      return false;
    }
    // None of the above? Then it's probably not a mobile device.
    return false;
  }

  /**
   * JavaScript Alert 및 페이지 이동 스크립트를 생성합니다.
   * json_encode()를 사용하여 메시지 내 특수 문자를 안전하게 이스케이프 처리합니다.
   * * @param string $msg 브라우저 Alert에 표시할 메시지
   * @param string|null $url Alert 후 이동할 URL (null: 이동 없음, 'close': 창 닫기)
   * @return string HTML <script> 태그
   */
  final public function alertTrait(string $msg, $url = null): string
  {
    $safeMsg = json_encode($msg, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);
    $js = "alert({$safeMsg});";
    switch ($url) {
      case 'close':
        $js .= "window.close();";
        break;
      case null:
      case '':
        // 이동 없음
        break;
      default:
        $safeUrl = json_encode($url, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);
        $js .= "location.href = {$safeUrl};";
        break;
    }
    return "<script type=\"text/javascript\">{$js}</script>";
  }

  final public function getPasswordStringTrait($length = 8, $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  {
    return substr(str_shuffle($characters), 0, $length);
    ;
  }

  // byte값을 알아보기 쉽게 변환
  final public function getSizeForHumanTrait($bytes)
  {
    $ext = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $unitCount = 0;
    for (; $bytes > 1024; $unitCount++) {
      $bytes /= 1024;
    }
    return floor($bytes) . $ext[$unitCount];
  }

  // Proxy등을 통하여 Client_IP가 알수없는경우 실제사용자의 IP를 가져오기 위한것
  final public function getClientIPTrait($clientIP = false)
  {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
      $clientIP = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
      $clientIP = $_SERVER['HTTP_X_FORWARDED'];
    } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
      $clientIP = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_FORWARDED'])) {
      $clientIP = $_SERVER['HTTP_FORWARDED'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
      $clientIP = $_SERVER['REMOTE_ADDR'];
    }
    return $clientIP;
  }

  // (EX:192.168.1.0 -> 192.168.001.000)
  final public function cidrToIpRangeTrait(string $cidr): array
  {
    if (!$this->isValidCIDRTrait($cidr)) {
      return []; // 유효하지 않으면 빈 배열 반환
    }

    list($ip, $prefix) = explode('/', $cidr);
    $prefix = (int) $prefix;

    $ipLong = ip2long($ip);
    $netmask = ~((1 << (32 - $prefix)) - 1);
    $network = $ipLong & $netmask;
    $broadcast = $network | ~$netmask;

    $ips = [];

    // 첫 IP부터 마지막 IP까지 반복
    for ($i = $network; $i <= $broadcast; $i++) {
      $ips[] = long2ip($i);
    }

    return $ips;
  }
}
