<?php
class S
{
  public static function array_unique_multi( $array, $key )
  {
     $temp_array = [];
     foreach ($array as &$v) {
         if (!isset($temp_array[$v[$key]]))
         $temp_array[$v[$key]] =& $v;
     }
     $array = array_values($temp_array);
     return $array;

  }

  static public function number_display( $value )
  {
    return number_format( $value, 2, ',', ' ' ) . ' zł';
  }

  public static function prepar_request( $query )
  {
    if ( is_array( $query ) && !empty( $query ) )
    {
      foreach ( $query as $key => $value )
        $query[$key] = urlencode( $key ) . '=' . urlencode( $value );
      return implode( '&', $query );
    }
    else
      return false;
  }

  public static function seo( $val, $delete_rhombs = false )
  {
    $array_rep1 = array( '*', '_', ' ', '+', '"', "'", '?', '-', ',', '!', '~', '<', '>', '@', '#', '$', '%', '^', '&', '*' . '(', ')' . '-', '=', '\\', '|', '[', ']', ':', '(', ')' );
    $array_rep2 = array( '-', '-', '-', '-', '', '', '', '-', '-', '', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '', '-', '-', '-', '-', '-', '-', '-', '-' );

    $val = self::noPl( $val );
    $val = str_replace( $array_rep1, $array_rep2, $val );
    $val = strtolower( $val );
    $val = preg_replace( '/(-){2,}/', '-', $val );
    if ( $delete_rhombs )
      $val = str_replace( '/', '', $val );

    return $val;
  }

  static public function no_pl_excel( $val )
  {
    $table = Array(
          "\xc4\x85" => "a", "\xc4\x84" => "A", "\xc4\x87" => "c", "\xc4\x86" => "C",
          "\xc4\x99" => "e", "\xc4\x98" => "E", "\xc5\x82" => "l", "\xc5\x81" => "L",
          "\xc3\xb3" => "o", "\xc3\x93" => "O", "\xc5\x9b" => "s", "\xc5\x9a" => "S",
          "\xc5\xbc" => "z", "\xc5\xbb" => "Z", "\xc5\xba" => "z", "\xc5\xb9" => "Z",
          "\xc5\x84" => "n", "\xc5\x83" => "N"
    );

    $val = strtr( $val, $table );

    return $val;
  }

  public static function noPL( $val )
  {
    $table = array(
            "А" => "a", "Б" => "b", "В" => "v", "Г" => "g", "Д" => "d",
            "Е" => "e", "Ё" => "yo", "Ж" => "zh", "З" => "z", "И" => "i",
            "Й" => "j", "К" => "k", "Л" => "l", "М" => "m", "Н" => "n",
            "О" => "o", "П" => "p", "Р" => "r", "С" => "s", "Т" => "t",
            "У" => "u", "Ф" => "f", "Х" => "kh", "Ц" => "ts", "Ч" => "ch",
            "Ш" => "sh", "Щ" => "sch", "Ъ" => "", "Ы" => "y", "Ь" => "",
            "Э" => "e", "Ю" => "yu", "Я" => "ya", "а" => "a", "б" => "b",
            "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ё" => "yo",
            "ж" => "zh", "з" => "z", "и" => "i", "й" => "j", "к" => "k",
            "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p",
            "р" => "r", "с" => "s", "т" => "t", "у" => "u", "ф" => "f",
            "х" => "kh", "ц" => "ts", "ч" => "ch", "ш" => "sh", "щ" => "sch",
            "ъ" => "", "ы" => "y", "ь" => "", "э" => "e", "ю" => "yu",
            "я" => "ya", " " => "-", "." => "", "," => "",
            ":" => "", ";" => "", "—" => "", "–" => "-"
    );

    $val = strtr( $val, $table );

    $val = iconv( 'UTF-8', 'ASCII//TRANSLIT',  $val );

    $table = Array(
            "\xc4\x85" => "a", "\xc4\x84" => "A", "\xc4\x87" => "c", "\xc4\x86" => "C",
            "\xc4\x99" => "e", "\xc4\x98" => "E", "\xc5\x82" => "l", "\xc5\x81" => "L",
            "\xc3\xb3" => "o", "\xc3\x93" => "O", "\xc5\x9b" => "s", "\xc5\x9a" => "S",
            "\xc5\xbc" => "z", "\xc5\xbb" => "Z", "\xc5\xba" => "z", "\xc5\xb9" => "Z",
            "\xc5\x84" => "n", "\xc5\x83" => "N"
    );

    $val = strtr( $val, $table );

    return $val;
  }

  public static function alert( $text )
  {
    \S::set_session( 'alert', $text );
  }

  public static function hash( $qtd )
  {
    $Caracteres = 'ABCDEFGHIJKLMOPQRSTUVXWYZ0123456789';
    $QuantidadeCaracteres = strlen($Caracteres);
    $QuantidadeCaracteres--;

    $Hash  =NULL;
    for ( $x = 1; $x <= $qtd; $x++ )
    {
      $Posicao = rand( 0, $QuantidadeCaracteres );
      $Hash .= substr( $Caracteres, $Posicao, 1 );
    }

    return $Hash;
  }

  public static function sort_array_of_array( &$array, $subfield, $type = SORT_ASC )
  {
    $sortarray = array();
    foreach ( $array as $key => $row )
      $sortarray[$key] = $row[$subfield];

    array_multisort( $sortarray, $type, $array );
  }

  public static function json_to_array( $json )
  {
    $values_tmp = json_decode( $json, true );

    if ( is_array( $values_tmp ) ) foreach ( $values_tmp as $val )
    {
      if ( isset( $values[ $val['name'] ] ) )
      {
        if ( is_array( $values[ $val['name'] ] ) )
          $values[ $val['name'] ][] = $val['value'];
        else
          $values[ $val['name'] ] = array( $values[ $val['name'] ], $val['value'] );
      }
      else
        $values[ $val['name'] ] = $val['value'];
    }
    return $values;
  }

  public static function get_session( $var )
  {
    return $_SESSION[ $var ];
  }

  public static function del_session( $var ) {
    unset( $_SESSION[ $var ] );
  }

	public static function set_session( $var, $val )
	{
    $_SESSION[ $var ] = $val;
	}

  public static function get( $var )
	{
		if ( isset( $_POST[ $var ] ) )
    {
      if ( is_string( $_POST[ $var ] ) )
        return $_POST[ $var ];
      else
        return $_POST[ $var ];
    }
    else
    {
      if ( isset( $_GET[ $var ] ) )
      {
        if ( is_string( $_GET[ $var ] ) )
          return $_GET[ $var ];
        else
          return $_GET[ $var ];
      }
    }
	}

  public static function pre( $data , $type = '' )
  {
    $data = str_replace( 'Array
(' , '' , $data );
    $data = str_replace( ')' , '' , $data );

    echo '<pre';
      if ( $type == 'error' )
        echo ' style="color: #cc0000;" ';
      else if ( $type == 'info' )
        echo ' style="color: #2c539e;" ';
      else
        echo ' style="color: #8fc400;" ';
    echo '>' . print_r( $data , true ) . '</pre>';
  }

  public static function csrf_token()
  {
    if ( empty( $_SESSION['csrf_token'] ) )
      $_SESSION['csrf_token'] = bin2hex( random_bytes( 32 ) );

    return $_SESSION['csrf_token'];
  }

  public static function csrf_verify()
  {
    $token = isset( $_POST['csrf_token'] ) ? $_POST['csrf_token'] : '';
    return is_string( $token ) && hash_equals( $_SESSION['csrf_token'] ?? '', $token );
  }

  public static function email_check( $email )
  {
    return filter_var( $email, FILTER_VALIDATE_EMAIL );
  }

  public static function send_email( $email, $subject, $text, $file = '' )
  {
    global $settings;

    $mail = new PHPMailer;
    $mail -> IsSMTP();
    $mail -> SMTPAuth   = true;
    $mail -> Host       = $settings['email_host'];
    $mail -> Port       = $settings['email_port'];
    $mail -> Username   = $settings['email_login'];
    $mail -> Password   = $settings['email_password'];
    $mail -> CharSet = "UTF-8";
    $mail -> SMTPOptions = array(
      'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
      )
    );
    $mail -> From       = 'www@projectpro.pl';
    $mail -> FromName   = 'crmPRO';
    $mail -> addAddress( $email, $email );
    $mail -> addReplyTo( 'biuro@project-pro.pl', 'crmPRO' );
    $mail -> isHTML( true );

    $mail -> Subject = $subject;
    $mail -> Body    = $text;

    if ( is_array( $file ) )
    {
      foreach ( $file as $file_tmp )
      {
        if ( file_exists( $file_tmp ) )
          $mail -> AddAttachment( $file_tmp );
      }
    }
    else
    {
      if ( file_exists( $file ) )
        $mail -> AddAttachment( $file );
    }

    return $mail -> send();
  }
}
