<?php

namespace Blazemedia\Blackhole;

use Blazemedia\Blackhole\Tools\SimpleDB;

use Blazemedia\Blackhole\Tools\TimeHelper;
use Blazemedia\Blackhole\Types\PostItem;

class OfferListProvider {

    const MONTHS_TO_START_BEFORE = 6;


    function __construct(
        protected SimpleDB $db,
        private int $monthsToCheckTrafficFrom = 2,
        private int $usersThreshold = 10
        ) {
    }


    function scan() {

        $beforeTimestamp = strtotime('now') - TimeHelper::ONE_MONTH * OfferListProvider::MONTHS_TO_START_BEFORE;

        echo "Before: ".date('Y-m-d', $beforeTimestamp );

        $this->db->forEachOfferPost( [$this, 'checkWpPost'], $beforeTimestamp );
    }


    public function checkWpPost( $wp_post ){

        /// if already inserted do nothing
        if( $this->db->exists( $wp_post['ID']) ) return;

        $post = new PostItem( $wp_post, $this->monthsToCheckTrafficFrom );

        echo json_encode( $post->toArray() ) ."\n";

        if( $this->hasNotEnoughTraffic( $post ) ) $this->insertIntoList( $post );
    }


    function insertIntoList( PostItem $post ) {

        $this->db->save( $post );
    }


    function hasNotEnoughTraffic( $post ) {

        return $post->users < $this->usersThreshold;
    }

}
