<?php

namespace Blazemedia\Blackhole;

use Blazemedia\Blackhole\Tools\SimpleDB;

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

class OfferListProvider {

    const DEFAULT_CUTOFF_DAYS = 180;


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


    function scan() {

        $beforeTimestamp = $this->getCutoffTimestamp();

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

        $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;
    }

    private function getCutoffTimestamp() : int {
        $settings = get_option( 'blackhole_settings_option', array() );
        $mode = isset( $settings['cutoff_mode'] ) ? sanitize_key( $settings['cutoff_mode'] ) : 'days';

        if ( $mode === 'fixed_date' && !empty( $settings['cutoff_date'] ) ) {
            $fixedDate = sanitize_text_field( $settings['cutoff_date'] );
            $fixedTimestamp = strtotime( $fixedDate . ' 23:59:59' );

            if ( $fixedTimestamp !== false ) {
                return $fixedTimestamp;
            }
        }

        $days = isset( $settings['cutoff_days'] ) ? absint( $settings['cutoff_days'] ) : self::DEFAULT_CUTOFF_DAYS;
        if ( $days <= 0 ) {
            $days = self::DEFAULT_CUTOFF_DAYS;
        }

        return strtotime('now') - ( DAY_IN_SECONDS * $days );
    }

}
