<?php
namespace front\factory;
class GlobelusAdverts
{
  const advert_list_limit = 10;

  static public function get_similar_adverts( $advert )
  {
    global $mdb;
    return $mdb -> rand( 'globelus_adverts', 'id', [ 'AND' => [ 'visible' => 1, 'category_id' => $advert['category_id'], 'id[!]' => $advert['id'] ], 'LIMIT' => 5 ] );
  }

  public static function last_adverts( $limit = 3 )
  {
    global $mdb;

    return $mdb -> query( 'SELECT '
                              . 'ga.id, title, date_add, gc.name AS country, ga.city, firm_name_profile, gac.name AS category, text, visits, ga.user_id, ga.highlight '
                          . 'FROM '
                            . 'globelus_adverts AS ga '
                            . 'LEFT JOIN globelus_countries AS gc ON gc.id = 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 '
                              . 'visible = 1 '
                            . 'AND '
                              . '( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
                          . 'ORDER BY '
                            . 'date_add DESC '
                          . 'LIMIT ' . $limit ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function main_page_adverts( $limit = 5 )
  {
    global $mdb;

    return $mdb -> query( 'SELECT '
                              . 'ga.id, title, date_add, gc.name AS country, ga.city, firm_name_profile, gac.name AS category, text, visits, ga.user_id, ga.highlight '
                          . 'FROM '
                            . 'globelus_adverts AS ga '
                            . 'LEFT JOIN globelus_countries AS gc ON gc.id = 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 '
                              . 'visible = 1 '
                            . 'AND '
                              . '( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
                            . 'AND '
                              . 'main_page = 1 '
                          . 'ORDER BY RAND() '
                          . 'LIMIT ' . $limit ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function top_firms( $limit = 5 )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'gfd.user_id, gfd.firm_name_profile, COUNT(gfd.id) AS cc '
                            . 'FROM '
                              . 'globelus_firms_data AS gfd '
                              . 'INNER JOIN globelus_adverts AS ga ON ga.user_id = gfd.user_id '
                            . 'WHERE '
                                . 'visible = 1 '
                              . 'AND '
                              . '( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
                            . 'GROUP BY '
                              . 'gfd.user_id '
                            . 'ORDER BY '
                              . 'cc DESC, firm_name_profile ASC '
                            . 'LIMIT ' . $limit ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function top_categories( $limit = 5 )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'gac.id, gac.name, COUNT(ga.id) AS cc '
                            . 'FROM '
                              . 'globelus_adverts_categories AS gac '
                              . 'INNER JOIN globelus_adverts AS ga ON ga.category_id = gac.id '
                            . 'WHERE '
                                . 'visible = 1 '
                              . 'AND '
                              . '( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
                            . 'GROUP BY '
                              . 'gac.id '
                            . 'ORDER BY '
                              . 'cc DESC '
                            . 'LIMIT ' . $limit ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function top_countries( $limit = 5 )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'gc.id, gc.name, COUNT(ga.id) AS cc '
                            . 'FROM '
                              . 'globelus_countries AS gc '
                              . 'INNER JOIN globelus_adverts AS ga ON ga.country_id = gc.id '
                            . 'WHERE '
                                . 'visible = 1 '
                              . 'AND '
                              . '( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
                            . 'GROUP BY '
                              . 'gc.id '
                            . 'ORDER BY '
                              . 'cc DESC '
                            . 'LIMIT ' . $limit ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function firms_list()
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'gu.id, firm_name_profile '
                            . 'FROM '
                              . 'globelus_users AS gu '
                              . 'INNER JOIN globelus_firms_data AS gfd ON gfd.user_id = gu.id '
                            . 'WHERE '
                                . 'gu.type = 1 '
                              . 'AND '
                                . 'gu.status = 1 '
                              . 'AND '
                                . 'gu.profile_completed = 1 '
                            . 'ORDER BY '
                              . 'gfd.firm_name ASC ' ) -> fetchAll( \PDO::FETCH_ASSOC );
  }

  public static function refresh_count( $advert_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_adverts', 'refresh_count', [ 'id' => $advert_id ] );
  }

  public static function last_refresh( $advert_id )
  {
    global $mdb;
    $row = $mdb -> get( 'globelus_adverts', [ 'date_add', 'last_refresh' ], [ 'id' => $advert_id ] );
    if ( $row['last_refresh'] )
      return $row['last_refresh'];
    else
      return $row['date_add'];
  }

  public static function active_to( $advert_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_adverts', 'active_to', [ 'id' => $advert_id ] );
  }

  public static function advert_visits_increase( $advert_id )
  {
    global $mdb;
    return $mdb -> update( 'globelus_adverts', [ 'visits[+]' => 1 ], [ 'AND' => [ 'visible' => 1, 'id' => $advert_id ] ] );
  }

  public static function remove_from_favorite( $advert_id, $user_id )
  {
    global $mdb;
    return $mdb -> delete( 'globelus_candidates_adverts', [
              'AND' => [
                'advert_id' => $advert_id,
                'user_id'   => $user_id
              ]
            ] );
  }

  public static function add_to_favorite( $advert_id, $user_id )
  {
    global $mdb;
    return $mdb -> insert( 'globelus_candidates_adverts', [
              'advert_id' => $advert_id,
              'user_id'   => $user_id
            ] );
  }

  public static function advert_title( int $advert_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_adverts', 'title', [ 'id' => (int)$advert_id ] );
  }

  public static function advert_user_id( int $advert_id )
  {
    global $mdb;
    return $mdb -> get( 'globelus_adverts', 'user_id', [ 'id' => $advert_id ] );
  }

  public static function send_message( $advert_id, $user_id = null, $name, $surname, $email, $phone, $text, $cv_file, $register )
  {
    global $mdb, $lang, $settings, $globelus_settings;

    if ( $cv_file['tmp_name'] == '' and $user_id )
    {
      $cv         = \front\factory\GlobelusCandidates::cv_url( $user_id );
      $extension  = \front\factory\GlobelusCandidates::cv_extension( $user_id );
    }
    else if ( $cv_file['tmp_name'] == '' and \S::get_session( 'advert_answer_cv' ) )
    {
      $cv         = \S::get_session( 'advert_answer_cv' );
      $extension  = \S::get_session( 'advert_answer_cv_extension' );
    }
    else if ( $cv_file['tmp_name'] != '' )
    {
      $allowed_mime_types = \front\factory\Globelus::cv_allowed_mime_types();

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

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

      $cv_hash  = \front\factory\GlobelusCandidates::cv_hash( time() );
      $dir      = 'files/cv_tmp/' . $cv_hash{0} . '/' . $cv_hash{1} . '/';

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

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

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

    $mdb -> insert( 'globelus_adverts_answers', [
      'advert_id'     => $advert_id,
      'user_id'       => $user_id ? $user_id : null,
      'name'          => $name,
      'surname'       => $surname,
      'email'         => $email,
      'phone'         => $phone,
      'text'          => $text,
      'cv'            => $cv,
      'cv_extension'  => $extension
    ] );

    if ( $answer_id = $mdb -> id() )
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template( '#powiadomienie-o-zlozonej-aplikacji' );
      $text .= $settings['newsletter_footer_1'];

      $advert_title = self::advert_title( (int)$advert_id );
      $advert_user_id = self::advert_user_id( (int)$advert_id );

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

      $text = str_replace( '[LINK]', $base . "://" . $_SERVER['SERVER_NAME'] . "/login-as/" . \front\factory\GlobelusUser::get_hash( $advert_user_id ) . "?return_url=" . urlencode( '/panel-pracodawcy/odpowiedzi/' . $advert_id . '/' ), $text );

      $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( '[TYTUL_OGLOSZENIA]', $advert_title, $text );

      if ( $globelus_settings['maile-wysylanie'] )
        \S::send_email( self::advert_email( $advert_id ), $lang['aplikacja-na-stanowisko'] . ' ' . $advert_title, $text );

      if ( !$user_id )
      {
        \S::set_session( 'advert_answer_name', $name );
        \S::set_session( 'advert_answer_surname', $surname );
        \S::set_session( 'advert_answer_email', $email );
        \S::set_session( 'advert_answer_phone', $phone );
        \S::set_session( 'advert_answer_cv', $cv );
        \S::set_session( 'advert_answer_cv_extension', $extension );

        if ( $register == 'on' )
        {
          if ( $cv_file['tmp_name'] == '' and \S::get_session( 'advert_answer_cv' ) )
          {
            $cv         = \S::get_session( 'advert_answer_cv' );
            $extension  = \S::get_session( 'advert_answer_cv_extension' );
          }

          $password = \front\factory\Globelus::gen_password();
          \front\factory\GlobelusUser::signup( $email, $password, 0, 'on', 'off', true, $name, $surname, $phone, $cv_file, $cv, $extension, 1 );

          $user_tmp_id = $mdb -> get( 'globelus_users', 'id', [ 'email' => $email ] );
          $mdb -> update( 'globelus_adverts_answers', [ 'user_id' => $user_tmp_id ], [ 'id' => $answer_id ] );
          $mdb -> update( 'globelus_users', [ 'profile_completed' => 1 ], [ 'id' => $user_tmp_id ] );
        }
      }

      return true;
    }
    return false;
  }

  public static function advert_email( $advert_id )
  {
    global $mdb;

    $email = $mdb -> get( 'globelus_adverts', 'email', [ 'id' => $advert_id ] );

    if ( !$email )
      $email = $mdb -> get( 'globelus_users', 'email', [ 'id' => $mdb -> get( 'globelus_adverts', 'user_id', [ 'id' => $advert_id ] ) ] );

    return $email;
  }

  public static function adverts_count( $values, $voivodeships, $accommodation_provided )
  {
    global $mdb;

    if ( is_array( $values['categories'] ) and count( $values['categories'] ) )
      $filtr = 'AND category_id IN (' . implode( ',', $values['categories'] ) . ') ';

    if ( $values['keyword'] )
      $filtr .= 'AND ( '
                    . 'title_nopl LIKE :title_nopl '
                  . 'OR '
                    . 'firm_name_profile_nopl LIKE :firm_name_profile_nopl '
                  . 'OR '
                    . 'text_nopl LIKE :text_nopl '
                  . 'OR '
                    . 'country_nopl LIKE :country_nopl '
                  . 'OR '
                    . 'city_nopl LIKE :city_nopl '
                 . ') ';

    if ( is_array( $values['countries'] ) and count( $values['countries'] ) == 1 and $values['countries'][0] == 75 )
      $filtr .= '';
    else
    {
      if ( is_array( $values['countries'] ) and count( $values['countries'] ) == 1 and $values['countries'][0] == 77 )
        $filtr .= 'AND country_id NOT IN (1) ';
      elseif ( is_array( $values['countries'] ) and count( $values['countries'] ) )
        $filtr .= 'AND country_id IN (' . implode( ',', $values['countries'] ) . ') ';
    }

    if ( is_array( $voivodeships ) and count( $voivodeships ) )
    {
      if ( count( $voivodeships ) == 1 and $voivodeships[0] == 1 )
        {}
      else
        $filtr .= 'AND id_voivodeship IN (' . implode( ',', $voivodeships ) . ') ';
    }
    // var_dump( $voivodeships );

    switch ( $values['time'] ):
      case 1: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-24 hours', time() ) ) . '\' '; break;
      case 2: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-3 days', time() ) ) . '\' '; break;
      case 3: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-7 days', time() ) ) . '\' '; break;
      case 4: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-14 days', time() ) ) . '\' '; break;
      case 5: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-1 months', time() ) ) . '\' '; break;
      case 6: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-2 months', time() ) ) . '\' '; break;
    endswitch;

    if ( is_array( $values['work_types'] ) and ( count( $values['work_types'] ) > 1 or ( count( $values['work_types'] ) == 1 and $values['work_types'][0] != 0 ) ) )
    {
      $filtr_work_type = ' (';
      foreach ( $values['work_types'] as $work_type )
        $filtr_work_type .= ' OR work_type = ' . (int)$work_type . ' ';
      $filtr_work_type .= ') ';
    }

    if ( (int)$values['work_type'] )
      $filtr .= 'AND work_type = ' . (int)$values['work_type'] . ' ';

    // if ( (int)$values['work_type'] )
    //   $filtr .= 'AND work_type = ' . (int)$values['work_type'] . ' ';

    if ( (int)$values['salary'] )
      $filtr .= 'AND salary IS NOT NULL ';

    if ( (int)$values['without_language'] )
      $filtr .= 'AND without_language = 1 ';

    if ( (int)$values['without_experience'] )
      $filtr .= 'AND without_experience = 1 ';

    if ( (int)$values['for_couples'] )
      $filtr .= 'AND for_couples = 1 ';

    if ( (int)$values['outside_eu'] )
      $filtr .= 'AND outside_ue = 1 ';

    if ( (int)$values['without_driving_license'] )
      $filtr .= 'AND without_driving_license = 1 ';

    if ( (int)$values['travel_refund'] )
    $filtr .= 'AND travel_refund = 1 ';

    if ( (int)$accommodation_provided )
    {
      $filtr .= 'AND accommodation = 1 ';
    }

    /* SQL */
    $sql = 'SELECT COUNT(0) '
            . 'FROM ('
              . 'SELECT '
                  . 'ga.id, title, title_nopl, date_add, gc.name AS country, gc.name_nopl AS country_nopl, ga.city, ga.city_nopl, firm_name_profile, firm_name_profile_nopl, gac.name AS category, text, text_nopl, visits, ga.user_id, ga.highlight, category_id, '
                  . 'ga.country_id, IF ( last_refresh IS NULL, date_add, last_refresh ) AS date_active, work_type, salary, without_language, without_experience, for_couples, from_now, outside_ue, without_driving_license, travel_refund, id_voivodeship '
                . 'FROM '
                  . 'globelus_adverts AS ga '
                  . 'INNER JOIN globelus_countries AS gc ON gc.id = country_id ';

      if ( is_array( $voivodeships ) and count( $voivodeships ) )
        $sql .= 'INNER JOIN globelus_voivodeships AS gv ON gv.id = id_voivodeship ';

    $sql .= 'INNER JOIN globelus_firms_data AS gfd ON gfd.user_id = ga.user_id '
          . 'INNER JOIN globelus_adverts_categories AS gac ON gac.id = ga.category_id '
        . 'WHERE '
            . 'visible = 1 '
          . 'AND '
            . 'disabled_by_admin = 0 '
          . 'AND '
            . ' ( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
          . 'AND '
            . '( '
                  . '( last_refresh IS NULL AND date_add >= \'' . date( 'Y-m-d H:i:s', strtotime( '-6 months', time() ) ) . '\' ) '
                . 'OR '
                  . '( last_refresh IS NOT NULL AND last_refresh >= \'' . date( 'Y-m-d', strtotime( '-6 months', time() ) ) . '\' ) '
            . ') '
          . ') AS q1 '
        . 'WHERE '
          . '1=1 '
      . $filtr;
// echo $sql;
    try
    {
      $result = $mdb -> query( $sql, [
                                      ':firm_name_profile_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                      ':title_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                      ':text_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                      ':country_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                      ':city_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%'
                                    ] ) -> fetch();
    }
    catch ( \Throwable $t )
    {
      \S::pre( $mdb -> error() );
      $debug = debug_backtrace(true);
      echo $debug[0]['file'] . ' | ' . $debug[0]['line'];
      exit;
    }

    return $result[0];
  }

  public static function adverts_list( $values, $voivodeships, $accommodation_provided )
  {
    global $mdb;

    if ( $values['start'] < 1 )
       $values['start'] = 0;
    else
       $values['start']--;

    if ( is_array( $values['categories'] ) and count( $values['categories'] ) )
      $filtr .= 'AND category_id IN (' . implode( ',', $values['categories'] ) . ') ';

    if ( $values['keyword'] )
      $filtr .= 'AND ( '
                    . 'title_nopl LIKE :title_nopl '
                  . 'OR '
                    . 'firm_name_profile_nopl LIKE :firm_name_profile_nopl '
                  . 'OR '
                    . 'text_nopl LIKE :text_nopl '
                  . 'OR '
                    . 'country_nopl LIKE :country_nopl '
                  . 'OR '
                    . 'city_nopl LIKE :city_nopl '
                 . ') ';

    if ( is_array( $values['countries'] ) and count( $values['countries'] ) == 1 and $values['countries'][0] == 75 )
      $filtr .= '';
    else
    {
      if ( is_array( $values['countries'] ) and count( $values['countries'] ) == 1 and $values['countries'][0] == 77 )
        $filtr .= 'AND country_id NOT IN (1) ';
      elseif ( is_array( $values['countries'] ) and count( $values['countries'] ) )
        $filtr .= 'AND country_id IN (' . implode( ',', $values['countries'] ) . ') ';
    }

    if ( is_array( $voivodeships ) and count( $voivodeships ) )
    {
      if ( count( $voivodeships ) == 1 and $voivodeships[0] == 1 )
        {}
      else
        $filtr .= 'AND id_voivodeship IN (' . implode( ',', $voivodeships ) . ') ';
    }

    switch ( $values['time'] ):
      case 1: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-24 hours', time() ) ) . '\' '; break;
      case 2: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-3 days', time() ) ) . '\' '; break;
      case 3: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-7 days', time() ) ) . '\' '; break;
      case 4: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-14 days', time() ) ) . '\' '; break;
      case 5: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-1 months', time() ) ) . '\' '; break;
      case 6: $filtr .= 'AND date_active >= \'' . date( 'Y-m-d H:i:s', strtotime( '-2 months', time() ) ) . '\' '; break;
    endswitch;

    if ( is_array( $values['work_types'] ) and ( count( $values['work_types'] ) > 1 or ( count( $values['work_types'] ) == 1 and $values['work_types'][0] != 0 ) ) )
    {
      $filtr_work_type = ' (';
      foreach ( $values['work_types'] as $work_type )
        $filtr_work_type .= ' OR work_type = ' . (int)$work_type . ' ';
      $filtr_work_type .= ') ';
    }

    if ( (int)$values['work_type'] )
      $filtr .= 'AND work_type = ' . (int)$values['work_type'] . ' ';

    if ( (int)$values['salary'] )
      $filtr .= 'AND salary IS NOT NULL ';

    if ( (int)$values['without_language'] )
      $filtr .= 'AND without_language = 1 ';

    if ( (int)$values['without_experience'] )
      $filtr .= 'AND without_experience = 1 ';

    if ( (int)$values['for_couples'] )
      $filtr .= 'AND for_couples = 1 ';

    if ( (int)$values['outside_ue'] )
      $filtr .= 'AND outside_ue = 1 ';

    if ( (int)$values['without_driving_license'] )
      $filtr .= 'AND without_driving_license = 1 ';

    if ( (int)$values['travel_refund'] )
    $filtr .= 'AND travel_refund = 1 ';

    if ( (int)$accommodation_provided )
    {
      $filtr .= 'AND accommodation = 1 ';
    }

    if ( (int)$values['sort'] )
      $order = 'date_active DESC ';
    else
      $order = 'highlight DESC, date_active DESC ';

    /* SQL */
    $sql = 'SELECT * '
            . 'FROM ('
              . 'SELECT '
                  . 'ga.id, title, title_nopl, date_add, gc.name AS country, gc.name_nopl AS country_nopl, ga.city, ga.city_nopl, firm_name_profile, firm_name_profile_nopl, gac.name AS category, text, text_nopl, visits, ga.user_id, ga.highlight, category_id, '
                  . 'ga.country_id, IF ( last_refresh IS NULL, date_add, last_refresh ) AS date_active, last_refresh, work_type, salary, without_language, without_experience, for_couples, from_now, overtime, overtime_quantity, accommodation, accommodation_cost, '
                  . 'travel_refund, outside_ue, without_driving_license, id_voivodeship '
              . 'FROM '
                . 'globelus_adverts AS ga '
                . 'INNER JOIN globelus_countries AS gc ON gc.id = country_id ';

    // jeżeli wybrano jakiekolwiek województwo
    if ( is_array( $voivodeships ) and count( $voivodeships ) )
      $sql .= 'INNER JOIN globelus_voivodeships AS gv ON gv.id = id_voivodeship ';

    $sql .= 'INNER JOIN globelus_firms_data AS gfd ON gfd.user_id = ga.user_id '
                . 'INNER JOIN globelus_adverts_categories AS gac ON gac.id = ga.category_id '
              . 'WHERE '
                  . 'visible = 1 '
                . 'AND '
                  . 'disabled_by_admin = 0 '
                . 'AND '
                    . ' ( active_to >= \'' . date( 'Y-m-d' ) . '\' OR active_to IS NULL ) '
              . ') AS q1 '
          . 'WHERE '
            . '1=1 '
            . $filtr
          . 'ORDER BY '
            . $order
          . 'LIMIT ' . (  $values['start'] * $values['limit'] ) . ',' . $values['limit'];

    try
    {
      $results = $mdb -> query( $sql, [
                                  ':title_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                  ':firm_name_profile_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                  ':text_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                  ':country_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%',
                                  'city_nopl' => '%' . \S::seo( $values['keyword'], true ) . '%'
                                ] ) -> fetchAll( \PDO::FETCH_ASSOC );
    }
    catch ( \Throwable $t )
    {
      \S::pre( $mdb -> error() );
      $debug = debug_backtrace(true);
      echo $debug[0]['file'] . ' | ' . $debug[0]['line'];
      exit;
    }
    return $results;
  }

  public static function advert_details( $advert_id )
  {
    global $mdb;
    return $mdb -> query( 'SELECT '
                              . 'ga.id, title, ga.user_id, category_id, ga.country_id, ga.city, ga.region, text, contact_person, email, ga.phone, gfd.clauses, '
                              . 'gac.name AS category_name, gc.name AS country_name, gfd.firm_name_profile, date_add, salary, work_type, without_language, '
                              . 'without_experience, for_couples, from_now, accommodation, accommodation_cost, overtime, overtime_quantity, travel_refund, outside_ue, without_driving_license, ga.old, ga.visible, id_voivodeship, aplication_link, id_position '
                            . 'FROM '
                              . 'globelus_adverts AS ga '
                              . 'LEFT JOIN globelus_adverts_categories AS gac ON gac.id = ga.category_id '
                              . 'LEFT JOIN globelus_countries AS gc ON gc.id = ga.country_id '
                              . 'LEFT JOIN globelus_firms_data AS gfd ON gfd.user_id = ga.user_id '
                            . 'WHERE '
                              . 'ga.id = ' . (int)$advert_id ) -> fetch( \PDO::FETCH_ASSOC );
  }

  public static function categories( $user_categories = '' )
  {
    global $mdb;
    return $mdb -> select( 'globelus_adverts_categories', [ 'id', 'name' ], [ 'ORDER' => [ 'name' => 'ASC' ] ] );
  }
}