<?php

namespace auctionforge\ajax;

use stdClass;
use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\abs\ImageModel;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\Lot;
use auctionforge\inc\model\LotImage;
use WP_Post;
use WP_Query;

class AuctionFilter extends AJAXHandler
{
    private $isSearch = true;

    function callback ()
    {
        add_filter('posts_join', array($this, 'cf_search_join'));
        add_filter('posts_where', array($this, 'cf_search_where'));
        add_filter('posts_distinct', array($this, 'cf_search_distinct'));

        $data = $_POST;
        $this->setAction($data["action"]);
        $phrase = $data["phrase"];
        $param = array(
            Lot::NAME_PARAM => (!empty($data["sort_by"])) ? $data["sort_by"] : ""
        );
        $taxonomy = intval($data["term"]);
        $trigger = false;

        $lotsNotFoundTemplate = "<div class=\"bp-d-flex bp-mb-30\"><p>" . __('Lots not found', 'auctionforge') ."</p></div>";

        if ($phrase == "") {
            $items = array();
        } else {
            $this->setIsSearch(true);
            $items = Lot::getLotsBySearch($phrase, $taxonomy, $param);
            $trigger = true;
        }

        $displayStartPriceInCatalog = SettingsHelper::getTermOption($taxonomy, 'auction_displayStartPriceInCatalog');
        $showEstimatedPriceInItemsList = SettingsHelper::getTermOption($taxonomy, 'auction_showEstimatedPriceInItemsList');

        if ($trigger == true) {
            $lots = array();
            /** @var WP_Post $item */
            foreach ($items as $item) {
                $lot = new stdClass();
                $lotHelper = new LotHelper($item->ID);
                $itemIndex = $lotHelper->getOptionValue('lot_itemIndex', 0);
                $lot->post_title = LotHelper::printTranslateLot($itemIndex);
                $lot->guid = get_the_permalink($item->ID);
                $lot->guid = LotHelper::getLotLink($lot->guid, $data['lang']);

                $title = $lotHelper->getOptionValue('lot_name', '');
                $content = $item->post_content;
                $title = LotHelper::getLotTitle($title, $content);

                $lot->post_content = htmlspecialchars_decode($title);

                $lot->featureImage = $lotHelper->getFeatureImage();

                $lot->start_price = $lotHelper->getOptionValue('lot_start_price', 0);
                $lot->estimated_price = $lotHelper->getOptionValue('lot_estimated_price', 0);
                $lot->itemIndex = $itemIndex;

                $itemData = new stdClass();
                $itemData->title = $title;
                $itemData->content = $content;
                $lot->itemData = urlencode(json_encode($itemData, ENT_QUOTES));

                $lots[] = apply_filters('auctionforge_item_do_load_more', $lot, $item, $itemData);
            }
            $lots = apply_filters('auctionforge_items_do_load_more', $lots);
            
            $response = array(
                'lots' => $lots,
                'showEstimatedPriceInItemsList' => $showEstimatedPriceInItemsList,
                'displayStartPriceInCatalog' => $displayStartPriceInCatalog,
                'loadPagination' => false,
                'lotsNotFoundTemplate' => $lotsNotFoundTemplate
            );
            wp_send_json_success($response);
        } else {
            wp_send_json_error(array(
                'lots' => array()
            ));
        }
    }

    public function cf_search_join( $join ){
        global $wpdb;

        if ($this->getIsSearch()) {
            $join .= " LEFT JOIN $wpdb->postmeta auctionforgekey ON (ID = auctionforgekey.post_id)";
        }

        return $join;
    }

    public function cf_search_where( $where ){
        global $wpdb;

        if ($this->getIsSearch()) {
            $where = preg_replace(
                "/OR +\( *$wpdb->posts.post_content +LIKE +('[^']+')/",
                "OR (auctionforgekey.meta_value LIKE $1) $0",
                $where
            );
            $where .= $wpdb->prepare(' AND auctionforgekey.meta_key = %s', 'lot_name');

            $pattern = '/\(..+.meta_key = \'lot_name\' AND .+.meta_value +LIKE +(\'[^\']+\').+\)/';
            $where = preg_replace($pattern, '1=1', $where);
        }
        return $where;
    }

    public function cf_search_distinct($where) {
        if ($this->getIsSearch()) {
            return 'DISTINCT';
        } else {
            return $where;
        }
    }

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

    /**
     * @param  mixed  $isSearch
     */
    public function setIsSearch($isSearch)
    {
        $this->isSearch = $isSearch;
    }
}
//$gate = new AuctionFilter();
//$gate->init('do_lot_filter');
