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

/**
 * Blog — the Bloom Iris Journal: insights and articles.
 */
#[\AllowDynamicProperties]
class Blog extends Public_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('blog_model', 'user_model'));
	}

	/** Blog index with pagination. */
	public function index()
	{
		$this->_listing(NULL);
	}

	/** Posts filtered by category. */
	public function category($slug)
	{
		$slug = str_replace('-', ' ', $slug);
		$this->_listing($slug);
	}

	/** Shared listing logic. */
	private function _listing($category)
	{
		$this->load->library('pagination');
		$per_page = $this->config->item('per_page_public') ?: 9;

		$base = $category
			? base_url('blog/category/'.url_title($category))
			: base_url('blog');
		$offset = (int) $this->uri->segment($category ? 4 : 3, 0);
		$total  = $this->blog_model->published_count($category);

		$this->pagination->initialize($this->_pagination_config($base, $total, $per_page));

		$this->meta(array(
			'title'       => ($category ? ucfirst($category).' — ' : '').'The Journal — Bloom Iris Agency',
			'description' => 'Creative insights, campaign stories and behind-the-scenes from Bloom Iris.',
		));

		$this->render('blog/index', array(
			'posts'      => $this->blog_model->published($per_page, $offset, $category),
			'pager'      => $this->pagination->create_links(),
			'categories' => $this->blog_model->categories(),
			'active_cat' => $category,
		));
	}

	/** Single article. */
	public function detail($slug)
	{
		$post = $this->blog_model->by_slug($slug);
		if ( ! $post) show_404();

		$this->blog_model->add_view($post['id']);
		$author = $post['author_id'] ? $this->user_model->get($post['author_id']) : NULL;

		$this->meta(array(
			'title'       => ($post['meta_title'] ?: $post['title'].' — Bloom Iris Journal'),
			'description' => ($post['meta_desc'] ?: excerpt($post['excerpt'], 30)),
			'image'       => upload_url($post['cover_image']),
		));

		$this->render('blog/detail', array(
			'post'   => $post,
			'author' => $author,
			'recent' => $this->blog_model->recent($post['id'], 3),
		));
	}

	/** CI pagination styling config. */
	private function _pagination_config($base, $total, $per_page)
	{
		return array(
			'base_url'     => $base,
			'total_rows'   => $total,
			'per_page'     => $per_page,
			'uri_segment'  => substr_count(str_replace(base_url(), '', $base), '/') + 1,
			'num_links'    => 2,
			'use_page_numbers' => FALSE,
			'full_tag_open'   => '<div class="pagination">',
			'full_tag_close'  => '</div>',
			'cur_tag_open'    => '<span class="page-cur">',
			'cur_tag_close'   => '</span>',
			'num_tag_open'    => '<span class="page-num">',
			'num_tag_close'   => '</span>',
			'next_link'       => 'Next →',
			'prev_link'       => '← Prev',
			'first_link'      => FALSE,
			'last_link'       => FALSE,
		);
	}
}
