<?php

namespace Blazemedia\Affiliation\Rendering;

class Parameters {
    
    protected int $post_id;
    protected int $author_id;
    protected string $domain;
    protected string $post_type;    
    protected string $taxonomies;
    protected string $device;
    protected string $content;
    protected string $extra;

    public function __construct(protected \WP_Post $post) {

        $this->buildParameters();
    }
    
    public function toArray(): array {

        return [
            'post_id'    => $this->post_id,
            'domain'     => $this->domain,
            'post_type'  => $this->post_type,
            'author_id'  => $this->author_id,
            'taxonomies' => urlencode($this->taxonomies),
            'device'     => $this->device,
            'content'    => urlencode(urlencode($this->content)),
            'extra'      => urlencode($this->extra),
        ];
    }

    protected function buildParameters() {

        $this->post_id = $this->post->ID;
        $this->domain = $this->getDomain();
        $this->post_type = $this->post->post_type;
        $this->author_id = $this->post->post_author;
        $this->taxonomies = $this->getTaxonomies();
        $this->device = wp_is_mobile() ? 'mobile' : 'desktop';
        $this->content = $this->post->post_content;
        $this->extra = $this->getExtra();
    }

    

    protected function getTaxonomies(): string {

        $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 json_encode($tax_array);
    }

    protected function getDomain(): string {

        $options = get_option('affiliation_settings_option_name');

        return $options['domain_2'];
    }

    protected function getExtra(): string {

        return json_encode([
            'path' => get_permalink(),
        ]);
    }


    public function getSignature( $key =  ''): string {
        return hash('sha256', $key . json_encode($this->toArray()));
    }
    
}   