<?php

namespace auctionforge\inc\controllers;

use stdClass;
use auctionforge\inc\abs\BidspiritWebhooks;
use auctionforge\inc\BidSpiritRequest;
use auctionforge\inc\helpers\BS_API;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\import\InsertLotsBS;
use auctionforge\inc\model\Auction;
use auctionforge\inc\model\Lot;
use auctionforge\inc\model\LotMetaData;
use auctionforge\inc\traits\LoggerInfo;
use WP_REST_Request;

class PluginAPI extends BidspiritWebhooks
{
    use LoggerInfo;

    const API_NAMESPACE = 'plugin/v1';

    public function init()
    {
        add_action('rest_api_init', array($this, 'menu'));
        add_action('rest_api_init', array($this, 'sync_lot'));
        add_action('rest_api_init', array($this, 'get_item_info'));
    }

    public function sync_lot()
    {
        if (!defined('ABSPATH')) {
            die('You shouldnt be here');
        }

        $namespace = self::API_NAMESPACE;

        $rout = '/sync-lot/';

        $rout_params = array(
            'methods' => 'POST',
            'callback' => array($this, 'sync_lot_action'),
            'permission_callback' => function ($request) {
                return $this->checkPermission();
            },
        );

        register_rest_route($namespace, $rout, $rout_params);
    }

    public function sync_lot_action(WP_REST_Request $request)
    {
        $action = "items/getAuctionItem.api";
        $action2 = "items/getItemsInfo.api";
        $data = $request->get_params();
        $auctionId = $data['auctionId'];
        $sessionId = $data['sessionId'];
        $itemIndex = $data['item']["itemIndex"];
        $langCode = MultiLanguageSupport::getDefaultLangCode();

        $data = array(
            "auctionId" => $auctionId,
            "itemIndex" => $itemIndex,
            "language" => $langCode
        );

        $auctionItemResponse = BidSpiritRequest::send($action, $data);
        $auctionItemResponse = json_decode($auctionItemResponse['response']);
        $item = new stdClass();
        if (isset($auctionItemResponse->response) && isset($auctionItemResponse->response->item)) {
            $item = $auctionItemResponse->response->item;
        }

        $data = [
            "sessionId" => $sessionId,
            "auctionId" => $auctionId,
            "lotIndexes" => $itemIndex
        ];
        $itemsInfoResponse = BidSpiritRequest::send($action2, $data);
        $itemsInfoResponse = json_decode($itemsInfoResponse['response']);

        if (isset($itemsInfoResponse->response->itemsInfo)) {
            $itemsInfo = $itemsInfoResponse->response->itemsInfo->{$itemIndex};
            $response['itemsInfo'] = $itemsInfo;
            if (!empty($itemsInfo->leadingBid)) {
                $item = Lot::leadingBid($itemsInfo->leadingBid, $item);
            }

            if (!empty($itemsInfo->soldBid)) {
                $item = Lot::soldBid($itemsInfo->soldBid, $item);
            }

            if (!empty($itemsInfo->paddedIndex)) {
                $item->paddedIndex = $itemsInfo->paddedIndex;
            }
        }

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $secondLangCode = MultiLanguageSupport::getSecondLangCode();
            $action = "items/getAuctionItem.api";
            $data = array(
                "auctionId" => $auctionId,
                "itemIndex" => $itemIndex,
                "language" => $secondLangCode
            );
            $itemSecond = BidSpiritRequest::send($action, $data);
            $itemSecond = json_decode($itemSecond['response']);

            $item = Lot::buildItem($item, $itemSecond->response->item);
        }

        $lot = new Lot();
        $lot->loadAttributes($item);
        $lot->setPriority(1);
        $lots[] = $lot;
        $result = Lot::bulkSave($lots);
        $response['item'] = $item;
        $response['data'] = $data;

        $response = apply_filters('bs_api_sync_lot_response', $response);
        echo json_encode($response);
    }

    public function menu()
    {
        if (!defined('ABSPATH')) {
            die('You shouldnt be here');
        }

        $namespace = self::API_NAMESPACE;

        $rout = '/menu/';

        $rout_params = array(
            'methods' => 'GET',
            'callback' => array($this, 'menu_action'),
            'permission_callback' => function ($request) {
                return $this->checkPermission();
            },
        );

        register_rest_route($namespace, $rout, $rout_params);
    }

    public function menu_action(WP_REST_Request $request)
    {
        /** @var stdClass $response */
        $response = new \stdClass();
        $response->menu = [];
        $isDebug = false;
        $menus = get_terms([
            'taxonomy' => 'nav_menu',
            'hide_empty' => false,
        ]);
        $defaultLang = SettingsHelper::getOption('lang', 'en');
        $secondLang = false;
        $otherLangs = [];
        if (PolylangSupport::isPolylangActive()) {
            $secondLang = MultiLanguageSupport::getSecondLangCode();
        }

        $otherLanguages = PolylangSupport::getSupportedLanguages();
        if (!empty($otherLanguages['other'])) {
            foreach ($otherLanguages['other'] as $otherLanguage) {
                $otherLangs[] = $otherLanguage;
            }
        }

        $menuSlug = "primary-menu";
        $menuSlugSecond = apply_filters("bp_api_menu_second_slug", "primary-" . $secondLang);

        $slugs = [
            $defaultLang => $menuSlug,
        ];
        if ($secondLang) {
            $slugs[$secondLang] = $menuSlugSecond;
        }
        if (!empty($otherLangs)) {
            foreach ($otherLangs as $item) {
                $menuSlugOther = apply_filters("bp_api_menu_second_slug", "primary-" . $item);
                $slugs[$item] = $menuSlugOther;
            }
        }
        $slugs = apply_filters("bp_api_menu_slugs", $slugs);
        if ($isDebug) {
            $response->slugs = $slugs;
            $response->otherLangs = $otherLangs;
        }

        if (!empty($menus)) {
            $home = home_url();
            foreach ($menus as $menu) {
                if ($isDebug) {
                    $response->debug[] = [
                        $menu->slug,
                        array_search($menu->slug, $slugs)
                    ];
                }
                if (array_search($menu->slug, $slugs) !== false) {
                    $key = array_search($menu->slug, $slugs);
                    /** @var \WP_Post[] $menuItems */
                    $menuItems = wp_get_nav_menu_items($menu->term_id);
                    if ($isDebug) {
//                        $response->menus = $menuItems;
                    }
                    $menu = [];
                    $tmpItems = [];

                    foreach ($menuItems as $menuItem) {
                        $current_item = array(
                            'title' => $menuItem->title,
                            'href' => $menuItem->url,
                            'id' => $menuItem->ID
                        );

                        if (strpos($menuItem->url, $home) === false) {
                            continue;
                        }

                        if (!in_array($menuItem->url, $tmpItems) !== false) {
                            $tmpItems[] = $menuItem->url;
                            $menu[] = $current_item;
                        }

                        //For multilevel menu
                        /*if ( $parent_id ) {
                            $menu[$parent_id]['submenu'][] = $current_item;
                        } else {
                            $menu[$menuItem->ID] = $current_item;
                        }*/
                    }
                    $menu = array_values($menu);
                    $response->menu[$key] = $menu;
                }
            }
        }
        $response = apply_filters('bs_api_menu_response', $response);
        echo json_encode($response);
    }

    public function get_item_info()
    {
        if (!defined('ABSPATH')) {
            die('You shouldnt be here');
        }

        $namespace = self::API_NAMESPACE;

        $rout = '/item-info/';

        $rout_params = array(
            'methods' => 'POST',
            'callback' => array($this, 'get_item_info_action'),
            'permission_callback' => function ($request) {
                return $this->checkPermission();
            },
        );

        register_rest_route($namespace, $rout, $rout_params);
    }

    public function get_item_info_action(WP_REST_Request $request)
    {
        $params = $request->get_params();
        $lotData = LotMetaData::getMetaDataByLotId($params['lotId']);
        $termId = LotMetaData::getMetaFieldByLotId('termId', $params['lotId']);
        $auctionId = SettingsHelper::getTermOption($termId, 'auction_id');
        $lang = MultiLanguageSupport::getDefaultLangCode();
        $success = true;

        if (empty($lotData)) {
            $success = false;
        }

        echo json_encode([
            'success' => $success,
            'params' => $params,
            'data' => $lotData,
            'auctionId' => $auctionId,
            'lang' => $lang,
        ]);
    }
}
$instance = new PluginAPI();
$instance->init();
