<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Blog_model — insight articles.
 */
#[\AllowDynamicProperties]
class Blog_model extends MY_Model {

	protected $table = 'blog';
	protected $order_by = 'publish_at DESC, created_at DESC';

	/** Published posts (status published, or scheduled and now due). */
	public function published($limit = NULL, $offset = 0, $category = NULL)
	{
		$now = date('Y-m-d H:i:s');
		$this->db->group_start()
			->where('status', 'published')
			->or_group_start()
				->where('status', 'scheduled')
				->where('publish_at <=', $now)
			->group_end()
		->group_end();
		if ($category) $this->db->where('category', $category);
		$this->db->order_by('publish_at DESC');
		if ($limit) $this->db->limit($limit, $offset);
		return $this->db->get($this->table)->result_array();
	}

	/** Count published posts (for pagination). */
	public function published_count($category = NULL)
	{
		$now = date('Y-m-d H:i:s');
		$this->db->group_start()
			->where('status', 'published')
			->or_group_start()
				->where('status', 'scheduled')
				->where('publish_at <=', $now)
			->group_end()
		->group_end();
		if ($category) $this->db->where('category', $category);
		return $this->db->count_all_results($this->table);
	}

	/** Fetch a published post by slug. */
	public function by_slug($slug)
	{
		$row = $this->get_by(array('slug' => $slug));
		if ( ! $row) return NULL;
		// Hide drafts / not-yet-due scheduled posts from the public.
		if ($row['status'] === 'draft') return NULL;
		if ($row['status'] === 'scheduled' && strtotime($row['publish_at']) > time()) return NULL;
		return $row;
	}

	/** Recent posts excluding the current one. */
	public function recent($exclude_id = NULL, $limit = 3)
	{
		$now = date('Y-m-d H:i:s');
		$this->db->where('status', 'published');
		if ($exclude_id) $this->db->where('id !=', $exclude_id);
		return $this->db->order_by('publish_at DESC')
			->limit($limit)->get($this->table)->result_array();
	}

	/** Increment view counter. */
	public function add_view($id)
	{
		return $this->db->where('id', $id)
			->set('views', 'views+1', FALSE)
			->update($this->table);
	}

	/** Distinct categories among published posts. */
	public function categories()
	{
		$rows = $this->db->distinct()->select('category')
			->where('status', 'published')
			->where('category !=', '')
			->get($this->table)->result_array();
		return array_column($rows, 'category');
	}
}
