<?php

namespace App\Helpers;

use App\Entities\CommonEntity;

class CommonHelper
{
  private $_myAuth = null;
  private $_viewDatas = [];
  private $_titleField = "";
  protected function __construct() {}
  final protected function getMyAuth(): mixed
  {
    if (!$this->_myAuth) {
      $this->_myAuth = service('myauth');
    }
    return $this->_myAuth;
  }
  final public function setTitleField(string $field): void
  {
    $this->_titleField = $field;
  }
  final public function getTitleField(): string
  {
    if (!$this->_titleField) {
      throw new \Exception("titleField가 지정되지 않았습니다.");
    }
    return $this->_titleField;
  }
  final public function setViewDatas(array $viewDatas): void
  {
    $this->_viewDatas = $viewDatas;
  }
  final public function getViewDatas(string $key)
  {
    if (!array_key_exists($key, $this->_viewDatas)) {
      throw new \Exception("{$key}에 해당하는 ViewData가 존재하지 않습니다.");
    }
    return $this->_viewDatas[$key];
  }

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

  final public function isIPAddress(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;
  }
  final function isValidCIDR(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->isIPAddress($ip, $type)) {
      return false;
    }
    // Prefix는 0~32 사이인지 검사 (IPv4 기준)
    $prefix = (int) $prefix;
    if ($prefix < 0 || $prefix > 32) {
      return false;
    }
    return true;
  }
  final public function isHostName(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;
  }

  final public function alert(string $msg, $url = null)
  {
    $msg = preg_replace("/\r/", "\\r", $msg);
    $msg = preg_replace("/\n/", "\\n", $msg);
    $msg = preg_replace("/\'/", "\'", $msg);
    $msg = preg_replace("/\"/", "\'", $msg);
    $msg = "alert(\"{$msg}\");";
    switch ($url) {
      case 'close':
        $msg .= "window.close();";
        break;
      default:
        $msg .= $url ? "location.href=\"{$url}\";" : "";
        break;
    }
    return "<script type=\"text/javascript\">{$msg}</script>";
  }

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

  final public function getPasswordString($length = 8)
  {
    return $this->getRandomString($length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?");
  }

  // byte값을 알아보기 쉽게 변환
  final public function getSizeForHuman($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 getClientIP($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 cidrToIpRange(string $cidr): array
  {
    if (!$this->isValidCIDR($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;
  }
  final public function form_dropdown_common(string $field, mixed $value, array $viewDatas, array $extras = [], array $attributes = [], bool $isAll = false): string
  {
    // 필터 옵션이 없으면 빈 배열로 초기화
    if (!array_key_exists($field, $viewDatas['control']['field_optons'])) {
      return ""; // 필터 옵션이 없으면 빈 문자열 반환
    }
    $extra = "";
    foreach ($extras as $extra_tag => $extra_value) {
      $extra .= sprintf(" %s=\"%s\"", $extra_tag, $extra_value);
    }
    // $formOptions는 필터 옵션 배열로, key는 필터 엔티티의 PK, value는 필터 엔티티 객체
    $html = sprintf("<select name=\"%s\" %s>",  $field, $extra);
    $html .= "<option value=\"\">" . lang("{$viewDatas['class_path']}.label.{$field}") . " 선택" . "</option>";
    $html .= $this->form_dropdown_common_process($field, $value, $viewDatas, $extras, $attributes, $isAll);
    $html .= '</select>';
    return $html;
  }
  //필수함수
  protected function form_dropdown_common_process(string $field, mixed $value, array $viewDatas, array $extras = [], array $attributes = [], bool $isAll = false): string
  {
    $html = "";
    switch ($field) {
      default:
        foreach ($viewDatas['control']['field_optons'][$field] as $option_key => $option_value) {
          $isSelected = $option_key == $value ? ' selected' : '';
          $isDisabled  = "";
          $attribute = "";
          $label      = "";
          if ($option_value instanceof CommonEntity) {
            if ($option_key != $value && $option_value->getStatus() != $option_value::DEFAULT_STATUS && !$isAll) {
              continue;
            }
            foreach ($attributes as $attribute_name => $attribute_value) {
              $attribute .= sprintf(" %s=\"%s\"", $attribute_name, $option_value->$attribute_value);
            }
            $label = $option_value->getCustomTitle();
          } else {
            $label = $option_value;
          }
          $html .= sprintf("<option value=\"%s\"%s%s%s>%s</option>", $option_key, $isSelected, $isDisabled, $attribute, $label);
        }
        break;
    }
    return $html;
  }
  public function getFieldLabel(string $field, string $label, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      default:
        // required가 있으면 class 추가
        $extras = (strpos($viewDatas['control']['field_rules'][$field], 'required') !== false) ? ["class" => "text-danger", "required" => "", ...$extras] : $extras;
        $label = form_label($label, $field, ['class' => 'form-label-sm', ...$extras]);
        break;
    }
    return $label;
  }
  public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      case 'email':
        $form = form_input($field, $value ?? "", [
          "class" => "form-control",
          'style' => 'width:100%;',
          "placeholder" => "예)test@example.com",
          ...$extras
        ]);
        break;
      case 'mobile':
      case 'phone':
        $form = form_input($field, $value ?? "", [
          "class" => "form-control",
          'style' => 'width:100%;',
          "placeholder" => "예)010-0010-0010",
          ...$extras
        ]);
        break;
      case 'role':
        if (!is_array($viewDatas['control']['field_optons'][$field])) {
          throw new \Exception(__METHOD__ . "에서 {$field}의 field_options가 array형태가 아닙니다.");
        }
        // create, modify, create_form, modify_form일때 checkbox로 표시
        if (in_array($viewDatas['control']['action'], ['create_form', 'modify_form'])) {
          $forms = [];
          foreach ($viewDatas['control']['field_optons'][$field] as $key => $label) {
            if ($key !== '') { // 빈값은 제외
              $values = is_array($value) ? $value : explode(DEFAULTS["DELIMITER_ROLE"], $value);
              //form_check에는 "class" => "form-control" 쓰면 않되거나 form-check를 써야함
              $forms[] = form_checkbox("{$field}[]", $key, in_array($key, $values), $extras) . $label;
            }
          }
          $form = implode(" ", $forms);
        } else {
          $form = form_dropdown($field, $value, $viewDatas, $extras);
        }
        break;
      case 'issue_at':
      case 'expired_at':
      case 'billing_at':
      case 'start_at':
      case 'end_at':
      case 'updated_at':
      case 'created_at':
      case 'deleted_at':
        $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' calender' : 'calender';
        $form = form_input($field, $value ?? "", $extras);
        break;
      case 'description':
      case 'content':
      case 'detail':
      case 'history':
        $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' tinymce' : 'tinymce';
        $form = form_textarea($field, html_entity_decode($value ?? "", ENT_QUOTES, 'UTF-8'), [
          "class" => "form-control",
          'style' => 'width:100%;',
          ...$extras
        ]);
        break;
      default:
        if (in_array($field, $viewDatas['control']['actionFilters'])) {
          if (str_contains($field, "_uid")) {
            $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' select-field' : 'select-field';
          }
          $form = $this->form_dropdown_common($field, $value, $viewDatas, $extras);
        } else {
          $form = form_input($field, $value ?? "", [
            "class" => "form-control",
            'style' => 'width:100%;',
            ...$extras
          ]);
        }
        break;
    }
    return $form;
  }
  public function getFieldView(string $field, mixed $value, array $viewDatas, array $extras = []): string|null
  {
    switch ($field) {
      case 'clientinfo_uid':
        if (array_key_exists($value, $viewDatas['control']['field_optons'][$field])) {
          $value = "<a href=\"/admin/customer/client/detail/{$value}\">" . $viewDatas['control']['field_optons'][$field][$value]->getTitle() . "</a>";
        }
        break;
      case 'role':
        $roles = [];
        foreach (explode(DEFAULTS["DELIMITER_ROLE"], $value) as $key) {
          $roles[] = $viewDatas['control']['field_optons'][$field][$key] ?? "";
        }
        $value = implode(" , ", $roles);
        break;
      case 'description':
      case 'content':
      case 'detail':
      case 'history':
        if (in_array($viewDatas['control']['action'], ['view', 'index'])) {
          $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
        }
        break;
      case 'issue_at':
      case 'expired_at':
      case 'billing_at':
      case 'start_at':
      case 'end_at':
      case 'updated_at':
      case 'created_at':
      case 'deleted_at':
        $value = $value ? date("Y-m-d", strtotime($value)) : "";
        break;
      default:
        if (in_array($field, $viewDatas['control']['actionFilters'])) {
          if (str_contains($field, "_uid")) {
            $value = array_key_exists($value, $viewDatas['control']['field_optons'][$field]) && $viewDatas['control']['field_optons'][$field][$value] ? $viewDatas['control']['field_optons'][$field][$value]->getTitle() : "";
          } else {
            $value = array_key_exists($value, $viewDatas['control']['field_optons'][$field]) ? $viewDatas['control']['field_optons'][$field][$value] : "";
          }
        }
        break;
    }
    if (is_array($value)) {
      throw new \Exception(__METHOD__ . "에서 오류: {$field}의 값이 Array형태입니다");
    }
    return $value;
  }
  public function getListFilter(string $field, mixed $value, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      default:
        if (in_array($field, $viewDatas['control']['actionFilters'])) {
          if (str_contains($field, "_uid")) {
            $extras['class'] = array_key_exists('class', $extras) ? $extras['class'] . ' select-field' : 'select-field';
          }
          $attributes = [];
          $isAll      = true;
          $filter = $this->form_dropdown_common($field, $value, $viewDatas, $extras, $attributes, $isAll);
        } else {
          $filter = array_key_exists($value, $viewDatas['control']['field_optons'][$field]) ? $viewDatas['control']['field_optons'][$field][$value] : "";
        }
        break;
    }
    return $filter;
  }
  public function getListLabel(string $field, string $label, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      default:
        $label = $this->getFieldLabel($field, $label, $viewDatas, $extras);
        if (isset($viewDatas['order_field']) && $viewDatas['order_field'] == $field) {
          $label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"];
        }
        $query = $viewDatas['uri']->getQuery(['except' => ['order_field', 'order_value']]);
        $query .= empty($query) ? "" : "&";
        $query .= "order_field={$field}&order_value=";
        $query .= isset($viewDatas['order_value']) && $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC";
        $label = anchor(current_url() . "?" . $query, $label);
        form_dropdown('per_page', $viewDatas['page_options'], $viewDatas['per_page'], ['onChange' => 'this.form.submit()']);
        break;
    }
    return $label;
  }

  public function getListButton(string $action, string $label, array $viewDatas, array $extras = []): string
  {
    switch ($action) {
      case 'create':
        $action = form_label(
          $label ? $label : '입력',
          $action,
          [
            "data-src" => current_url() . '/' . $action . '?' . $viewDatas['uri']->getQuery(),
            "data-bs-toggle" => "modal",
            "data-bs-target" => "#modal_action_form",
            "class" => "btn btn-sm btn-primary form-label-sm",
            ...$extras
          ]
        );
        break;
      case 'modify':
        $oldBatchJobUids = old("batchjob_uids", null);
        $oldBatchJobUids = is_array($oldBatchJobUids) ? $oldBatchJobUids : [$oldBatchJobUids];
        $checkbox = form_checkbox([
          "id" => "checkbox_uid_{$viewDatas['entity']->getPK()}",
          "name" => "batchjob_uids[]",
          "value" => $viewDatas['entity']->getPK(),
          "class" => "batchjobuids_checkboxs",
          "checked" => in_array($viewDatas['entity']->getPK(), $oldBatchJobUids)
        ]);
        $action = $checkbox . form_label(
          $label,
          $action,
          [
            "data-src" => current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK() . '?' . $viewDatas['uri']->getQuery(),
            "data-bs-toggle" => "modal",
            "data-bs-target" => "#modal_action_form",
            'class' => 'form-label-sm',
            ...$extras
          ]
        );
        break;
      case 'view':
        $action = form_label(
          $label ? $label : ICONS['SEARCH'],
          $action,
          [
            "data-src" => current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK() . '?' . $viewDatas['uri']->getQuery(),
            "data-bs-toggle" => "modal",
            "data-bs-target" => "#modal_action_form",
            "class" => "btn btn-sm btn-primary form-label-sm",
            ...$extras
          ]
        );
        break;
      case 'delete':
        $action = anchor(
          current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK(),
          $label ? $label :  ICONS['DELETE'],
          [
            "class" => "btn btn-sm btn-danger form-label-sm",
            ...$extras
          ]
        );
        break;
      case 'batchjob':
        $action = form_submit("batchjob_submit", $label ? $label : '일괄처리', [
          "formaction" => current_url() . '/batchjob',
          "class" => "btn btn-sm btn-warning form-label-sm",
          ...$extras,
          // "onclick" => "return submitBatchJob()"
        ]);
        break;
      case 'batchjob_delete':
        $action = form_submit("batchjob_submit", $label ? $label : '일괄삭제', [
          "formaction" => current_url() . '/batchjob_delete',
          "class" => "btn btn-sm btn-danger form-label-sm",
          ...$extras,
          // "onclick" => "return submitBatchJobDelete()"
        ]);
        break;
      default:
        $action = "";
        break;
    }
    return $action;
  }
}
