<?php

namespace front\factory;

class GlobelusFirms
{
  const firm_list_limit = 12;

  static public function is_user_advert( $user_id, $advert_id )
  {
    global $mdb;
    return $mdb -> count( 'globelus_adverts', [ 'AND' => [ 'user_id' => $user_id, 'id' => $advert_id ] ] );
  }

  static public function proposed_candidates( $advert_id = null, $adverts )
  {
    global $mdb;

    if ( !$advert_id )
    {
      foreach ( $adverts as $advert )
        $advert_id[] = $advert['id'];
    }

    $results = $mdb -> query( 'SELECT candidate_id, IF ( gu.last_refresh IS NULL, register_date, gu.last_refresh ) AS date_active FROM globelus_proposed_candidates AS gpc INNER JOIN globelus_candidates_data AS gcd ON gcd.user_id = gpc.candidate_id INNER JOIN globelus_users AS gu ON gcd.user_id = gu.id WHERE advert_id IN (' . implode( ',', array_merge( [ 0 ], $advert_id ) ) . ') ORDER BY date_active DESC' ) -> fetchAll( \PDO::FETCH_ASSOC );
    foreach ( $results as $row )
      $candidates[] = $row['candidate_id'];
    return $candidates;
  }

  static public function active_adverts_list( $user_id )
  {
    global $mdb;
    return $mdb -> select( 'globelus_adverts', [ 'id', 'title' ], [ 'AND' => [ 'user_id' => $user_id, 'visible' => 1 ], 'ORDER' => [ 'title' => 'ASC' ] ] );
  }

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

  public static function generate_order($user_id, $package, $points, $price)
  {
    global $mdb;

    $mdb->insert('globelus_orders', [
      'hash' => md5(time() . $user_id),
      'user_id' => $user_id,
      'points' => $points,
      'price' => $price,
      'status' => 0
    ]);
    $order_id = $mdb->id();

    return $mdb->get('globelus_orders', 'hash', ['id' => $order_id]);
  }

  static public function user_adverts_count($user_id)
  {
    global $mdb;
    return $mdb->count('globelus_adverts', ['user_id' => $user_id]);
  }

  public static function adverts_count($user_id)
  {
    global $mdb;
    return $mdb->count('globelus_adverts', ['AND' => ['user_id' => $user_id, 'visible' => 1]]);
  }

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

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

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

  public static function answer_delete(int $user_id, int $advert_id, int $answer_id)
  {
    global $mdb;

    if ($advert_id)
    {
      if ($mdb->count('globelus_adverts', ['AND' => ['id' => $advert_id, 'user_id' => $user_id]]))
        return $mdb->update('globelus_adverts_answers', ['deleted' => 1], ['AND' => ['id' => $answer_id, 'advert_id' => $advert_id]]);
    }
    else
    {
      return $mdb->query('UPDATE '
        . 'globelus_adverts_answers AS gaa '
        . 'INNER JOIN globelus_adverts AS ga ON ga.id = gaa.advert_id '
        . 'SET '
        . 'deleted = 1 '
        . 'WHERE '
        . 'gaa.id = ' . $answer_id . ' '
        . 'AND '
        . 'ga.user_id = ' . $user_id);
    }
    return false;
  }

  public static function firm_adverts($user_id)
  {
    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 '
      . 'INNER JOIN globelus_countries AS gc ON gc.id = country_id '
      . '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 '
      . '( active_to >= \'' . date('Y-m-d') . '\' OR active_to IS NULL ) '
      . 'AND '
      . 'ga.user_id = ' . (int)$user_id . ' '
      . 'AND '
      . 'disabled_by_admin = 0 '
      . 'ORDER BY '
      . 'highlight DESC, date_add DESC ')->fetchAll(\PDO::FETCH_ASSOC);
  }

  public static function can_see_candidate($firm_id, $user_id)
  {
    global $mdb;
    $result = $mdb->query('SELECT '
      . 'COUNT(0) AS count '
      . 'FROM '
      . 'globelus_candidates_categories '
      . 'WHERE '
      . 'user_id = ' . (int)$user_id . ' '
      . 'AND '
      . 'category_id IN (SELECT category_id FROM globelus_firms_categories WHERE user_id = ' . (int)$firm_id . ') ')->fetch(\PDO::FETCH_ASSOC);
    if ($result['count'] > 0)
      return true;
    return false;
  }

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

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

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

  public static function advert_add_img_top_hash($advert_id)
  {
    return md5('files/advert_add_img_top/' . $advert_id . '/');
  }

  public static function advert_add_img_bottom_hash($advert_id)
  {
    return md5('files/advert_add_img_bottom/' . $advert_id . '/');
  }

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

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

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

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

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

  public static function logo_url($user_id)
  {
    $logo_hash = \front\factory\GlobelusFirms::logo_hash($user_id);
    return $file_name    = 'files/logos/' . $logo_hash[0] . '/' . $logo_hash[1] . '/' . $logo_hash;
  }

  public static function img_header_url($user_id)
  {
    $img_header_hash = \front\factory\GlobelusFirms::img_header_hash($user_id);
    return $file_name    = 'files/img_header/' . $img_header_hash[0] . '/' . $img_header_hash[1] . '/' . $img_header_hash;
  }

  static public function img_top_url( $user_id ) {
    $img_top_hash = \front\factory\GlobelusFirms::img_header_hash( $user_id );
    return $file_name = 'files/img_header/' . $img_top_hash[0] . '/' . $img_top_hash[1] . '/' . $img_top_hash;
  }

  public static function img_bottom_url($user_id)
  {
    $img_bottom_hash = \front\factory\GlobelusFirms::img_bottom_hash($user_id);
    return $file_name    = 'files/img_bottom/' . $img_bottom_hash[0] . '/' . $img_bottom_hash[1] . '/' . $img_bottom_hash;
  }

  public static function advert_add_img_top_url($advert_id)
  {
    $advert_add_img_top_hash = \front\factory\GlobelusFirms::advert_add_img_top_hash($advert_id);
    return $file_name    = 'files/advert_add_img_top/' . $advert_add_img_top_hash[0] . '/' . $advert_add_img_top_hash[1] . '/' . $advert_add_img_top_hash;
  }

  public static function advert_add_img_bottom_url($advert_id)
  {
    $advert_add_img_bottom_hash = \front\factory\GlobelusFirms::advert_add_img_bottom_hash($advert_id);
    return $file_name    = 'files/advert_add_img_bottom/' . $advert_add_img_bottom_hash[0] . '/' . $advert_add_img_bottom_hash[1] . '/' . $advert_add_img_bottom_hash;
  }

  public static function logo($user_id, $token)
  {
    if ($_SESSION['tokens'][$token])
    {
      $logo_hash  = \front\factory\GlobelusFirms::logo_hash($user_id);
      $extension    = \front\factory\GlobelusFirms::logo_extension($user_id);
      $file_name    = 'files/logos/' . $logo_hash[0] . '/' . $logo_hash[1] . '/' . $logo_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 img_header($user_id, $token)
  {
    if ($_SESSION['tokens'][$token])
    {
      $img_header_hash  = \front\factory\GlobelusFirms::img_header_hash($user_id);
      $extension    = \front\factory\GlobelusFirms::img_header_extension($user_id);
      $file_name    = 'files/img_header/' . $img_header_hash[0] . '/' . $img_header_hash[1] . '/' . $img_header_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 img_bottom($user_id, $token)
  {
    if ($_SESSION['tokens'][$token])
    {
      $img_bottom_hash  = \front\factory\GlobelusFirms::img_bottom_hash($user_id);
      $extension    = \front\factory\GlobelusFirms::img_bottom_extension($user_id);
      $file_name    = 'files/img_bottom/' . $img_bottom_hash[0] . '/' . $img_bottom_hash[1] . '/' . $img_bottom_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 advert_add_img_top($advert_id, $token)
  {
    if ($_SESSION['tokens'][$token])
    {
      $advert_add_img_top_hash  = \front\factory\GlobelusFirms::advert_add_img_top_hash($advert_id);
      $extension    = \front\factory\GlobelusFirms::advert_add_img_top_extension($advert_id);
      $file_name    = 'files/advert_add_img_top/' . $advert_add_img_top_hash[0] . '/' . $advert_add_img_top_hash[1] . '/' . $advert_add_img_top_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 advert_add_img_bottom($advert_id, $token)
  {
    if ($_SESSION['tokens'][$token])
    {
      $advert_add_img_bottom_hash  = \front\factory\GlobelusFirms::advert_add_img_bottom_hash($advert_id);
      $extension    = \front\factory\GlobelusFirms::advert_add_img_bottom_extension($advert_id);
      $file_name    = 'files/advert_add_img_bottom/' . $advert_add_img_bottom_hash[0] . '/' . $advert_add_img_bottom_hash[1] . '/' . $advert_add_img_bottom_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 firm_profile($user_id)
  {
    global $mdb;
    return $mdb->query('SELECT '
      . 'gu.id, firm_name_profile, nip_vat, phone, email, www, gc.name AS country, region, city, postal_code, street, apartment_number, other_information '
      . 'FROM '
      . 'globelus_users AS gu '
      . 'INNER JOIN globelus_firms_data AS gfd ON gfd.user_id = gu.id '
      . 'LEFT JOIN globelus_countries AS gc ON gc.id = gfd.country_id '
      . 'WHERE '
      . 'gu.type = 1 '
      . 'AND '
      . 'gu.status = 1 '
      . 'AND '
      . 'gu.profile_completed = 1 '
      . 'AND '
      . 'gu.id = ' . (int)$user_id)->fetch(\PDO::FETCH_ASSOC);
  }

  public static function firms_count($letter = '')
  {
    global $mdb;

    if ($letter and ctype_alpha($letter))
      $filtr = "AND LOWER(firm_name_profile) LIKE '" . $letter . "%' ";

    $result = $mdb->query('SELECT '
      . 'COUNT(gu.id) '
      . '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 '
      . 'firm_list = 1 '
      . 'AND '
      . 'gu.profile_completed = 1 '
      . $filtr)->fetch();
    return $result[0];
  }

  public static function firms_list($start = 0, $letter = '', $limit = 2)
  {
    global $mdb;

    if ($start < 1)
      $start = 0;
    else
      $start--;

    if ($letter and ctype_alpha($letter))
      $filtr = "AND LOWER(firm_name_profile) LIKE '" . $letter . "%' ";

    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 '
      . 'firm_list = 1 '
      . 'AND '
      . 'gu.profile_completed = 1 '
      . $filtr
      . 'ORDER BY '
      . 'gfd.firm_name_profile ASC '
      . 'LIMIT ' . ($start * $limit) . ',' . $limit)->fetchAll(\PDO::FETCH_ASSOC);
  }

  public static function datą_save(
    $user_id,
    $firm_name,
    $firm_name_profile,
    $nip_vat,
    $phone,
    $www,
    $country_id,
    $region,
    $city,
    $postal_code,
    $street,
    $apartment_number,
    $other_information,
    $logo_file,
    $contact_person_1,
    $email_1,
    $phone_1,
    $contact_person_2,
    $email_2,
    $phone_2,
    $clauses,
    $img_header,
    $img_bottom
  )
  {
    global $mdb, $lang;

    $clauses = \front\factory\Globelus::clean_text($clauses);

    if ($data_id = $mdb->get('globelus_firms_data', 'id', ['user_id' => $user_id]))
      $mdb->update('globelus_firms_data', [
        'firm_name'             => $firm_name,
        'firm_name_profile'     => $firm_name_profile,
        'nip_vat'               => $nip_vat,
        'phone'                 => $phone,
        'www'                   => $www,
        'country_id'            => $country_id,
        'region'                => $region,
        'city'                  => $city,
        'postal_code'           => $postal_code,
        'street'                => $street,
        'apartment_number'      => $apartment_number,
        'other_information'     => $other_information,
        'contact_person_1' => $contact_person_1,
        'email_1' => $email_1,
        'phone_1' => $phone_1,
        'contact_person_2' => $contact_person_2,
        'email_2' => $email_2,
        'phone_2' => $phone_2,
        'clauses' => $clauses,
        'img_header_extension' => $img_header,
        'img_bottom_extension' => $img_bottom,
      ], [
        'id'                    => $data_id
      ]);
    else
      $mdb->insert('globelus_firms_data', [
        'user_id'               => $user_id,
        'firm_name'             => $firm_name,
        'firm_name_profile'     => $firm_name_profile,
        'nip_vat'               => $nip_vat,
        'phone'                 => $phone,
        'www'                   => $www,
        'country_id'            => $country_id,
        'region'                => $region,
        'city'                  => $city,
        'postal_code'           => $postal_code,
        'street'                => $street,
        'apartment_number'      => $apartment_number,
        'other_information'     => $other_information,
        'contact_person_1' => $contact_person_1,
        'email_1' => $email_1,
        'phone_1' => $phone_1,
        'contact_person_2' => $contact_person_2,
        'email_2' => $email_2,
        'phone_2' => $phone_2,
        'clauses' => $clauses,
        'img_header_extension' => $img_header,
        'img_bottom_extension' => $img_bottom,
      ]);

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

    $logo_error = false;

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

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

    if ($logo_file['tmp_name'] and !$logo_error)
    {
      $logo_hash  = \front\factory\GlobelusFirms::logo_hash($user_id);
      $dir        = 'files/logos/' . $logo_hash[0] . '/' . $logo_hash[1] . '/';

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

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

      move_uploaded_file($logo_file['tmp_name'], $dir . $logo_hash);

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

    /* zdjęcie górne ogłoszenia */
    $allowed_mime_types_img_header = \front\factory\Globelus::img_header_allowed_mime_types();

    $img_header_error = false;

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

    if ($img_header['tmp_name'] and !$img_header_error and !in_array($img_header["type"], $allowed_mime_types_img_header))
    {
      \S::set_alert_prompt('Informacja', $lang['logo-niedozwolony-format-pliku']);
      return false;
    }

    if ($img_header['tmp_name'] and !$img_header_error)
    {
      $img_header_hash  = \front\factory\GlobelusFirms::img_header_hash($user_id);
      $dir = 'files/img_header/' . $img_header_hash[0] . '/' . $img_header_hash[1] . '/';

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

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

      move_uploaded_file($img_header['tmp_name'], $dir . $img_header_hash);

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

    // /*zdjęcie dolne ogłoszenia */
    $allowed_mime_types_img_bottom = \front\factory\Globelus::img_bottom_allowed_mime_types();

    $img_bottom_error = false;

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

    if ($img_bottom['tmp_name'] and !$img_bottom_error and !in_array($img_bottom["type"], $allowed_mime_types_img_bottom))
    {
      \S::set_alert_prompt('Informacja', $lang['logo-niedozwolony-format-pliku']);
      return false;
    }

    if ($img_bottom['tmp_name'] and !$img_bottom_error)
    {
      $img_bottom_hash  = \front\factory\GlobelusFirms::img_bottom_hash($user_id);
      $dir        = 'files/img_bottom/' . $img_bottom_hash[0] . '/' . $img_bottom_hash[1] . '/';

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

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

      move_uploaded_file($img_bottom['tmp_name'], $dir . $img_bottom_hash);

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


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

    return true;
  }

  public static function candidate_remove_from_favorite($candidate_id, $user_id)
  {
    global $mdb;
    return $mdb->delete('globelus_firms_candidates', [
      'AND' => [
        'candidate_id'  => $candidate_id,
        'user_id'       => $user_id
      ]
    ]);
  }

  public static function candidate_add_to_favorite($candidate_id, $user_id)
  {
    global $mdb;
    return $mdb->insert('globelus_firms_candidates', [
      'candidate_id'  => $candidate_id,
      'user_id'       => $user_id
    ]);
  }

  public static function advert_refresh( $advert_id, $user_id )
  {
    global $mdb, $globelus_settings;

    $advert = \front\factory\GlobelusAdverts::advert_details( $advert_id );

    if ( $advert['disabled_by_admin'] )
      return [
        'result' => false,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title( $advert_id ) . '<\/b> zostało zablokowane przez administratora.</p>'
      ];

    if ( !$advert['visible'] )
      return [
        'result' => false,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title( $advert_id ) . '<\/b> nie jest widoczne.</p>'
      ];

    $points = \front\factory\GlobelusFirms::get_firm_points( $user_id );

    if ( $points < $globelus_settings['pkt-odswiezenie-ogloszenia'] )
    {
      return [
        'result' => false,
        'msg' => '<p>Nie masz wystarczającej ilości punktów, aby odświeżyć ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title( $advert_id ) . '<\/b>.</p>'
      ];
    }


    $last_refresh = \front\factory\GlobelusAdverts::last_refresh( $advert_id );
    $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 < 1 )
    {
      return [
        'result' => false,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title( $advert_id ) . '<\/b> może być odświeżone raz na dobę.</p>'
      ];
    }

    $mdb -> update( 'globelus_users', [ 'points[-]' => $globelus_settings['pkt-odswiezenie-ogloszenia'] ], [ 'id' => $user_id] );
    $mdb -> insert( 'globelus_points_history', [
      'user_id' => $user_id,
      'points' => $globelus_settings['pkt-odswiezenie-ogloszenia'],
      'event_type' => 3
    ] );

    if ( $mdb -> update( 'globelus_adverts', [ 'last_refresh' => date('Y-m-d H:i:s'), 'refresh_count[+]' => 1 ], [ 'AND' => [ 'id' => $advert_id, 'user_id' => $user_id ] ] ) )
    {
      \S::log($user_id, __METHOD__, [0 => ['points' => $points, 'advert_id' => $advert_id, 'refresh_diff' => $refresh_diff]]);
      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> zostało odświeżone.</p>'
      ];
    }
  }

  public static function advert_extend($advert_id, $user_id)
  {
    global $mdb;

    $active_to    = \front\factory\GlobelusAdverts::active_to($advert_id);
    $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 <= 3)
    {
      $mdb->update('globelus_adverts', [
        'active_to'       => date('Y-m-d', strtotime('+30 days', strtotime($active_to))),
        'last_refresh'    => date('Y-m-d H:i:s'),
        'mail_expiration' => 0,
        'mail_expired'    => 0
      ], [
        'AND' => [
          'user_id' => $user_id,
          'id'      => $advert_id
        ]
      ]);
      return true;
    }
    return false;
  }

  public static function followed_candidates($user_id)
  {
    global $mdb;
    return $mdb->query('SELECT '
      . 'gu.id, gcd.name, gcd.surname, gcd.sex, gcd.date_of_birth, gu.email, gcd.phone '
      . 'FROM '
      . 'globelus_users AS gu '
      . 'INNER JOIN globelus_firms_candidates AS gfc ON gfc.candidate_id = gu.id '
      . 'INNER JOIN globelus_candidates_data AS gcd ON gcd.user_id = gu.id '
      . 'WHERE '
      . 'gfc.user_id = ' . (int)$user_id . ' '
      . 'AND '
      . 'gu.status = 1 '
      . 'AND '
      . 'gu.visible = 1')->fetchAll(\PDO::FETCH_ASSOC);
  }

  public static function advert_additional_promotion($user_id, $advert_id)
  {
    global $mdb, $settings, $lang, $globelus_settings;

    $user_id = (int)$user_id;
    $advert_id = (int)$advert_id;

    if (!$mdb->count('globelus_adverts', ['AND' => ['id' => $advert_id, 'user_id' => $user_id]]))
      return false;

    $points = \front\factory\GlobelusFirms::get_firm_points($user_id);

    if ($points >= $globelus_settings['pkt-dodatkowa-promocja-ogloszenia'] and !$mdb->get('globelus_adverts', 'additional_promotion', ['id' => $advert_id]))
    {
      $mdb->update('globelus_adverts', ['additional_promotion' => 1], ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      $mdb->update('globelus_users', ['points[-]' => $globelus_settings['pkt-dodatkowa-promocja-ogloszenia']], ['id' => $user_id]);
      $mdb->insert('globelus_points_history', [
        'user_id' => $user_id,
        'points' => $globelus_settings['pkt-dodatkowa-promocja-ogloszenia'],
        'event_type' => 6
      ]);

      return [
        'result' => true
      ];
    }
    else
    {
      if ($points < $globelus_settings['pkt-dodatkowa-promocja-ogloszenia'])
        return [
          'result' => false
        ];
    }

    return [
      'result' => false
    ];
  }

  public static function advert_main_page_enable($user_id, $advert_id, $user_email = '')
  {
    global $mdb, $settings, $lang, $globelus_settings;

    $user_id = (int)$user_id;
    $advert_id = (int)$advert_id;

    if (!$mdb->count('globelus_adverts', ['AND' => ['id' => $advert_id, 'user_id' => $user_id]]))
      return false;

    $points = \front\factory\GlobelusFirms::get_firm_points($user_id);

    if ($points >= $globelus_settings['pkt-polecanie-ogloszenia'] and !$mdb->get('globelus_adverts', 'main_page', ['id' => $advert_id]))
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template('#ogloszenie-jest-polecane');

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

      //$send = \S::send_email( $user_email, str_replace( '[TYTUL]', $title, $lang['mail-ogloszenie-jest-polecane'] ), $text );

      $mdb->update('globelus_adverts', ['main_page' => 1, 'main_page_to' => date('Y-m-d', strtotime('+10 days', time()))], ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      $mdb->update('globelus_users', ['points[-]' => $globelus_settings['pkt-polecanie-ogloszenia']], ['id' => $user_id]);
      $mdb->insert('globelus_points_history', [
        'user_id' => $user_id,
        'points' => $globelus_settings['pkt-polecanie-ogloszenia'],
        'event_type' => 2
      ]);

      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> jest polecane na stronie glównej.</p>'
      ];
    }
    else
    {
      if ($points < $globelus_settings['pkt-polecanie-ogloszenia'])
        return [
          'result' => false,
          'msg' => '<p>Nie możesz polecić ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> z powodu <b>zbyt małej ilości punktów<\/b>.</p>'
        ];

      return [
        'result' => false,
        'msg' => '<p>Nie możesz plecić ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b>.</p>'
      ];
    }

    return [
      'result' => false
    ];
  }

  public static function advert_highlight_enable($user_id, $advert_id, $user_email = '')
  {
    global $mdb, $settings, $lang, $globelus_settings;

    $points = \front\factory\GlobelusFirms::get_firm_points($user_id);

    if ($points >= $globelus_settings['pkt-wyroznienie-ogloszenia'] and !$mdb->get('globelus_adverts', 'highlight', ['id' => $advert_id]))
    {
      $text = $settings['newsletter_header'];
      $text .= \front\factory\Newsletter::get_template('#ogloszenie-zostalo-wyroznione');

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

      //$send = \S::send_email( $user_email, str_replace( '[TYTUL]', $title, $lang['mail-ogloszenie-zostalo-wyroznione'] ), $text );

      $mdb->update('globelus_adverts', ['highlight' => 1, 'highlight_to' => date('Y-m-d', strtotime('+10 days', time()))], ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      $mdb->update('globelus_users', ['points[-]' => $globelus_settings['pkt-wyroznienie-ogloszenia']], ['id' => $user_id]);
      $mdb->insert('globelus_points_history', [
        'user_id' => $user_id,
        'points' => $globelus_settings['pkt-wyroznienie-ogloszenia'],
        'event_type' => 1
      ]);

      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> zostało wyróżnione.</p>'
      ];
    }
    else
    {
      if ($points < $globelus_settings['pkt-wyroznienie-ogloszenia'])
        return [
          'result' => false,
          'msg' => '<p>Nie możesz wyróżnić ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> z powodu <b>zbyt małej ilości punktów<\/b>.</p>'
        ];

      return [
        'result' => false,
        'msg' => '<p>Nie możesz wyróżnić ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b>.</p>'
      ];
    }

    return [
      'result' => false
    ];
  }

  public static function advert_disable($user_id, $advert_id)
  {
    global $mdb;

    if ($mdb->update('globelus_adverts', [
      'visible' => 0,
      'highlight' => 0,
      'highlight_to' => null,
      'main_page' => 0,
      'main_page_to' => null,
      'additional_promotion' => 0
    ], [
      'AND' => [
        'user_id' => $user_id,
        'id' => $advert_id
      ]
    ]))
      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> zostało wyłączone.</p>'
      ];

    return [
      'result' => false
    ];
  }

  public static function advert_enable($user_id, $advert_id, $email = '')
  {
    global $mdb, $lang, $settings, $globelus_settings;

    // if ($mdb->get('globelus_adverts', 'old', ['id' => $advert_id]))
    //   return [
    //     'result' => false,
    //     'msg' => '<p>Nie możesz opublikować ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> ponieważ <b>ma ono ponad 90 dni<\/b>.</p>'
    //   ];

    if (\front\factory\GlobelusFirms::adverts_count($user_id) > $globelus_settings['limit-ogloszen'] and \front\factory\GlobelusFirms::get_firm_points($user_id) < $globelus_settings['pkt-dodanie-ogloszenia-powyzej-limitu'])
      return false;

    if (!$mdb->get('globelus_adverts', 'visible_mail', ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]) and $email)
    {
      $title      = $mdb->get('globelus_adverts', 'title', ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      $highlight  = $mdb->get('globelus_adverts', 'highlight', ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      $main_page  = $mdb->get('globelus_adverts', 'main_page', ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);

      if ( $globelus_settings['maile-wysylanie'] )
      {
        $text = $settings['newsletter_header'];
        $text .= \front\factory\Newsletter::get_template('#potwierdzenie-dodania-ogloszenia');

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

        //        $send = \S::send_email( $email, str_replace( '[TYTUL]', $title, $lang['mail-ogloszenie-jest-juz-widoczne'] ), $text );

        $mdb->update('globelus_adverts', ['visible_mail' => 1], ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]);
      }
    }

    if ($mdb->get('globelus_adverts', 'visible', ['id' => $advert_id]))
      return [
        'result' => false,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> jest już widoczne.</p>'
      ];

    if ( $mdb -> update('globelus_adverts', ['visible' => 1, 'mail_expired' => 0 ], ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]))
    {
      if ( \front\factory\GlobelusFirms::adverts_count($user_id) > $globelus_settings['limit-ogloszen'] and \front\factory\GlobelusFirms::get_firm_points($user_id) >= $globelus_settings['pkt-dodanie-ogloszenia-powyzej-limitu'] )
      {
        $mdb->update('globelus_users', ['points[-]' => $globelus_settings['pkt-dodanie-ogloszenia-powyzej-limitu']], ['id' => $user_id]);
        $mdb->insert('globelus_points_history', [
          'user_id' => $user_id,
          'points' => $globelus_settings['pkt-dodanie-ogloszenia-powyzej-limitu'],
          'event_type' => 4
        ]);
      }

      if ( $mdb -> get( 'globelus_adverts', 'old', [ 'id' => $advert_id ] ) )
      {
        $mdb->update('globelus_adverts', [ 'old' => 0, 'active_to' => date( 'Y-m-d', strtotime('+' . $globelus_settings['ogloszenie-ilosc-dni-waznosci'] . ' days', time())), 'date_add' => date( 'Y-m-d H:i:s' ), 'last_refresh' => date( 'Y-m-d H:i:s' ) ], [ 'id' => $advert_id ]);
      }

      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b> zostało opublikowane.</p>'
      ];
    }

    return [
      'result' => false,
      'msg' => '<p>Nie możesz opublikować ogłoszenia <b>' . \front\factory\GlobelusAdverts::advert_title($advert_id) . '<\/b>.</p>'
    ];
  }

  public static function advert_delete($user_id, $advert_id)
  {
    global $mdb;

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

    $title = \front\factory\GlobelusAdverts::advert_title($advert_id);

    if ($mdb->delete('globelus_adverts', ['AND' => ['user_id' => $user_id, 'id' => $advert_id]]))
      return [
        'result' => true,
        'msg' => '<p>Ogłoszenie <b>' . $title . '<\/b> zostało usunięte.</p>'
      ];

    return [
      'result' => false
    ];
  }

  static public function advert_save($values, $id_voivodeship, $aplication_link, $advert_add_img_bottom, $advert_add_img_top, $id_position = null )
  {
    global $mdb, $globelus_settings, $lang;

    $values['text'] = \front\factory\Globelus::clean_text($values['text']);
    $g_user = \S::get_session('g_user');

    if (!$values['advert_id'])
    {
      $user_adverts_count = \front\factory\GlobelusFirms::user_adverts_count($g_user['id']);

      $mdb->insert('globelus_adverts', [
        'user_id'             => $values['user_id'],
        'title'               => $values['title'],
        'category_id'         => $values['category'],
        'country_id'          => $values['country'],
        'id_voivodeship' => ($values['country'] == 1 and $id_voivodeship) ? $id_voivodeship : null,
        'id_position' => $id_position ? $id_position : null,
        'city'                => $values['city'],
        'region'              => $values['region'],
        'text' => \S::clear_advert_text( $values['text'] ),
        'contact_person'      => $values['contact_person'],
        'email'               => $values['email'],
        'phone'               => $values['phone'],
        'highlight'           => 0,
        'main_page'           => 0,
        'active_to'           => $globelus_settings['ogloszenie-ilosc-dni-waznosci'] ? date('Y-m-d', strtotime('+' . $globelus_settings['ogloszenie-ilosc-dni-waznosci'] . ' days', time())) : date('Y-m-d', strtotime('+180 days', time())),
        'salary'              => trim(strip_tags($values['salary'])) ? trim(strip_tags($values['salary'])) : null,
        'work_type'           => $values['work_type'],
        'without_language'    => $values['without_language'],
        'without_experience'  => $values['without_experience'],
        'for_couples'         => $values['for_couples'],
        'from_now' => 0,
        'accommodation' => $values['accommodation'],
        'accommodation_cost' => $values['accommodation_cost'],
        'overtime' => $values['overtime'],
        'overtime_quantity' => $values['overtime_quantity'],
        'travel_refund' => $values['travel_refund'],
        'outside_ue' => $values['outside_ue'],
        'without_driving_license' => $values['without_driving_license'],
        'aplication_link' => $aplication_link ? $aplication_link : null
      ]);
      $advert_id = $mdb->id();
    }
    else
    {
      if ($values['user_id'] != $mdb->get('globelus_adverts', 'user_id', ['id' => $values['advert_id']]))
        return false;

      $mdb->update('globelus_adverts', [
        'title'               => $values['title'],
        'category_id'         => $values['category'],
        'country_id'          => $values['country'],
        'id_voivodeship' => ($values['country'] == 1 and $id_voivodeship) ? $id_voivodeship : null,
        'id_position' => $id_position ? $id_position : null,
        'city'                => $values['city'],
        'region'              => $values['region'],
        'text' => \S::clear_advert_text( $values['text'] ),
        'contact_person'      => $values['contact_person'],
        'email'               => $values['email'],
        'phone'               => $values['phone'],
        'salary'              => trim(strip_tags($values['salary'])) ? trim(strip_tags($values['salary'])) : null,
        'work_type'           => $values['work_type'],
        'without_language'    => $values['without_language'],
        'without_experience'  => $values['without_experience'],
        'for_couples'         => $values['for_couples'],
        'from_now' => 0,
        'accommodation' => $values['accommodation'],
        'accommodation_cost' => $values['accommodation_cost'],
        'overtime' => $values['overtime'],
        'overtime_quantity' => $values['overtime_quantity'],
        'travel_refund' => $values['travel_refund'],
        'outside_ue' => $values['outside_ue'],
        'without_driving_license' => $values['without_driving_license'],
        'aplication_link' => $aplication_link ? $aplication_link : null
      ], [
        'AND' => [
          'user_id' => $values['user_id'],
          'id'      => $values['advert_id']
        ]
      ]);

      if ( $mdb ->get('globelus_adverts', 'old', ['AND' => ['id' => $values['advert_id'], 'user_id' => $values['user_id']]]))
      {
        $mdb->update('globelus_adverts', [
          'old' => 0,
          'highlight' => 0,
          'highlight_to' => null,
          'main_page' => 0,
          'main_page_to' => null,
          'last_refresh' => null,
          'refresh_count' => 0,
          'mail_expiration' => null,
          'mail_expired' => null,
          'active_to' => $globelus_settings['ogloszenie-ilosc-dni-waznosci'] ? date('Y-m-d', strtotime('+' . $globelus_settings['ogloszenie-ilosc-dni-waznosci'] . ' days', time())) : date('Y-m-d', strtotime('+180 days', time())),
          'date_add' => date('Y-m-d H:i:s'),
          'visits' => 0
        ], [
          'AND' => [
            'user_id' => $values['user_id'],
            'id'      => $values['advert_id']
          ]
        ]);
      }

      \S::log($g_user['id'], __METHOD__, func_get_args());

      $advert_id = $values['advert_id'];
    }

    /* zdjęcie górne ogloszenia edycja ogloszenia */
    $allowed_mime_types_advert_top = \front\factory\Globelus::advert_add_img_top_allowed_mime_types();

    $advert_add_img_top_error = false;

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

    if ($advert_add_img_top['tmp_name'] and !$advert_add_img_top_error and !in_array($advert_add_img_top["type"], $allowed_mime_types_advert_top))
    {
      \S::set_alert_prompt('Informacja', $lang['logo-niedozwolony-format-pliku']);
      return false;
    }

    if ($advert_add_img_top['tmp_name'] and !$advert_add_img_top_error)
    {
      $advert_add_img_top_hash  = \front\factory\GlobelusFirms::advert_add_img_top_hash($advert_id);
      $dir = 'files/advert_add_img_top/' . $advert_add_img_top_hash[0] . '/' . $advert_add_img_top_hash[1] . '/';

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

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

      move_uploaded_file($advert_add_img_top['tmp_name'], $dir . $advert_add_img_top_hash);

      $mdb->update('globelus_adverts', ['advert_add_img_top' => $file_ext], ['id' => $advert_id]);
    }

    /* zdjęcie dolne ogloszenia edycja ogloszenia */
    $allowed_mime_types_advert_bottom = \front\factory\Globelus::advert_add_img_bottom_allowed_mime_types();

    $advert_add_img_bottom_error = false;

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

    if ($advert_add_img_bottom['tmp_name'] and !$advert_add_img_bottom_error and !in_array($advert_add_img_bottom["type"], $allowed_mime_types_advert_bottom))
    {
      \S::set_alert_prompt('Informacja', $lang['logo-niedozwolony-format-pliku']);
      return false;
    }

    if ($advert_add_img_bottom['tmp_name'] and !$advert_add_img_bottom_error)
    {
      $advert_add_img_bottom_hash  = \front\factory\GlobelusFirms::advert_add_img_bottom_hash($advert_id);
      $dir = 'files/advert_add_img_bottom/' . $advert_add_img_bottom_hash[0] . '/' . $advert_add_img_bottom_hash[1] . '/';

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

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

      move_uploaded_file($advert_add_img_bottom['tmp_name'], $dir . $advert_add_img_bottom_hash);

      $mdb->update('globelus_adverts', ['advert_add_img_bottom' => $file_ext], ['id' => $advert_id]);
    }

    if ( $advert_id )
      return true;

    return false;
  }

  public static function answer_mark_as_displayed($answer_id)
  {
    global $mdb;
    return $mdb->update('globelus_adverts_answers', ['displayed' => 1], ['id' => $answer_id]);
  }

  public static function answers(int $user_id)
  {
    global $mdb;
    return $mdb->query('SELECT '
      . 'gaa.id, gaa.name, gaa.surname, gaa.email, gaa.phone, gaa.text, gaa.cv, gaa.cv_extension, gaa.displayed, gaa.date_add, gaa.user_id, ga.title '
      . 'FROM '
      . 'globelus_adverts_answers AS gaa '
      . 'INNER JOIN globelus_adverts AS ga ON ga.id = gaa.advert_id '
      . 'WHERE '
      . 'ga.user_id = ' . $user_id . ' AND gaa.deleted = 0 '
      . 'ORDER BY '
      . 'gaa.date_add DESC, gaa.id DESC')->fetchAll();
  }

  public static function advert_answers($advert_id)
  {
    global $mdb;
    return $mdb->query('SELECT '
      . 'id, name, surname, email, phone, text, cv, cv_extension, displayed, date_add, user_id '
      . 'FROM '
      . 'globelus_adverts_answers AS gaa '
      . 'WHERE '
      . 'advert_id = ' . (int)$advert_id . ' AND deleted = 0 '
      . 'ORDER BY '
      . 'date_add DESC, id DESC')->fetchAll();
  }

  public static function adverts_list($user_id)
  {
    global $mdb;
    return $mdb->query('SELECT '
      . 'ga.id, title, visible, date_add, visits, active_to, highlight, main_page, last_refresh, refresh_count, '
      . '( SELECT COUNT(0) FROM globelus_adverts_answers WHERE advert_id = ga.id ) AS answers, '
      . '( SELECT COUNT(0) FROM globelus_adverts_answers WHERE advert_id = ga.id AND displayed = 0 ) AS answers_nondisplayed '
      . 'FROM '
      . 'globelus_adverts AS ga '
      . 'LEFT JOIN globelus_adverts_categories AS gac ON gac.id = category_id '
      . 'WHERE '
      . 'user_id = ' . (int)$user_id . ' '
      . 'ORDER BY '
      . 'date_add DESC')->fetchAll(\PDO::FETCH_ASSOC);
  }
}
