<?php

namespace auctionforge\inc\model;

use stdClass;
use auctionforge\inc\abs\Importer;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\controllers\MultiLanguageSupport;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\InstanceDB;
use WP_Post;
use WP_Query;

class Lot extends LotModel
{
    const VIEW_HOMEPAGE = 'lot_view_homepage';
    const VALUE_NUM = 'meta_value_num ID';
    const NAME_PARAM = 'sort_by';
    const NAME_PARAM_CATEGORY = 'category_by';
    const NAME_PARAM_PHRASE = 'phrase_by';
    const NAME_PARAM_PER_PAGE = 'per_page';
    const NAME_PARAM_IS_SOLD = 'is_sold';

    const VIEW_HOMEPAGE_BS = 'featured';
    const VALUE_NUM_BS = 'paddedIndex';

    public static $orderField = array('lot_paddedIndex', 'lot_itemIndex');
    public static $approvedFields = array('lot_lotIndex', 'lot_start_price', 'lot_estimated_price_int', 'lot_leadingBid', 'lot_soldBid');

    public static $orderFieldBS = array('paddedIndex', 'itemIndex');
    public static $approvedFieldsBS = array('lotIndex', 'start_price', 'startPrice', 'estimated_price_int', 'estimatedPriceInt', 'leadingBid', 'soldBid', 'effectivePrice', 'mostActive', 'buyoutPrice', 'id');

    public function loadAttributes($model)
    {
        parent::loadAttributes($model);

        $this->buildParams($model);
    }

    protected function buildParams($model)
    {
        $isRawData = false;
        if (!empty($model->params)) {
            $rawData = (array)json_decode($model->params);
            $isRawData = (!empty($rawData));
        }
        $params = new \stdClass();
        if (!$isRawData) {
            $fields = array(
                "condition",
                "conditionReport",
                "width",
                "height",
                "widthWithFrame",
                "heightWithFrame",
                "lengthUnit",
                "weightUnit",
                "weight",
                "depth",
            );
            foreach ($fields as $field) {
                if (isset($model->{$field})) {
                    $params->{$field} = addslashes($model->{$field});
                }
            }

            if (!empty($model->carInfo)) {
                $params->carInfo = addslashes(json_encode($model->carInfo));
            }

            if (!empty($model->realEstateInfo)) {
                $params->realEstateInfo = addslashes(json_encode($model->realEstateInfo));
            }

            if (!empty($model->artDocuments)) {
                $params->artDocuments = json_encode($model->artDocuments);
            }

            $raw = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT);
        } else {
            $raw = $model->params;
        }
        $this->setParams($raw);
    }

    public static function getLotsBySearch($phrase, $taxonomy, $params = array())
    {
        $args = array(
            'numberposts' => -1,
            'post_type' => BidspiritLots::POST_TYPE,
            'hide_empty' => 0,
            'taxonomy' => BidspiritLots::TAX_AUCTION_TYPE,
            's' => $phrase,
            'exact' => false,
            'sentence' => true,
            'compare' => 'LIKE',
            'meta_query' => array(
                array(
                    'key' => 'lot_name',
                    'value' => $phrase,
                    'compare' => 'LIKE'
                )
            ),
            'tax_query' => array(
                array(
                    'taxonomy' => BidspiritLots::TAX_AUCTION_TYPE,
                    'field' => 'id',
                    'terms' => array($taxonomy),
                    'operator'  => 'IN'
                )
            ),
//            'meta_key' => 'lot_itemIndex',
            'orderby' => self::VALUE_NUM,
            'suppress_filters' => false,
            'order' => 'ASC',
        );

        $orderByFields = BidspiritLots::sort_order($params);

        $args2['meta_key'] = BidspiritLots::sort_meta_key($params);
        $args2['orderby'] = $orderByFields['orderBy'];
        $args2['order'] = $orderByFields['order'];

        $args = wp_parse_args($args2, $args);

        return get_posts($args);
    }

    public function save()
    {
        $db = InstanceDB::getInstanceDB();

        $flag = apply_filters('auctionforge_before_save_history_customize', false);
        $data = apply_filters('auctionforge_before_save_history_data', $this->buildFields(), $this, $flag);
        $masksData = apply_filters('auctionforge_before_save_history_masks', $this->getMasksForFields(), $flag);

        return $db->insert(self::getTableName($db), $data, $masksData);
    }

    public static function getRawLots($limit)
    {
        $excludeAuction = array();

        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT * FROM " . self::getTableName($db) . " WHERE `syncStart` != " . self::DIGIT_MASK . " AND `syncFinished` != " .
            self::DIGIT_MASK . " AND `syncTimes` < " . self::DIGIT_MASK . " ";

        if (!empty($excludeAuction)) {
            $excludeAuction = array_diff($excludeAuction, array(''));
            $sql .= " AND `auctionSlug` NOT IN ('" . implode('\',\'', $excludeAuction) . "') ";
        }
        $sql .= " ORDER BY `priority`, `id`";
        $sql .= " LIMIT " . $limit * 10 . ";";
        $sql = $db->prepare($sql, array(1, 1, TRY_LOT_LIMIT));

        $rows = $db->get_results($sql);
        if (!empty($rows)) {
            $data = [];
            foreach ($rows as $row) {
                $data[$row->lotId] = $row;
            }

            return $data;
        } else {
            return [];
        }
    }

    public static function getTableName($db)
    {
        return $db->prefix . Importer::TABLE_NAME;
    }

    public function buildFields()
    {
        return array(
            'lotId' => $this->getId(),
            'auctionSlug' => $this->getAuctionId(),
            'lang' => $this->getLang(),
            'paddedIndex' => $this->getPaddedIndex(),
            'itemIndex' => $this->getItemIndex(),
            'name' => $this->getName(),
            'nameL2' => $this->getNameL2(),
            'description' => $this->getDescription(),
            'descriptionL2' => $this->getDescriptionL2(),
            'author' => $this->getAuthor(),
            'authorL2' => $this->getAuthorL2(),
            'mlFields' => $this->getMlFields(),
            'details' => $this->getDetails(),
            'startPrice' => $this->getStartPrice(),
            'leadingBid' => $this->getLeadingBid(),
            'soldBid' => $this->getSoldBid(),
            'auctionId' => $this->getAuctionId(),
            'imagesListStr' => $this->getImagesListStr(),
            'categoryId' => $this->getCategoryId(),
            'estimatedPrice' => $this->getEstimatedPrice(),
            'tags' => $this->getTags(),
            'videoUrl' => $this->getVideoUrl(),
            'extraInfo' => $this->getExtraInfo(),
            'params' => $this->getParams(),
            'postSaleDisabled' => $this->getPostSaleDisabled(),
            'imagesBase' => $this->getImagesBase(),
            'imagesCloned' => $this->getImagesCloned(),
            'buyoutPrice' => $this->getBuyoutPrice(),
            'lastUpdate' => $this->getLastUpdate(),
            'fullPriceVat' => $this->getFullPriceVat(),
            'largeDisplay' => $this->getLargeDisplay(),
            'viewOnly' => $this->getViewOnly(),
            'hidden' => $this->getHidden(),
            'hiddenInPortal' => $this->getHiddenInPortal(),
            'removedFromAuction' => $this->getRemovedFromAuction(),
            'eroticContent' => $this->getEroticContent(),
            'criminalContent' => $this->getCriminalContent(),
            'priority' => $this->getPriority(),
            'isGem' => $this->getIsGem(),
            'syncStart' => 0,
            'syncFinished' => 0,
            'createDatetime' => $this->getCreateDatetime(),
            'syncDatetime' => $this->getSyncDatetime(),
            'syncErrors' => $this->getSyncErrors(),
            'syncTimes' => 0
        );
    }

    private function getMasksForFields()
    {
        return array(
            self::DIGIT_MASK,//lotId
            self::STRING_MASK,//auctionSlug
            self::STRING_MASK,//lang
            self::STRING_MASK,//paddedIndex
            self::STRING_MASK,//itemIndex
            self::STRING_MASK,//name
            self::STRING_MASK,//name_l2
            self::STRING_MASK,//description
            self::STRING_MASK,//description_l2
            self::STRING_MASK,//author
            self::STRING_MASK,//author_l2
            self::STRING_MASK,//ml_fields
            self::STRING_MASK,//details
            self::DIGIT_MASK,//startPrice
            self::DIGIT_MASK,//leadingBid
            self::DIGIT_MASK,//soldBid
            self::DIGIT_MASK,//auctionId
            self::STRING_MASK,//imagesListStr
            self::DIGIT_MASK,//categoryId
            self::STRING_MASK,//estimatedPrice
            self::STRING_MASK,//tags
            self::STRING_MASK,//videoUrl
            self::STRING_MASK,//extraInfo
            self::STRING_MASK,//params
            self::DIGIT_MASK,//postSaleDisabled
            self::STRING_MASK,//imagesBase
            self::DIGIT_MASK,//imagesCloned
            self::DIGIT_MASK,//buyoutPrice
            self::DIGIT_MASK,//lastUpdate
            self::DIGIT_MASK,//fullPriceVat
            self::DIGIT_MASK,//largeDisplay
            self::DIGIT_MASK,//viewOnly
            self::DIGIT_MASK,//hidden
            self::DIGIT_MASK,//hiddenInPortal
            self::DIGIT_MASK,//removedFromAuction
            self::DIGIT_MASK,//eroticContent
            self::DIGIT_MASK,//criminalContent
            self::DIGIT_MASK,//priority
            self::DIGIT_MASK,//isGem
            self::DIGIT_MASK,//syncStart
            self::DIGIT_MASK,//syncFinished
            self::STRING_MASK,//createDatetime
            self::STRING_MASK,//syncDatetime
            self::STRING_MASK,//syncErrors
            self::DIGIT_MASK,//syncTimes
        );
    }
    
    /**
     * Search for a record in the database by id bidsirit
     * @param Lot $lot
     * @return stdClass
     */
    public static function findLot(Lot $lot)
    {
        $args = array(
            'numberposts' => 1,
            'post_type' => BidspiritLots::POST_TYPE,
            'taxonomy' => BidspiritLots::TAX_AUCTION_TYPE,
            'lang' => '',
            'orderby' => 'ID',
            'order' => 'ASC',
        );

        $args = array_merge($args, array(
            LotMetaData::BP_QUERY => array(
                "bp_id" => [
                    "value" => $lot->getLotId(),
                    "compare" => "="
                ],
            ),
        ));

        $posts = get_posts($args);

        if (!empty($posts) && is_array($posts)) {
            return (object)array(
                'post_id' => $posts[0]->ID,
                'meta_key' => 'lot_id',
                'meta_value' => $lot->getLotId()
            );
        }
        return null;
    }

    public static function findDataLots($ids, $limit = 0)
    {
        return self::findByBSMeta($ids, $limit);
    }

    private static function findByPostParent($ids, $limit = 0)
    {
        $mlSupport = new MultiLanguageSupport();

        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT " . $db->prefix . "posts.ID, UNIX_TIMESTAMP(
            CONVERT_TZ(" . $db->prefix . "posts.post_date, '+00:00', @@global.time_zone)
            ) AS lastUpdate, " . $db->prefix . "posts.post_parent AS lotId";
        $sql .= " FROM " . $db->prefix . "posts";

        if ($mlSupport->isLotSupport()) {
            $sql .= " LEFT JOIN " . $db->prefix . "term_relationships AS tt0 ON (" . $db->prefix . "posts.ID = tt0.object_id)";
        }

        $sql .= " WHERE (1 = 1";

        if ($mlSupport->isLotSupport()) {
            $termId = pll_default_language('term_id');
            $sql .= " AND tt0.term_taxonomy_id IN(" . $termId . ")";
        }

        $sql .= " AND " . $db->prefix . "posts.post_parent IN (" . implode(",", $ids) . "))
              AND " . $db->prefix . "posts.post_type = 'lot'
              AND ((" . $db->prefix . "posts.post_status IN ('publish', 'draft')))
            GROUP BY lotId
            ORDER BY lotId DESC
            LIMIT 0, " . $limit * 10 . ";";

        return $db->get_results($sql);
    }

    private static function findByBSMeta($ids, $limit = 0)
    {
        $mlSupport = new MultiLanguageSupport();

        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT posts.ID, UNIX_TIMESTAMP(
            CONVERT_TZ(posts.post_date, '+00:00', @@global.time_zone)
            ) AS lastUpdate, `meta`.`id` AS lotId";
        $sql .= " FROM " . $db->prefix . "posts AS posts
            INNER JOIN " . LotMetaData::getTableName() . " AS meta ON (`posts`.`ID` = `meta`.`postId`)";

        if ($mlSupport->isLotSupport()) {
            $sql .= " LEFT JOIN " . $db->prefix . "term_relationships AS tt0 ON (posts.ID = tt0.object_id)";
        }

        $sql .= " WHERE (`meta`.`id` IN (" . implode(",", $ids) . ") ";

        if ($mlSupport->isLotSupport()) {
            $termId = pll_default_language('term_id');
            $sql .= " AND tt0.term_taxonomy_id IN(" . $termId . ")";
        }

        $sql .= " )
              AND posts.ID = meta.postId
              AND posts.post_type = 'lot'
              AND meta.lang != '0'
              AND ((posts.post_status IN ('publish', 'draft')))
            GROUP BY lotId
            ORDER BY lotId DESC
            LIMIT 0, " . $limit * 10 . ";";

        return $db->get_results($sql);
    }

    private static function findByMeta($ids, $limit = 0)
    {
        $mlSupport = new MultiLanguageSupport();

        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT " . $db->prefix . "posts.ID, UNIX_TIMESTAMP(
            CONVERT_TZ(" . $db->prefix . "posts.post_date, '+00:00', @@global.time_zone)
            ) AS lastUpdate, " . $db->prefix . "postmeta.meta_value AS lotId";
        $sql .= " FROM " . $db->prefix . "posts
            INNER JOIN " . $db->prefix . "postmeta
                ON (" . $db->prefix . "posts.ID = " . $db->prefix . "postmeta.post_id)";

        if ($mlSupport->isLotSupport()) {
            $sql .= " LEFT JOIN " . $db->prefix . "term_relationships AS tt0 ON (" . $db->prefix . "posts.ID = tt0.object_id)";
        }

        $sql .= " WHERE (" . $db->prefix . "postmeta.meta_key = 'lot_id'";

        if ($mlSupport->isLotSupport()) {
            $termId = pll_default_language('term_id');
            $sql .= " AND tt0.term_taxonomy_id IN(" . $termId . ")";
        }

        $sql .= " AND " . $db->prefix . "postmeta.meta_value IN (" . implode(",", $ids) . "))
              AND " . $db->prefix . "posts.post_type = 'lot'
              AND ((" . $db->prefix . "posts.post_status IN ('publish', 'draft')))
            GROUP BY lotId
            ORDER BY lotId DESC
            LIMIT 0, " . $limit * 10 . ";";

        return $db->get_results($sql);
    }

    /**
     * @param $lotID int
     * @param $postID int
     * @param $langCode string
     * @return int[]|WP_Post[]
     */
    public static function findLotByLotID($lotID, $postID, $langCode)
    {
        $args = array(
            "numberposts" => -1,
            "post_status" => array(SettingsHelper::STATUS_PUBLISH, SettingsHelper::STATUS_DRAFT),
            LotMetaData::BP_QUERY => array(
                "bp_id" => [
                    "value" => $lotID,
                    "compare" => "="
                ],
                "lang" => $langCode
            ),
            "exclude" => $postID,
            "lang" => "",
            "post_type" => "lot",
            "suppress_filters" => false
        );

        return get_posts($args);
    }

    /**
     * @param $postId
     */
    public static function getMetaFieldsByPostID($postId)
    {
        $meta = new stdClass;
        foreach((array)get_post_meta($postId) as $key => $value) {
            $meta->$key = $value[0];
        }
        return $meta;
    }

    /**
     * @param $metaFields stdClass
     * @return array
     */
    public static function getMetaLotThumb($metaFields)
    {
        return self::filterMetaFields('lot_thumb_attachId', $metaFields);
    }

    /**
     * @param $metaFields stdClass
     * @return array
     */
    public static function getMetaLotImage($metaFields)
    {
        return self::filterMetaFields('lot_image_original', $metaFields);
    }

    /**
     * @param $fieldMask string
     * @param $metaFields stdClass
     * @return array
     */
    public static function filterMetaFields($fieldMask, $metaFields)
    {
        $meta = array();
        if (!empty($metaFields)) {
            foreach ($metaFields as $key => $metaField) {
                if (strpos($key, $fieldMask) !== false) {
                    $meta[$key] = $metaField;
                }
            }
        }
        return $meta;
    }

    /**
     * Search lastUpadte value by post id
     * @param $postId int
     * @return int
     */
    public static function findLotLastUpdate($postId) {
        $db = InstanceDB::getInstanceDB();

        $sql = "SELECT `lastUpdate` FROM " . LotMetaData::getTableName() . " WHERE postId = %d";
        $sql = $db->prepare($sql, $postId);
        $result = $db->get_col($sql);

        if (!empty($result)) {
            return $result[0];
        } else {
            return 0;
        }
    }

    public function updateFields($data, $format = false)
    {
        $db = InstanceDB::getInstanceDB();
        return $db->update(self::getTableName($db), $data, array('id' => $this->getId()), $format);
    }

    public static function bulkSave($lots)
    {
        $instance = new Lot();

        $flag = apply_filters('auctionforge_before_save_history_customize', false);
        $masks = apply_filters('auctionforge_before_save_history_masks', $instance->getMasksForFields(), $flag);

        $db = InstanceDB::getInstance();
        if (!empty($lots)) {
            return $db->wp_insert_rows_custom($lots, Importer::TABLE_NAME, $masks);
        } else {
            return false;
        }
    }

    /**
     * @param $count
     * @param int $offset
     * @return int[]|WP_Post[]
     */
    public static function getLots($count, $offset = 0) {
        $args = array(
            "numberposts" => $count,
            "post_status" => array("publish"),
            LotMetaData::BP_QUERY => array(
                "bp_field" => [
                    [
                        "value" => 1,
                        "field" => self::VIEW_HOMEPAGE_BS,
                        "compare" => "="
                    ]
                ],
            ),
            "post_type" => "lot",
            "bp_orderby" => self::VALUE_NUM_BS,
            "order" => "ASC",
            "offset" => $offset,
            "lang" => "",
            "suppress_filters" => false
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $args[LotMetaData::BP_QUERY] = array_merge($args[LotMetaData::BP_QUERY], [
                "bp_index" => array(1),
                "lang" => pll_current_language()
            ]);
        }

        return get_posts($args);
    }

    /**
     * @param $count
     * @param int $offset
     * @return int[]|WP_Post[]
     */
    public static function getFeaturedLotsInAuction($taxonomy, $count, $offset = 0) {
        $args = array(
            "numberposts" => $count,
            "post_status" => array("publish"),
            LotMetaData::BP_QUERY => array(
                "bp_field" => [
                    [
                        "value" => 1,
                        "field" => self::VIEW_HOMEPAGE_BS,
                        "compare" => "="
                    ],
                    [
                        "value" => $taxonomy,
                        "field" => 'termId',
                        "compare" => "="
                    ],
                    [
                        "value" => 0,
                        "field" => 'soldBid',
                        "compare" => ">"
                    ]
                ],
            ),
            "post_type" => "lot",
            "bp_orderby" => self::VALUE_NUM_BS,
            "order" => "ASC",
            "offset" => $offset,
            "lang" => "",
            "suppress_filters" => false
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $args[LotMetaData::BP_QUERY] = array_merge($args[LotMetaData::BP_QUERY], [
                "bp_index" => array(1),
                "lang" => pll_current_language()
            ]);
        }

        return get_posts($args);
    }

    public static function countLots() {
        $args = array(
            'numberposts' => -1,
            'post_status' => [SettingsHelper::STATUS_PUBLISH],
            'post_type' => 'lot',
            LotMetaData::BP_QUERY => [
                "bp_field" => [
                    [
                        "value" => 1,
                        "field" => self::VIEW_HOMEPAGE_BS,
                        "compare" => "="
                    ]
                ],
            ],
            "lang" => "",
            "suppress_filters" => false
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $args[LotMetaData::BP_QUERY] = array_merge($args[LotMetaData::BP_QUERY], [
                "bp_index" => array(1),
                "lang" => pll_current_language()
            ]);
        }

        return count(get_posts($args));
    }

    /**
     * @param $itemIndex string|int
     * @return int[]|WP_Post[]
     */
    public static function findLotByLotIndex($itemIndex, $termId)
    {
        if (PolylangSupport::isPolylangActive()) {
            $lang = pll_current_language();
        } else {
            $lang = "";
        }
        $args = array(
            'numberposts' => 1,
            'post_status' => array(SettingsHelper::STATUS_PUBLISH),
            LotMetaData::BP_QUERY => array(
                "bp_index" => [
                    "value" => $itemIndex,
                    "compare" => "=",
                ],
                "term_id" => $termId,
            ),
            "lang" => $lang,
            'post_type' => "lot",
            "suppress_filters" => false
        );

        return get_posts($args);
    }

    public static function getLotsInAuction($auctionId, $count, $offset = 0, $params = array()) {
        $isHideUnsold = SettingsHelper::isChecked(Settings::HIDE_UNSOLD_ITEMS, false);
        $part = $params['part'] ?? 0;
        $lang = $params['lang'] ?? 0;
        $filterCategory = $params['category_by'] ?? 0;
        $auctionDays = SettingsHelper::getTermOption($auctionId, 'auction_days');

        $isArchived = false;
        if ($isHideUnsold) {
            $auctionState = SettingsHelper::getTermOption($auctionId, 'auction_state');
            $isArchived = Auction::isAuctionArchived($auctionState);
        }

        if (!empty($auctionDays[intval($part) - 1])) {
            $auctionDay = $auctionDays[intval($part) - 1];
        } else {
            //$auctionDay = null;
            //$query->set_404();
            //status_header(404);
            $auctionDay = $auctionDays[0];
        }

        $args = array(
            "numberposts" => $count,
            "post_status" => array(SettingsHelper::STATUS_PUBLISH),
            "post_type" => "lot",
            LotMetaData::BP_QUERY => array(
                "bp_index" => array(1),
                "term_id" => intval($auctionId),
                "lang" => $lang
            ),
            "bp_orderby" => "paddedIndex",
            "offset" => $offset,
            "suppress_filters" => false
        );

        if (!empty($filterCategory)) {
            $categoryIds = array_filter(array_map('intval', explode(',', $filterCategory)));
            if (count($categoryIds) === 1) {
                $args[LotMetaData::BP_QUERY]["bp_field"][] = array(
                    "field" => "categoryId",
                    "value" => $categoryIds[0],
                    "compare" => '='
                );
            } elseif (count($categoryIds) > 1) {
                $args[LotMetaData::BP_QUERY]["bp_field"][] = array(
                    "field" => "categoryId",
                    "value" => '(' . implode(',', $categoryIds) . ')',
                    "compare" => 'IN'
                );
            }
        }

        if ($isHideUnsold && $isArchived) {
            $args[LotMetaData::BP_QUERY]["bp_field"][] = array(
                "field" => "soldBid",
                "value" => 0,
                "compare" => '>'
            );
        }

        if (!empty($auctionDay->firstLotIndex) && !empty($auctionDay->lastLotIndex)) {
            $argsBpQuery = array(
                "between" => array(
                    array(
                        "compare" => ">=",
                        "value" => intval($auctionDay->firstLotIndex),
                    ),
                    array(
                        "compare" => "<=",
                        "value" => intval($auctionDay->lastLotIndex),
                    ),
                ),
            );
            $args[LotMetaData::BP_QUERY]["bp_index"] = $argsBpQuery;
        }

        if (!empty($params[Lot::NAME_PARAM_PHRASE])) {
            $args = array_merge($args, [
                's' => $params[Lot::NAME_PARAM_PHRASE]
            ]);
        }

        if (!empty($params[Lot::NAME_PARAM_PER_PAGE])) {
            $args = array_merge($args, [
                'posts_per_page' => $params[Lot::NAME_PARAM_PER_PAGE]
            ]);
        }

        $orderByFields = BidspiritLots::sort_order($params);

        $args2['bp_orderby'] = $orderByFields['orderBy'];
        $args2['lang'] = "";

        $args2['order'] = $orderByFields['order'];

        $args = wp_parse_args($args2, $args);
        return new WP_Query($args);
    }

    /**
     * @param $postId int
     * @param $metaKey string
     * @param $metaValue string
     * @return int|\WP_Error
     */
    public static function updateMetaValue($postId, $metaKey, $metaValue)
    {
        $postData = array(
            'ID' => $postId,
            'meta_input' => [$metaKey => $metaValue],
        );
        return wp_update_post($postData);
    }

    public static function buildItem($item, $itemSecond)
    {
        $item->lotId = $item->id;
        $item->auctionSlug = $item->auctionId;
        $item->syncTimes = 0;
        $item->priority = 1;
        $item->createDatetime = date(Importer::DATE_FORMAT);

        if (isset($itemSecond->name)) {
            $item->nameL2 = $itemSecond->name;
        } else {
            $item->nameL2 = $item->name;
        }

        if (isset($itemSecond->description)) {
            $item->descriptionL2 = $itemSecond->description;
        } else {
            $item->descriptionL2 = $item->description;
        }

        if (isset($itemSecond->author)) {
            $item->authorL2 = $itemSecond->author;
        } else {
            $item->authorL2 = $item->author;
        }

        return $item;
    }

    /**
     * @param $item stdClass
     * @param $leadingBid stdClass
     * @return stdClass
     */
    public static function leadingBid($leadingBid, $item)
    {
        if (!empty($leadingBid) && isset($leadingBid->price)) {
            $item->leadingBid = $leadingBid->price;
        } else {
            $item->leadingBid = 0;
        }

        return $item;
    }

    public static function soldBid($soldBid, $item)
    {
        if (!empty($soldBid) && isset($soldBid->price)) {
            $item->soldBid = $soldBid->price;
        }
        return $item;
    }
}