<?php

namespace Blazemedia\Blackhole\Types;

use Blazemedia\Blackhole\Tools\GA4Client;
use Blazemedia\Blackhole\Tools\TimeHelper;

class PostItem {

    public int    $ID = 0;
    public int    $timestamp = 0;
    public string $query = '';
    public int    $users = 0;
    public string $status = '';
    public bool   $redirected = false;

    private GA4Client $ga;

    private int $timeToCheckBefore;

    public function __construct( array $wp_post  = [], int $monthsToCheckBefore = 0 ) {


		/** prepara l'istanza del DB */
		(new DotEnv(__DIR__ . '/../../../../../../.env'))->load();

        $this->timeToCheckBefore = strtotime('now') - TimeHelper::ONE_MONTH * $monthsToCheckBefore;

        $this->ga = new GA4Client( getenv('GA4_PROPERTY') );

        if( !empty( $wp_post) ) $this->getData( $wp_post );
    }

    public function toArray(){

        return [
            'ID'        => $this->ID,
            'users'     => $this->users,
            'timestamp' => $this->timestamp,
            'query'     => $this->query,
            'status'    => $this->status
        ];
    }


    private function getData( array $wp_post ) : PostItem {

        $this->ID        = $wp_post['ID'];
        $this->users     = $this->getUsers( $wp_post['post_name'] );
        $this->timestamp = strtotime( $wp_post['post_date'] );
        $this->query     = $wp_post['post_name'];
        $this->status    = $wp_post['post_status'];

        return $this;
    }



    private function getUsers( $post_name ) {

        $startDate = date('Y-m-d', $this->timeToCheckBefore );

        return $this->ga->getUsers( $post_name, $startDate )->users;
    }


}
