<?php

namespace auctionforge\inc\import;

use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\Auction;
use auctionforge\inc\model\LotMetaData;
use WP_Post;
use WP_Term;

class MetaMigrate
{
    public function run()
    {
        $limit = 100;
        $i = 0;
        $lotIds = $this->listOfAllLots($limit, $i);
        $tablePerObject = SettingsHelper::getOption(Settings::OPTION_TABLE_PER_OBJECT, false, 'file');
        $migrationIsFinished = SettingsHelper::getOption("migration_is_finished", false, 'file');

        if ($migrationIsFinished) {
            return;
        }

        if (!$tablePerObject && count($lotIds) > 0) {
            $langCode = SettingsHelper::getOption('lang', 'en');
            $polylangEnable = false;
            if (PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport()) {
                $polylangEnable = true;
            }
            /** @var WP_Post $lot */
            foreach ($lotIds as $lotId) {
                $lot = get_post($lotId);
                $metaFields = get_post_meta($lotId);

                $rows = [];
                if (!empty($metaFields)) {
                    $fields = array();
                    $metaModel = apply_filters('auctionforge_lot_meta_data_instance', new LotMetaData());
                    foreach ($metaFields as $key => $metaField) {
                        $key = preg_replace("/lot_/", "", $key);
                        if (!isset($metaField[0])) {
                            continue;
                        }
                        $fields[$key] = $metaField[0];

                    }

                    $metaModel->loadAttributes($fields);
                    $metaModel->init($lot);

                    $auction = Auction::findAuctionById($metaModel->getAuctionId());
                    $termId = 0;
                    if ($auction instanceof WP_Term) {
                        $termId = $auction->term_id;
                    }
                    $metaModel->setTermId($termId);

                    if ($polylangEnable) {
                        $langCodes = pll_get_post_translations($lot->ID);
                        $langCode = array_search($lot->ID, $langCodes);
                        $metaModel->setLang($langCode);
                    } else {
                        $metaModel->setLang($langCode);
                    }

                    if ($metaModel->getPostId()) {
                        $rows[] = $metaModel;
                    }
                }

                if (!empty($rows)) {
                    foreach ($rows as $row) {
                        $this->insertRow(array($row), LotMetaData::getMasks());
                    }
                }
            }
        } else {
            $posts = $this->listOfAllLotsWP($limit, $i);
            SettingsHelper::setOption(Settings::OPTION_TABLE_PER_OBJECT, true);
            if (!empty($posts)) {
                foreach ($posts as $post) {
                    $this->deleteAllMetaFieldsByPostID($post->ID);
                }
            } else {
                SettingsHelper::setOption("migration_is_finished", true);
            }
        }
    }

    private function listOfAllLots($limit, $i) {
        $db = InstanceDB::getInstanceDB();
        $sql = "SELECT `posts`.`ID`
            FROM `" . $db->posts . "` AS `posts`
            LEFT JOIN `" . LotMetaData::getTableName() . "` AS `meta` ON (`meta`.`postId` = `posts`.`ID`)
            WHERE `meta`.postId IS NULL AND `posts`.`post_type` = 'lot' LIMIT {$i}, {$limit}";

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

    private function listOfAllLotsWP($limit, $i) {
        return get_posts(
            array(
                'post_type' => 'lot',
                'numberposts' => $limit,
                'post_status' => array(
                    SettingsHelper::STATUS_PUBLISH,
                    SettingsHelper::STATUS_DRAFT,
                    SettingsHelper::STATUS_TRASH,
                    SettingsHelper::STATUS_FUTURE
                ),
                'meta_query' => array(
                    array(
                        'key' => 'lot_id',
                        'compare' => 'EXISTS'
                    )
                ),
                'offset' => $limit * $i,
                'lang' => ''
            )
        );
    }

    private function insertRow($row, $masks)
    {
        $db = InstanceDB::getInstance();
        return $db->wp_insert_rows_custom($row, LotMetaData::TABLE_LOT_META, $masks);
    }

    private function deleteAllMetaFieldsByPostID($postId) {
        $db = InstanceDB::getInstanceDB();
        $result = $db->delete($db->postmeta, array('post_id' => $postId));
        clean_post_cache($postId);
        return $result;
    }
}
