<?php

namespace CliqThemes\ORM\Entities;

use CliqThemes\ORM\Model;

/**
 * ORM model representing the wp_posts table.
 */
class Post extends Model
{
    protected string $table = 'posts';

    protected string $primaryKey = 'ID';

    protected array $fillable = [
        'post_author',
        'post_date',
        'post_date_gmt',
        'post_content',
        'post_title',
        'post_excerpt',
        'post_status',
        'comment_status',
        'ping_status',
        'post_password',
        'post_name',
        'to_ping',
        'pinged',
        'post_modified',
        'post_modified_gmt',
        'post_content_filtered',
        'post_parent',
        'guid',
        'menu_order',
        'post_type',
        'post_mime_type',
        'comment_count',
    ];

    protected bool $timestamps = false;

    /**
     * Relationship to the user that authored the post.
     */
    public function author()
    {
        return $this->belongsTo(User::class, 'post_author');
    }

    /**
     * Relationship to comments associated with the post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class, 'comment_post_ID', 'ID');
    }

    /**
     * Relationship to post meta rows associated with the post.
     */
    public function meta()
    {
        return $this->hasMany(PostMeta::class, 'post_id', 'ID');
    }

    /**
     * Relationship to term taxonomies the post is assigned to.
     */
    public function taxonomies()
    {
        return $this->belongsToMany(TermTaxonomy::class, 'term_relationships', 'object_id', 'term_taxonomy_id');
    }

    /**
     * Convenience accessor to return the related terms for the post.
     *
     * @return Term[]
     */
    public function terms(): array
    {
        return array_values(array_filter(array_map(static function (TermTaxonomy $taxonomy) {
            return $taxonomy->term;
        }, $this->taxonomies())));
    }
}

