<?php

namespace Blazemedia\Blackhole\Types;
use Blazemedia\Blackhole\Tools\DotEnv;
use Blazemedia\Blackhole\Tools\GA4Client;

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 bool $analyticsEnabled = true;

    private int $timeToCheckBefore;

    public function __construct( $wp_post  = [], int $daysToCheckBefore = 7, bool $analyticsEnabled = true ) {


        $this->analyticsEnabled = $analyticsEnabled;
        $this->timeToCheckBefore = strtotime('now') - DAY_IN_SECONDS * $daysToCheckBefore;

        if ( $this->analyticsEnabled ) {
            /** prepara l'istanza del DB */
            (new DotEnv(__DIR__ . '/../../../../../../.env'))->load();
            $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->analyticsEnabled ? $this->getUsers( $wp_post->post_name ) : 0;
        $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;
    }


}
