<?php

namespace App\Helpers;

abstract class CommonHelper
{
  protected function __construct() {}
  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;
  } //
  final public function isDomain(string $domain): bool
  {
    $parttern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
    return preg_match("$parttern_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 public function isHost(string $host): bool
  {
    $parttern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/';
    return preg_match($parttern_validation, $host);
  }
  //(EX:192.168.1.0 -> 192.168.001.000)
  final public function convertIPV4toCIDR($cidr)
  {
    $temps = explode(".", $cidr);
    return sprintf("%03d.%03d.%03d.%03d", $temps[0], $temps[1], $temps[2], $temps[3]);
  } //
  //(EX:192.168.001.0000 -> 192.168.1.0)
  final public function convertCIDRtoIPV4($ipv4)
  {
    $temps = explode(".", $ipv4);
    return sprintf("%d.%d.%d.%d", $temps[0], $temps[1], $temps[2], $temps[3]);
  } //
  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;
      case 'back':
        $msg .= "history.back();";
        break;
      default:
        $msg .= $url ? "location.href=\"{$url}\";" : "";
        break;
    }
    return "<script type=\"text/javascript\">{$msg}</script>";
  } //

  public function getFieldLabel(string $field, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      default:
        if (strpos($viewDatas['field_rules'][$field], 'required') !== false) {
          $extras = ["class" => 'text-danger', ...$extras];
        }
        $label = form_label(lang("{$viewDatas['class_path']}.label.{$field}"), $field, $extras);
        break;
    }
    return $label;
  }
  //header.php에서 getFieldForm_Helper사용
  public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
  {
    $value = $value ?: DEFAULTS['EMPTY'];
    switch ($field) {
      case 'status':
        $form = form_dropdown($field, [
          "" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택',
          ...$viewDatas['field_options'][$field]
        ], $value, $extras);
        break;
      case 'updated_at':
      case 'created_at':
        $extra_class = isset($extras['class']) ? $extras['class'] . ' calender' : 'calender';
        $form = form_input($field, $value, ['class' => $extra_class, ...array_diff_key($extras, ['class' => ''])]);
        break;
      default:
        $form = form_input($field, $value, ["autocomplete" => $field, ...$extras]);
        break;
    }
    return $form;
  } //
  public function getFieldView(string $field, array $viewDatas, array $extras = []): string
  {
    $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
    switch ($field) {
      case 'category_uid':
        foreach (array_values($viewDatas['field_options'][$field]) as $category_2depths) {
          foreach ($category_2depths as $key => $depth) {
            if ($key == $depth) {
              $value = $depth;
            }
          }
        }
        break;
      case 'updated_at':
      case 'created_at':
        $value = $value ? date("Y-m-d", strtotime($value)) : "";
        break;
      default:
        if (in_array($field, $viewDatas['filter_fields']) && $value) {
          $extras["onChange"] = sprintf(
            'location.href="%s/toggle/%s/%s?%s="+this.options[this.selectedIndex].value',
            current_url(),
            $viewDatas['entity']->getPK(),
            $field,
            $field
          );
          $value = $this->getFieldForm($field, $viewDatas['entity']->$field, $viewDatas, $extras);
        }
        break;
    }
    return $value;
  } //
  public function getListRowColor($entity): string
  {
    return $entity->status != DEFAULTS['STATUS'] ? 'class="table-danger"' : "";
  }
  public function getListLabel(string $field, array $viewDatas, array $extras = []): string
  {
    switch ($field) {
      default:
        $label = $this->getFieldLabel($field, $viewDatas, $extras);
        if (isset($viewDatas['order_field']) && $viewDatas['order_field'] == $field) {
          $label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"];
        }
        $viewDatas['uri']->addQuery('order_field', $field);
        $viewDatas['uri']->addQuery('order_value', $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC");
        $label = anchor(current_url() . ($viewDatas['uri']->getQuery() ? "?" . $viewDatas['uri']->getQuery() : ""), $label);
        break;
    }
    return $label;
  }
  public function getListButton(string $action, array $viewDatas, array $extras = []): string
  {
    switch ($action) {
      case 'create':
        $extras = ["class" => "btn btn-outline btn-primary btn-circle", "target" => "_self", ...$extras];
        $action = form_label(
          '입력',
          $action,
          [
            "data-src" => current_url() . '/' . $action,
            "data-bs-toggle" => "modal",
            "data-bs-target" => "#index_action_form",
            ...$extras
          ]
        );
        break;
      case 'modify':
        $pk = $viewDatas['entity']->getPK();
        $oldBatchJobUids = old("batchjob_uids", []);
        $oldBatchJobUids = is_array($oldBatchJobUids) ? $oldBatchJobUids : [$oldBatchJobUids];
        $checkbox = form_checkbox([
          "id" => "checkbox_uid_{$pk}",
          "name" => "batchjob_uids[]",
          "value" => $pk,
          "class" => "batchjobuids_checkboxs",
          "checked" => in_array($pk, $oldBatchJobUids)
        ]);
        $action = $checkbox . form_label(
          $viewDatas['cnt'],
          $action,
          [
            "data-src" => current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK(),
            "data-bs-toggle" => "modal",
            "data-bs-target" => "#index_action_form",
            ...$extras
          ]
        );
        break;
      case 'delete':
        $extras = ["class" => "btn btn-sm btn-danger btn-circle", "target" => "_self", ...$extras];
        $action = anchor(
          current_url() . '/' . $action . '/' . $viewDatas['entity']->getPK(),
          ICONS['DELETE'],
          $extras
        );
        break;
      case 'batchjob':
        $action = form_submit("batchjob_submit", '일괄처리', [
          "class" => "btn btn-outline btn-warning",
          "onclick" => "return submitBatchJob()"
        ]);
        break;
    }
    return $action;
  }
}
