<?php 
namespace theme\functions\post_types;
use WP_Post;

final class Page
{
	public $ID        = null;
	public $title     = null;
	public $excerpt   = null;
	public $content   = null;
	public $author_id = null; 
	public $permalink = null;
	public $date      = null;

	private $excerpt_max_word_count = 55;
	private $excerpt_cap_string     = "&hellip;"; // "&hellip;" => "…"

	function __construct( WP_Post|int $wp_post_id )
	{
		$wp_post = get_post( $wp_post_id );

		$this->set_id( $wp_post );
		$this->set_title( $wp_post );
		$this->set_author_id( $wp_post );
		$this->set_permalink( $wp_post );
		$this->set_date( $wp_post );
		$this->set_excerpt( $wp_post );
		$this->set_content( $wp_post );

	}

	private function set_id( WP_Post $wp_post ){ $this->ID = $wp_post->ID; }
	private function set_title( WP_Post $wp_post ){ $this->title = $wp_post->post_title; }
	private function set_author_id( WP_Post $wp_post ){ $this->author_id = $wp_post->post_author; }
	private function set_permalink( WP_Post $wp_post ){ $this->permalink = get_the_permalink( $wp_post->ID ); }
	private function set_date( WP_Post $wp_post ){ $this->date = $wp_post->post_date; }

	/**
	 * Excerpt setzen
	 * 
	 * Falls kein Excerpt gesetzt wurde, werden 
	 * Teile des Posts Contents her genommen.
	 *
	 * @param WP_Post $wp_post
	 * @return void
	 */
	private function set_excerpt( WP_Post $wp_post ){ 
		$excerpt     = $wp_post->post_excerpt;
		$has_excerpt = ( strlen( $excerpt ) > 0 ) ? true : false;

		// Fallback ist der Post-Content
		if( !$has_excerpt ){ $excerpt = $wp_post->post_content; }

		// Bissl nach filtern
		$filter        = [
			'\n'    => ' ',
			'<br>'  => ' ',
			'<br/>' => ' ',
		];
		$excerpt       = strtr( $excerpt, $filter );
		$excerpt       = strip_tags( $excerpt );
		$this->excerpt = wp_trim_words( $excerpt, $this->excerpt_max_word_count, $this->excerpt_cap_string ); 

	}

	/**
	 * Content setzen
	 * 
	 * wichtig ist hier der filter 'the_content'. Die Funktion basiert 
	 * stark auf der WP Funktion 'the_content'
	 * @link https://developer.wordpress.org/reference/functions/the_content/
	 *
	 * @param WP_Post $wp_post
	 * @return void
	 */
	private function set_content( WP_Post $wp_post ){ 
		$filtered_content = $wp_post->post_content;
		$filtered_content = apply_filters( 'the_content', $filtered_content );
		$filtered_content = str_replace( ']]>', ']]&gt;', $filtered_content );

		$this->content    = $filtered_content;
	}
}
