<?php

namespace auctionforge\inc\import;

use auctionforge\inc\Debug;
use auctionforge\inc\InstanceDB;

class SilentMigrator
{
    public function run()
    {
        $waSuspended = wp_suspend_cache_addition();
        wp_suspend_cache_addition(true);

        while ($ids = $this->findLots()) {
            if (!empty($ids)) {
                foreach ($ids as $post) {
                    $lotId = get_post_meta($post->ID, 'lot_id', true);
                    if (!empty($lotId)) {
                        $this->updatePostParent($post->ID, $lotId);
                    } else {
                        $this->updatePostParent($post->ID, 1);
                    }
                }
            }
        }

        wp_suspend_cache_addition($waSuspended);
    }

    public function start()
    {
        $waSuspended = wp_suspend_cache_addition();
        wp_suspend_cache_addition(true);

        $ids = $this->findLots();
        if (!empty($ids)) {
            foreach ($ids as $post) {
                $lotId = get_post_meta($post->ID, 'lot_id', true);
                if (!empty($lotId)) {
                    $this->updatePostParent($post->ID, $lotId);
                }
            }
        }

        wp_suspend_cache_addition($waSuspended);
    }

    /**
     * @param  int  $limit
     * @return array|object|null
     */
    private function findLots($limit = 100)
    {
        $db = InstanceDB::getInstanceDB();

        $sql = "SELECT " . $db->prefix . "posts.ID
                FROM " . $db->prefix . "posts
                WHERE (" . $db->prefix . "posts.post_parent = 0)
                  AND " . $db->prefix . "posts.post_type = 'lot'
                  AND (" . $db->prefix . "posts.post_status = 'publish')
                GROUP BY " . $db->prefix . "posts.ID
                LIMIT 0, " . $limit . ";";

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

    private function updatePostParent($postId, $parent)
    {
        $db = InstanceDB::getInstanceDB();

        $sql = "UPDATE `" . $db->prefix . "posts`" .
            " SET `post_parent` = %d WHERE `ID` = %d";
        $sql = $db->prepare($sql, $parent, $postId);
        return $db->query($sql);
    }
}