<?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'
                 AND   USERS = 0
                 ORDER BY post_date_timestamp asc
                 {$limit_sentence}
        ";

    }

    function draft( int $limit = 0 ) {

        $this->db->forEachQueryItem( $this->getQuery( $limit ), [ $this, 'setPostToDraft' ] );
    }


    function blackhole( int $limit = 0 ) {

        $this->db->forEachQueryItem( $this->getQuery( $limit ), [ $this, 'setPostToBlackhole' ] );

    }


    function rollback() {

        $query = "SELECT * from {$this->db->table}
                  WHERE post_status='draft'
                  AND   USERS = 0";

        $this->db->forEachQueryItem( $query, [ $this, 'setPostToPublish' ] );
    }


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


    /**
     * 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->setStatus(       $item['post_id'], $destination );

        $this->db->setWpPostStatus( $item['post_id'], $destination );

        echo json_encode($item);
    }



}
