<?php

namespace FleekDash\Models;

defined('ABSPATH') || exit;

class Posts extends BaseModel
{
	/**
	 * The table associated with the model.
	 *
	 * @var string
	 */
	protected $table = 'posts';

	/**
	 * The primary key for the model.
	 * WordPress uses 'ID'.
	 *
	 * @var string
	 */
	protected $primaryKey = 'ID';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['post_title', 'post_content', 'post_status', 'post_author'];

	/**
	 * Get published posts with pagination
	 */
	public static function getPublished($page = 1, $per_page = 10)
	{
		$instance = new static();
		$offset = ($page - 1) * $per_page;

		$results = $instance->wpdb->get_results($instance->wpdb->prepare(
			"SELECT * FROM {$instance->table}
			 WHERE post_status = 'publish'
			 ORDER BY post_date DESC
			 LIMIT %d OFFSET %d",
			$per_page,
			$offset
		), ARRAY_A);

		return array_map([$instance, 'castAttributes'], $results);
	}

	/**
	 * Get single published post
	 */
	public static function getPublishedById($id)
	{
		$instance = new static();

		$result = $instance->wpdb->get_row($instance->wpdb->prepare(
			"SELECT * FROM {$instance->table}
			 WHERE ID = %d AND post_status = 'publish'",
			$id
		), ARRAY_A);

		return $result ? $instance->castAttributes($result) : null;
	}
}
