<?php

namespace Blazemedia\Blackhole;

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

class ExpiredOffersCollector {

    private string $list = '';

    function __construct( private SimpleDB $db, private int $monthsToRedirect ) { }

    /**
     * Gather the post-names to redirect and
     * returns the redirection file in the correct format
     *
     * @param string $prefix - is the folder to insert before the post name
     * @return string - compiled file
     */
    function compile( string $prefix = '/', string $target = '') : string {

        $endTimestamp = strtotime('now') -
                        OfferListProvider::MONTHS_TO_START_FROM * TimeHelper::ONE_MONTH;

        $startTimestamp = $endTimestamp -
                          $this->monthsToRedirect * TimeHelper::ONE_MONTH;


        $this->forEachQueryItem(

            "SELECT * FROM {$this->table}
             WHERE users > 0
             AND post_date_timestamp > {$startTimestamp}
             AND post_date_timestamp < {$endTimestamp}
            ",

            function ( $item ) use( $prefix, $target ) {

                $item = (object) $item;

                $this->list .= $this->compileItemRow( $item, $prefix, $target );

                $this->db->setRedirected( $item->post_id );
            }
        );

        return $this->list;
    }


    function compileItemRow( $item, $prefix, $target ) : string {

        //$target = str_replace( '.', '\.', $target );

        return "~^{$prefix}{$item->post_query}/$ {$target};\n";
    }

}
