<?php

namespace Blazemedia\Affiliation\Inventory;

use Exception;

class InventoryItemData {

    protected $post;

    public int    $post_id;
    public int    $author_id;
    public string $domain; 
    public string $url; 
    public string $post_type;
    public string $pub_date;
    public string $content;
    public array  $taxonomies;

    function __construct( \WP_Post|null $post = null ) {

        if ( $post == null ) {
            $post = $GLOBALS['wp_the_query']->get_queried_object();
        }

        if ($post == null || !$post instanceof \WP_Post) {
            throw new \Exception('PostData invoked without a post');
        }
        $this->post = $post;

        $this->extractPostData();        
    }


    function toArray() : array {

        return [
            "post_id"    => $this->post_id,
            "author_id"  => $this->author_id,
            "domain"     => $this->domain,
            "url"        => $this->url,
            "pub_date"   => $this->pub_date,
            "post_type"  => $this->post->post_type,
            "content"    => $this->content,
            "taxonomies" => $this->taxonomies
        ];

    }


    function toJson() : string {

        return json_encode( $this->toArray() );
    }

    
    protected function extractPostData() {

        $this->post_id    = $this->post->ID;
        $this->author_id  = $this->post->post_author;
        $this->content    = $this->post->post_content;
        $this->pub_date   = $this->post->post_date;
        $this->domain     = $this->getDomain();        
        $this->url        = $this->getUrl();    
        $this->post_type  = $this->post->post_type;
        $this->taxonomies = $this->getTaxonomies();
    }


    protected function getDomain() : string {

        $options = \get_option('affiliation_settings_option_name');

        return $options['domain_2'];
    }

    
    protected function getUrl() : string {

        return get_permalink( $this->post );
    }


    protected function getTaxonomies() : array {

        $taxonomies = \get_taxonomies();

        $tax_array =  array_reduce( $taxonomies, function( $tax_array, $taxonomy ) {

            $terms = \wp_get_post_terms( $this->post->ID, $taxonomy, [ 'fields' => 'slugs'] );

            if( !empty($terms) )  $tax_array[ $taxonomy ] = $terms;

            return $tax_array;

        }, []);

        return $tax_array;
    }
}
