<?php
namespace front\factory;
class GlobelusCandidates
{
  public static function register_candidate( $email, $name, $surname, $phone, $date_of_birth, $sex, $positions, $positions_experience, $inexperience, $categories, $languages, $languages_experience,
          $countries, $voivodeships, $status_of_availability, $date_of_availability, $experience_abroad, $accommodation, $driving_license, $own_car, $other_information, $cv_file, $avatar_file )
  {
    global $mdb, $settings;

    $result = [ 'status' => 'bad', 'msg' => \S::lang( 'rejestracja-blad-ogolny' ) ];

    if ( $mdb -> count( 'globelus_users', [ 'email' => $email ] ) )
      return $result = [ 'status' => 'bad', 'msg' => 'Mamy juz Twój adres w naszej bazie, jeśli nie pamiętasz hasła do swojego konta kliknij <a href="/odzyskiwanie-hasla">tutaj</a>.' ];

    /* obsługa cv */
    $allowed_mime_types = \front\factory\Globelus::cv_allowed_mime_types();

    if ( $cv_file['tmp_name'] and $cv_file["size"] > 5242880 )
      return $result = [ 'status' => 'bad', 'msg' => \S::lang( 'plik-cv-jest-zbyt-duzy' ) ];

    if ( $cv_file['tmp_name'] and !$cv_error and !in_array( $cv_file["type"], $allowed_mime_types ) )
      return $result = [ 'status' => 'bad', 'msg' => \S::lang( 'cv-niedozwolony-format-pliku' ) ];

    /* obsługa avatarów */
    $allowed_mime_types = \front\factory\Globelus::avatar_allowed_mime_types();

    if ( $avatar_file['tmp_name'] and $avatar_file["size"] > 1048576 )
      return $result = [ 'status' => 'bad', 'msg' => \S::lang( 'plik-zdjecie-jest-zbyt-duzy' ) ];

    if ( $avatar_file['tmp_name'] and !$avatar_error and !in_array( $avatar_file["type"], $allowed_mime_types ) )
      return $result = [ 'status' => 'bad', 'msg' => \S::lang( 'zdjecie-niedozwolony-format-pliku' ) ];

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

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

    $user_id = $mdb -> id();

    $mdb -> insert( 'globelus_candidates_data', [
              'user_id'                 => $user_id,
              'name'                    => $name,
              'surname'                 => $surname,
              'date_of_birth'           => $date_of_birth ? date( 'Y-m-d', strtotime( $date_of_birth ) ) : null,
              'sex'                     => $sex === '' ? null : $sex,
              'phone'                   => $phone,
              'experience_abroad'       => $experience_abroad === '' ? null : $experience_abroad,
              'status_of_availability'  => $status_of_availability,
              'date_of_availability'    => $date_of_availability,
              'accommodation'           => $accommodation === '' ? null : $accommodation,
              'driving_license'         => $driving_license === '' ? null : $driving_license,
              'own_car'                 => $own_car === '' ? null : $own_car,
              'inexperience'            => $inexperience == 'on' ? 1 : 0,
              'other_information'       => $other_information
            ] );

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

    /* doświadczenie */
    if ( !$inexperience )
    {
      for ( $i = 0; $i < count( $positions ); $i++ )
      {
        if ( $positions[$i] )
          $mdb -> insert( 'globelus_candidates_positions', [
            'user_id'     => $user_id,
            'id_position' => $positions[$i],
            'experience'  => $positions_experience[$i]
          ] );
      }
    }

    /* języki */
    for ( $i = 0; $i < count( $languages ); $i++ )
    {
      if ( $languages[$i] and $languages_experience[$i] )
        $mdb -> insert( 'globelus_candidates_languages', [
                  'user_id'     => $user_id,
                  'language'    => $languages[$i],
                  'experience'  => $languages_experience[$i]
                ] );
    }

    /* kraje */
    for ( $i = 0; $i < count( $countries ); $i++ )
    {
      if ( $countries[$i] and !$mdb -> count( 'globelus_candidates_countries', [ 'AND' => [ 'user_id' => $user_id, 'country_id' => $countries[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_countries', [
                  'user_id'    => $user_id,
                  'country_id' => $countries[$i],
                ] );
    }

    /* wojewodztwa */
    for ( $i = 0; $i < count( $voivodeships ); $i++ )
    {
      if ( $voivodeships[$i] and !$mdb -> count( 'globelus_candidates_voivodeships', [ 'AND' => [ 'id_user' => $user_id, 'id_voivodeship' => $voivodeships[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_voivodeships', [
                  'id_user' => $user_id,
                  'id_voivodeship' => $voivodeships[$i],
                ] );
    }

    /* branże */
    for ( $i = 0; $i < count( $categories ); $i++ )
    {
      if ( $categories[$i] and !$mdb -> count( 'globelus_candidates_categories', [ 'AND' => [ 'user_id' => $user_id, 'category_id' => $categories[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_categories', [
                  'user_id'     => $user_id,
                  'category_id' => $categories[$i],
                ] );
    }

    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 ( $avatar_file['tmp_name'] and !$avatar_error )
    {
      $avatar_hash  = \front\factory\GlobelusCandidates::avatar_hash( $user_id );
      $dir      = 'files/avatars/' . $avatar_hash{0} . '/' . $avatar_hash{1} . '/';

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

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

      move_uploaded_file( $avatar_file['tmp_name'], $dir . $avatar_hash );

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

    $text = $settings['newsletter_header'];
    $text .= \front\factory\Newsletter::get_template( '#globelus-potwierdzenie-automatycznej-rejestracji' );
    $text .= '<p style="font-size: 13px; font-style: italic; color:#95a5a6; padding: 0 20px;">' . \S::lang( 'rejestracja-kandydat-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, \S::lang( 'potwierdzenie-rejestracji-konta-w-portalu' ) . ' GLOBELUS.PL', $text );

    \front\factory\GlobelusUser::signin( null, null, null, null, $hash );

    return $result = [ 'status' => 'ok', 'msg' => 'Twoje konto zostało założone. Dane do logowania zostały wysłane na podany adres email.' ];
  }

  public static function candidate_categories( $user_id )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'name '
                            . 'FROM '
                              . 'globelus_adverts_categories AS gac '
                              . 'INNER JOIN globelus_candidates_categories AS gcc ON gcc.category_id = gac.id '
                            . 'WHERE '
                              . 'gcc.user_id = ' . (int)$user_id ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function candidate_positions( $user_id )
  {
    global $mdb;
    return $mdb -> select( 'globelus_candidates_positions', [ 'position', 'experience', 'id_position' ], [ 'user_id' => $user_id ] );
  }

  public static function avatar_extension( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_candidates_data', 'avatar_extension', [ 'user_id' => $user_id ] );
  }

  public static function avatar_url( $user_id )
  {
    $avatar_hash = \front\factory\GlobelusCandidates::avatar_hash( $user_id );
    return $file_name    = 'files/avatars/' . $avatar_hash{0} . '/' . $avatar_hash{1} . '/' . $avatar_hash;
  }

  public static function avatar( $user_id, $token )
  {
    if ( $_SESSION['tokens'][$token] )
    {
      $avatar_hash  = \front\factory\GlobelusCandidates::avatar_hash( $user_id );
      $extension    = \front\factory\GlobelusCandidates::avatar_extension( $user_id );
      $file_name    = 'files/avatars/' . $avatar_hash{0} . '/' . $avatar_hash{1} . '/' . $avatar_hash;

      if ( file_exists( $file_name ) )
      {
        switch( $extension ):
          case "png": $ctype="image/png"; break;
          case "jpeg":
          case "jpg": $ctype="image/jpeg"; break;
          default:
        endswitch;

        header( 'Content-Type: ' . $ctype );
        readfile( $file_name );
        exit;
      }
    }
  }

  public static function cv_tmp_download( $answer_id, $token )
  {
    global $mdb;

    if ( $_SESSION['tokens'][$token] )
    {
      $cv_info = $mdb -> get( 'globelus_adverts_answers', [ 'cv', 'cv_extension' ], [ 'id' => $answer_id ] );

      if ( file_exists( $cv_info['cv'] ) )
      {
        $tmp_filename = "cv." . $cv_info['cv_extension'];
        $file_name    = $cv_info['cv'];

        header("Content-type: application/pdf");
        header("Content-type: octet-stream");
        header( "Content-Disposition: attachment; filename=$tmp_filename" );
        header( "Content-Length: " . filesize( $file_name ) );
        readfile( $file_name );
        exit;
      }
    }
  }

  public static function profile_visits_increase( $candidate_id, $firm_id )
  {
    global $mdb;
    $mdb -> insert( 'globelus_candidates_visits', [
              'candidate_id'  => $candidate_id,
              'firm_id'       => $firm_id
            ] );
    return $mdb -> update( 'globelus_users', [ 'visits[+]' => 1 ], [ 'id' => $candidate_id ] );
  }

  public static function adverts_list( $user_id )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'ga.title, ga.date_add, ga.user_id, ga.id, gc.name AS country, ga.city, firm_name_profile, gac.name AS category, text '
                            . 'FROM '
                              . 'globelus_adverts AS ga '
                              . 'INNER JOIN globelus_candidates_adverts AS gca ON gca.advert_id = ga.id '
                              . 'LEFT JOIN globelus_countries AS gc ON gc.id = ga.country_id '
                              . 'INNER JOIN globelus_firms_data AS gfd ON gfd.user_id = ga.user_id '
                              . 'LEFT JOIN globelus_adverts_categories AS gac ON gac.id = ga.category_id '
                            . 'WHERE '
                                . 'gca.user_id = ' . (int)$user_id . ' '
                              . 'AND '
                                . 'ga.visible = 1 '
                            . 'ORDER BY '
                                . 'ga.date_add DESC' ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function answers_list( $user_id )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'ga.title, gaa.date_add, gaa.text, displayed, ga.user_id, ga.id '
                            . 'FROM '
                              . 'globelus_adverts AS ga '
                              . 'INNER JOIN globelus_adverts_answers AS gaa ON gaa.advert_id = ga.id '
                            . 'WHERE '
                                . 'gaa.user_id = ' . (int)$user_id . ' '
                              . 'AND '
                                . 'ga.visible = 1 '
                            . 'ORDER BY '
                                . 'gaa.date_add DESC' ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function cv_extension( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_candidates_data', 'cv_extension', [ 'user_id' => $user_id ] );
  }

  public static function avatar_hash( $user_id )
  {
    return md5( 'files/avatars/' . $user_id . '/' );
  }

  public static function cv_hash( $user_id )
  {
    return md5( 'files/cv/' . $user_id . '/' );
  }

  public static function cv_url( $user_id )
  {
    $cv_hash = \front\factory\GlobelusCandidates::cv_hash( $user_id );
    return $file_name    = 'files/cv/' . $cv_hash{0} . '/' . $cv_hash{1} . '/' . $cv_hash;
  }

  public static function cv_download( $user_id, $token )
  {
    if ( $_SESSION['tokens'][$token] )
    {
      $cv_hash    = \front\factory\GlobelusCandidates::cv_hash( $user_id );
      $extension  = \front\factory\GlobelusCandidates::cv_extension( $user_id );
      $file_name  = 'files/cv/' . $cv_hash{0} . '/' . $cv_hash{1} . '/' . $cv_hash;

      if ( file_exists( $file_name ) )
      {
        $tmp_filename = "cv." . $extension;

        header("Content-type: octet-stream");
        header( "Content-Disposition: attachment; filename=$tmp_filename" );
        header( "Content-Length: " . filesize( $file_name ) );
        readfile( $file_name );
        exit;
      }
    }
  }

  public static function profile_disable( $user_id )
  {
    global $mdb;
    return $mdb -> update( 'globelus_users', [
                    'visible' => 0
                  ], [
                    'id' => $user_id
                  ] );
  }

  public static function profile_enable( $user_id, $email = '' )
  {

    global $mdb, $lang, $settings;

    if ( !$mdb -> get( 'globelus_users', 'visible_mail', [ 'id' => $user_id ] ) and $email )
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template( '#twoj-profil-jest-juz-widoczny' );

      $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-profil-jest-juz-widoczny'], $text );

      $mdb -> update( 'globelus_users', [ 'visible_mail' => 1 ], [ 'id' => $user_id ] );
    }
    return $mdb -> update( 'globelus_users', [
                    'visible' => 1
                  ], [
                    'id' => $user_id
                  ] );
  }

  public static function profile_extend( $user_id, $active_to )
  {
    global $mdb;

    $active_diff = \S::date_diff( date( 'Y-m-d H:i:s' ), date( 'Y-m-d H:i:s', strtotime( $active_to ) ), 60 * 60 * 24 );
    if ( $active_diff <= 7 )
    {
      $mdb -> update( 'globelus_users', [
                'active_to' => date( 'Y-m-d', strtotime( '+90 days', strtotime( $active_to ) ) ),
                'mail_expiration' => 0,
                'mail_expired'    => 0,
                'mail_delete' => 0,
                'mail_delete_date' => null,
              ], [
                'id' => $user_id
              ] );
      return true;
    }
    return false;
  }

  public static function profile_refresh( $user_id, $last_refresh )
  {
    global $mdb;

    $refresh_diff = \S::date_diff( date( 'Y-m-d H:i:s', strtotime( $last_refresh ) ), date( 'Y-m-d H:i:s' ), 60 * 60 * 24 );
    if ( $refresh_diff >= 5 )
    {
      $mdb -> update( 'globelus_candidates_data', [
                'last_refresh' => date( 'Y-m-d H:i:s' )
              ], [
                'user_id' => $user_id
              ] );
      return true;
    }
    return false;
  }

  public static function datą_save( $user_id, $name, $surname, $date_of_birth, $sex, $phone, $experience_abroad, $status_of_availability, $date_of_availability, $accommodation, $driving_license, $own_car,
          $positions, $positions_experience, $inexperience, $countries, $voivodeships, $languages, $languages_experience, $other_information, $categories, $cv_file, $avatar_file )
  {
    global $mdb, $lang;

    if ( $data_id = $mdb -> get( 'globelus_candidates_data', 'id', [ 'user_id' => $user_id ] ) )
      $mdb -> update( 'globelus_candidates_data', [
        'name'                    => $name,
        'surname'                 => $surname,
        'date_of_birth'           => $date_of_birth ? date( 'Y-m-d', strtotime( $date_of_birth ) ) : null,
        'sex'                     => $sex === '' ? null : $sex,
        'phone'                   => $phone,
        'experience_abroad'       => $experience_abroad === '' ? null : $experience_abroad,
        'status_of_availability'  => $status_of_availability,
        'date_of_availability'    => $date_of_availability,
        'accommodation'           => $accommodation === '' ? null : $accommodation,
        'driving_license'         => $driving_license === '' ? null : $driving_license,
        'own_car'                 => $own_car === '' ? null : $own_car,
        'inexperience'            => $inexperience == 'on' ? 1 : 0,
        'other_information'       => $other_information
      ], [
        'id'                      => $data_id
      ] );
    else
      $mdb -> insert( 'globelus_candidates_data', [
        'user_id'                 => $user_id,
        'name'                    => $name,
        'surname'                 => $surname,
        'date_of_birth'           => $date_of_birth ? date( 'Y-m-d', strtotime( $date_of_birth ) ) : null,
        'sex'                     => $sex === '' ? null : $sex,
        'phone'                   => $phone,
        'experience_abroad'       => $experience_abroad === '' ? null : $experience_abroad,
        'status_of_availability'  => $status_of_availability,
        'date_of_availability'    => $date_of_availability,
        'accommodation'           => $accommodation === '' ? null : $accommodation,
        'driving_license'         => $driving_license === '' ? null : $driving_license,
        'own_car'                 => $own_car === '' ? null : $own_car,
        'inexperience'            => $inexperience == 'on' ? 1 : 0,
        'other_information'       => $other_information
      ] );

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

    /* doświadczenie */
    $mdb -> delete( 'globelus_candidates_positions', [ 'user_id' => $user_id ] );
    if ( !$inexperience )
    {
      for ( $i = 0; $i < count( $positions ); $i++ )
      {
        if ( $positions[$i] )
          $mdb -> insert( 'globelus_candidates_positions', [
                    'user_id' => $user_id,
                    'id_position' => $positions[$i],
                    'experience' => $positions_experience[$i]
                  ] );
      }
    }

    /* języki */
    $mdb -> delete( 'globelus_candidates_languages', [ 'user_id' => $user_id ] );
    for ( $i = 0; $i < count( $languages ); $i++ )
    {
      if ( $languages[$i] and $languages_experience[$i] )
        $mdb -> insert( 'globelus_candidates_languages', [
                  'user_id'     => $user_id,
                  'language'    => $languages[$i],
                  'experience'  => $languages_experience[$i]
                ] );
    }

    /* kraje */
    $not_in = '0';
    if ( is_array( $countries ) and !empty( $countries ) ) foreach ( $countries as $country )
    {
      $not_in .= ',' . (int)$country;
    }

    $mdb -> query( 'DELETE FROM globelus_candidates_countries WHERE user_id = ' . (int)$user_id . ' AND country_id NOT IN (' . $not_in . ')' );
    for ( $i = 0; $i < count( $countries ); $i++ )
    {
      if ( $countries[$i] and !$mdb -> count( 'globelus_candidates_countries', [ 'AND' => [ 'user_id' => $user_id, 'country_id' => $countries[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_countries', [
                  'user_id'    => $user_id,
                  'country_id' => $countries[$i],
                ] );
    }

    /* województwa */
    $not_in = '0';
    if ( is_array( $voivodeships ) and !empty( $voivodeships ) ) foreach ( $voivodeships as $voivodeship )
    {
      $not_in .= ',' . (int)$voivodeship;
    }

    $mdb -> query( 'DELETE FROM globelus_candidates_voivodeships WHERE id_user = ' . (int)$user_id . ' AND id_voivodeship NOT IN (' . $not_in . ')' );
    for ( $i = 0; $i < count( $voivodeships ); $i++ )
    {
      if ( $voivodeships[$i] and !$mdb -> count( 'globelus_candidates_voivodeships', [ 'AND' => [ 'id_user' => $user_id, 'id_voivodeship' => $voivodeships[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_voivodeships', [
                  'id_user' => $user_id,
                  'id_voivodeship' => $voivodeships[$i],
                ] );
    }

    /* branże */
    $not_in = '0';
    if ( is_array( $categories ) and !empty( $categories ) ) foreach ( $categories as $category )
    {
      $not_in .= ',' . (int)$category;
    }

    $mdb -> query( 'DELETE FROM globelus_candidates_categories WHERE user_id = ' . (int)$user_id . ' AND category_id NOT IN (' . $not_in . ')' );
    for ( $i = 0; $i < count( $categories ); $i++ )
    {
      if ( $categories[$i] and !$mdb -> count( 'globelus_candidates_categories', [ 'AND' => [ 'user_id' => $user_id, 'category_id' => $categories[$i] ] ] ) )
        $mdb -> insert( 'globelus_candidates_categories', [
                  'user_id'     => $user_id,
                  'category_id' => $categories[$i],
                ] );
    }

    /* obsługa plików CV */
    $allowed_mime_types = \front\factory\Globelus::cv_allowed_mime_types();

    $cv_error = false;

    if ( $cv_file['tmp_name'] and $cv_file["size"] > 5242880 )
    {
      \S::set_alert_prompt( 'Informacja', $lang['plik-cv-jest-zbyt-duzy'] );
      $cv_error = true;
      return false;
    }

    if ( $cv_file['tmp_name'] and !$cv_error and !in_array( $cv_file["type"], $allowed_mime_types ) )
    {
      \S::set_alert_prompt( 'Informacja', $lang['cv-niedozwolony-format-pliku'] );
      return false;
    }

    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 ] );
    }

    /* obsługa avatarów */
    $allowed_mime_types = \front\factory\Globelus::avatar_allowed_mime_types();

    $avatar_error = false;

    if ( $avatar_file['tmp_name'] and $avatar_file["size"] > 1048576 )
    {
      \S::set_alert_prompt( 'Informacja', $lang['plik-zdjecie-jest-zbyt-duzy'] );
      $avatar_error = true;
      return false;
    }

    if ( $avatar_file['tmp_name'] and !$avatar_error and !in_array( $avatar_file["type"], $allowed_mime_types ) )
    {
      \S::set_alert_prompt( 'Informacja', $lang['zdjecie-niedozwolony-format-pliku'] );
      return false;
    }

    if ( $avatar_file['tmp_name'] and !$avatar_error )
    {
      $avatar_hash  = \front\factory\GlobelusCandidates::avatar_hash( $user_id );
      $dir      = 'files/avatars/' . $avatar_hash{0} . '/' . $avatar_hash{1} . '/';

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

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

      move_uploaded_file( $avatar_file['tmp_name'], $dir . $avatar_hash );

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

    return true;
  }
}
