<?php

namespace auctionforge\inc\model;

use DateTime;
use auctionforge\inc\abs\Model;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\Debug;
use auctionforge\inc\InstanceDB;
use WP_Post;
use WP_Term;

class LotMetaData extends LotModel
{
    const TABLE_LOT_META = "bp_meta_data";
    const BP_QUERY = "bp_query";

    protected $lot;
    protected $id;
    protected $postId;
    protected $termId;
    protected $estimatedPriceInt;

    /**
     * @param $lot WP_Post
     */
    public function init($lot)
    {
        try {
            $date = new DateTime($lot->post_date);
            $date = $date->getTimestamp();
        } catch (\Exception $e) {
            $date = time();
        }

        $this->setLot($lot);
        $this->setPostId($lot->ID);
        $this->setLastUpdate($date);
    }

    /**
     * @param $postId int
     * @return bool
     */
    public function issetRow($postId)
    {
        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT * FROM " . $db->prefix . LotMetaData::TABLE_LOT_META . " WHERE `postId` = %d";
        $sql = $db->prepare($sql, array($postId));
        return (!empty($db->get_var($sql)));
    }

    public static function getMetaField($field, $postId)
    {
        $cacheKey = 'auctionforge_meta_fields_' . $postId;

        $metaData = wp_cache_get($cacheKey, Settings::OPTIONS_GROUP);
        if(false === $metaData) {
            $db = InstanceDB::getInstanceDB();
            $sql = "SELECT * FROM " . $db->prefix . self::TABLE_LOT_META . " WHERE `postId` = %d";
            $sql = $db->prepare($sql, array($postId));
            $metaData = $db->get_row($sql);

            wp_cache_set($cacheKey, $metaData, Settings::OPTIONS_GROUP, 3600);
        }

        if (isset($metaData->{$field})) {
            return $metaData->{$field};
        } else {
            return false;
        }
    }

    public static function getMetaDataByLotId($postId)
    {
        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT * FROM " . $db->prefix . self::TABLE_LOT_META . " WHERE `id` = %d";
        $sql = $db->prepare($sql, array($postId));
        return $db->get_row($sql);
    }

    public static function getMetaFieldByLotId($field, $postId)
    {
        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT `" . $field . "` FROM " . $db->prefix . self::TABLE_LOT_META . " WHERE `id` = %d";
        $sql = $db->prepare($sql, array($postId));
        return $db->get_var($sql);
    }

    public static function getTableName()
    {
        $db = InstanceDB::getInstanceDB();
        return $db->prefix . self::TABLE_LOT_META;
    }

    public function update()
    {
        $db = InstanceDB::getInstanceDB();
        $this->setEstimatedPriceInt();
        return $db->update(self::getTableName(), $this->buildFields(), array("postId" => $this->getPostId()), self::getMasks(), array('%d'));
    }

    public static function updateField($data, $postId, $mask)
    {
        $db = InstanceDB::getInstanceDB();

        $cacheKey = 'auctionforge_meta_fields_' . $postId;
        wp_cache_delete($cacheKey, Settings::OPTIONS_GROUP);
        
        return $db->update(self::getTableName(), $data, array("postId" => $postId), $mask, array('%d'));
    }

    /**
     * @return array
     */
    public static function getMasks()
    {
        $masks = array(
            self::DIGIT_MASK,//postId
            self::DIGIT_MASK,//termId
            self::DIGIT_MASK,//id
            self::STRING_MASK,//lang
            self::STRING_MASK,//paddedIndex
            self::STRING_MASK,//itemIndex
            self::STRING_MASK,//name
            self::STRING_MASK,//author
            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::DIGIT_MASK,//estimatedPriceInt
            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,//isGem
            self::STRING_MASK,//createDatetime
        );

        return apply_filters('auctionforge_build_meta_masks', $masks);
    }

    public function buildFields()
    {
        $metaFields = array(
            'postId' => $this->getPostId(),
            'termId' => $this->getTermId(),
            'id' => $this->getId(),
            'lang' => $this->getLang(),
            'paddedIndex' => $this->getPaddedIndex(),
            'itemIndex' => $this->getItemIndex(),
            'name' => $this->getName(),
            'author' => $this->getAuthor(),
            'details' => $this->getDetails(),
            'startPrice' => $this->getStartPrice(),
            'leadingBid' => $this->getLeadingBid(),
            'soldBid' => $this->getSoldBid(),
            'auctionId' => $this->getAuctionId(),
            'imagesListStr' => $this->getImagesListStr(),
            'categoryId' => $this->getCategoryId(),
            'estimatedPrice' => $this->getEstimatedPrice(),
            'estimatedPriceInt' => $this->getEstimatedPriceInt(),
            'tags' => $this->getTags(),
            'videoUrl' => $this->getVideoUrl(),
            'extraInfo' => $this->getExtraInfo(),
            'params' => $this->getParams(),
            'postSaleDisabled' => Model::toInt($this->getPostSaleDisabled()),
            'imagesBase' => $this->getImagesBase(),
            'imagesCloned' => Model::toInt($this->getImagesCloned()),
            'buyoutPrice' => $this->getBuyoutPrice(),
            'lastUpdate' => $this->getLastUpdate(),
            'fullPriceVat' => Model::toInt($this->getFullPriceVat()),
            'largeDisplay' => Model::toInt($this->getLargeDisplay()),
            'viewOnly' => Model::toInt($this->getViewOnly()),
            'hidden' => Model::toInt($this->getHidden()),
            'hiddenInPortal' => Model::toInt($this->getHiddenInPortal()),
            'removedFromAuction' => Model::toInt($this->getRemovedFromAuction()),
            'eroticContent' => Model::toInt($this->getEroticContent()),
            'isGem' => Model::toInt($this->getIsGem()),
            'createDatetime' => time(),
        );

        return apply_filters('auctionforge_build_meta_fields', $metaFields, $this);
    }

    public function setPostId($postId)
    {
        return $this->postId = $postId;
    }

    public function getPostId()
    {
        return $this->postId;
    }

    public function setTermId($termId)
    {
        $this->termId = $termId;
    }

    public function getTermId()
    {
        return $this->termId;
    }

    /**
     * @return mixed
     */
    public function getLot()
    {
        return $this->lot;
    }

    /**
     * @param WP_Post $lot
     */
    public function setLot($lot)
    {
        $this->lot = $lot;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param  mixed  $id
     */
    public function setId($id)
    {
        $this->id = intval($id);
    }

    /**
     * @return mixed
     */
    public function getEstimatedPriceInt()
    {
        return $this->estimatedPriceInt;
    }

    /**
     * @param  mixed  $estimatedPriceInt
     */
    public function setEstimatedPriceInt()
    {
        $estimatedPriceInt = $this->getEstimatedPrice();
        $estimatedPriceInt = str_replace(" ", "", $estimatedPriceInt);
        $estimatedPriceInt = str_replace(" ", "", $estimatedPriceInt);
        $estimatedPriceInt = preg_replace("/^(\W)+|[\,\.]/", "", $estimatedPriceInt, 1);
        $estimatedPriceInt = preg_replace("/[\,\.]/", "", $estimatedPriceInt);
        $estimatedPriceInt = apply_filters('filter_estimatedPriceInt', $estimatedPriceInt);
        preg_match("/^\d+/", $estimatedPriceInt, $matches);
        if (!empty($matches[0])) {
            $this->estimatedPriceInt = $matches[0];
        } else {
            $this->estimatedPriceInt = $estimatedPriceInt;
        }
    }
}
