<?php

namespace Blazemedia\Blackhole;

use Blazemedia\Blackhole\Tools\SimpleDB;


class OffersReaper {

    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 ) {
        $this->db->forEachQueryItem( $this->getQuery( $limit ), [ $this, 'setPostToBlackhole' ] );
    }


    function rollback() {

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


    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 );
        
        echo json_encode($item);
    }



}
