<?php

namespace auctionforge\inc\abs;

use auctionforge\inc\BidSpiritRequest;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\controllers\MultiLanguageSupport;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\Auction;
use auctionforge\inc\traits\LoggerInfo;

abstract class Importer
{
    use LoggerInfo;

    const FIELD_LANGUAGE = 'language';
    const FIELD_SESSION_ID = 'sessionId';
    const SYNC_TABLE_FIELD_STATUS = 'updatedStatus';
    const SYNC_TABLE_STATUS = 'finished';
    const SYNC_TABLE_FIELD_UPDATE = 'updateStartedAt';
    const DATE_FORMAT = "Y-m-d H:i:s";
    const TABLE_NAME = "import_history";

    /**
     * Initialize SessionId to Bidspirit API and run process import
     * @var string
     */
    private $sessionId;
    protected $responseData;

    /**
     * List auctions
     * @var array
     */
    private $auctions;

    /**
     * List of errors that occurred on the bidspirit side
     * @var array
     */
    private $errors;

    protected function sessionInit()
    {
        $action = "users/initSession.api";
        $data = array(
            self::FIELD_SESSION_ID => "",
            self::FIELD_LANGUAGE => MultiLanguageSupport::getDefaultLangCode()
        );

        $responseInitSession = BidSpiritRequest::send($action, $data);
        $this->setSessionId($responseInitSession['response']);
    }

    /**
     * The name of the table for storing data from the bidspirit server
     * @var string
     */
    protected $tableName;

    /**
     * Initialization of variables
     * @return void
     */
    public function __construct() {
        $this->setTableName('import_history');
    }

    /**
     * Get session id from Bidspirit API
     * @return string
     */
    public function getSessionId()
    {
        return $this->sessionId;
    }

    /**
     * Set session id from answer Bidspirit system
     * @param $sessionData
     */
    private function setSessionId($sessionData)
    {
        $sessionData = json_decode($sessionData);
        if (!empty($sessionData->response->sessionId)) {
            $this->sessionId = $sessionData->response->sessionId;
        }
    }

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

    /**
     * @param mixed $responseData
     */
    public function setResponseData($responseData)
    {
        $this->responseData = new \stdClass();
        $responseData = json_decode($responseData['response']);
        if (!empty($responseData->response)) {
            $this->responseData = $responseData->response;
        }
    }

    /**
     * Get available identificators for auctions
     * @return array
     */
    public function getAuctions()
    {
        return $this->auctions;
    }

    /**
     * Set available identidicators for auctions
     * @return void
     */
    protected function setAuctions()
    {
        $this->auctions = [];
        $args = array(
            'post_type' => BidspiritLots::POST_TYPE,
            'taxonomy' => BidspiritLots::TAX_AUCTION_TYPE,
            'hide_empty' => 0,
            'orderby' => 'title',
            'order' => 'DESC',
        );

        if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
            $args = array_merge($args, array(
                'lang' => pll_default_language(),
            ));
        }

        $terms = get_terms($args);
        if (!empty($terms)) {
            // TODO: Get all auction IDs at once.
            foreach ($terms as $term) {
                $auctionId = SettingsHelper::getTermOption($term->term_id, 'auction_id');
                if (!empty($auctionId)) {
                    $this->auctions[] = $auctionId;
                }
            }
        }
    }

    protected function mergeWithShops($auctions)
    {
        $shopAuctions = SettingsHelper::getAuctionListFromSettings('shop_auction');
        $shopAuctionsTerms = get_terms([
            'taxonomy' => Auction::TERM,
            'include' => $shopAuctions
        ]);

        if (!empty($shopAuctionsTerms)) {
            $auctions = array_merge($auctions, $shopAuctionsTerms);
        }

        return $auctions;
    }

    /**
     * Get table name
     * @return string
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * Set table name
     * @param string $tableName
     * @return void
     */
    private function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }

    protected function clearErrorData ()
    {
        $this->errors = [];
    }

    /**
     * Getting a list of errors that occurred on the bidspirit side
     * @return mixed
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Install errors from answer Bidspirit API
     * @param $data string
     */
    protected function setErrors($data)
    {
        $data = json_decode($data);
        if (isset($data->response->success) && !$data->response->success) {
            $this->errors[] = json_encode($data->response);
        }
    }

    protected function setError($error)
    {
        $this->errors[] = $error;
    }

    /**
     * Get site admin id
     * @return int
     */
    protected function getUserIdAdmin()
    {
        $users = get_users([
            'role' => 'administrator',
        ]);
        if (!empty($users)) {
            $users = array_values(array_reverse($users));
            return $users[0]->ID;
        } else {
            return 0;
        }
    }
}