<?php

namespace Blazemedia\Blackhole\Types;
use Blazemedia\Blackhole\Tools\DotEnv;
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 string $post_type = '';
    public bool   $redirected = false;

    private GA4Client $ga;

    private int $timeToCheckBefore;

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


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

        $this->timeToCheckBefore = strtotime('now') - TimeHelper::ONE_MONTH * $monthsToCheckBefore;
        $blackhole_settings_options = get_option('blackhole_settings_option');
        $this->ga = new GA4Client( (isset($blackhole_settings_options['analytics_property']) ? $blackhole_settings_options['analytics_property'] : "298073691"));

        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,
            'post_type' => $this->post_type
        ];
    }


    private function getData( $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;
        $this->post_type = $wp_post->post_type;

        return $this;
    }



    private function getUsers( $post_name ) {

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

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


}
