<?php

namespace Blazemedia\Blackhole;

use Blazemedia\Blackhole\Tools\SimpleDB;


class OffersReaper {

    private int $movedCount = 0;

    function __construct( private SimpleDB $db ) { }


    protected function getQuery( int $limit ) : string {

        $limit_sentence = $limit > 0 ? "LIMIT {$limit}" : "";

        return  "SELECT * from {$this->db->table}
                 WHERE post_status='publish'
                 ORDER BY post_date_timestamp asc
                 {$limit_sentence}
        ";

    }


    function blackhole( int $limit = 0 ) : int {
        $this->movedCount = 0;
        $this->db->forEachQueryItem( $this->getQuery( $limit ), [ $this, 'setPostToBlackhole' ] );
        return $this->movedCount;
    }


    function rollback() : int {
        $this->movedCount = 0;

        $query = "SELECT * from {$this->db->table} WHERE post_status='blackhole' ";
        $this->db->forEachQueryItem( $query, [ $this, 'setPostToPublish' ] );
        return $this->movedCount;
    }


    public function setPostToPublish( $item )   { $this->setPostTo($item, 'publish'); }
    public function setPostToBlackhole( $item ) { $this->setPostTo($item, 'blackhole'); }

    /**
     * Invia un post nel posttype bakchole oppre in bozza
     *
     * @param [type] $item
     * @param string $destination {'publish'|'draft'|'blackhole'}
     * @return void
     */
    protected function setPostTo( $item, string $destination = 'blackhole' ) {

        if( $item->post_status == $destination ) return;

        $item->post_status = $destination;

        $this->db->setWpPostStatus( $item->post_id, $item->original_post_type , $destination );
        $this->db->setStatus(       $item->post_id, $destination );
        $this->movedCount++;
        
        echo json_encode($item);
    }



}
