<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Description of Post_tmodel
 *
 * @author CIEXT skeleton
 */
class Post_tmodel extends \Ciext\Model\AbstractTableModel
{

    protected $table = 'post';
    protected $pkey = 'id_post';
    protected $select = 't.id_post, pt.title, t.thumbnail, rtp.alias, rtpd.updated, pct.title as category_title, rtpc.alias as category_alias';
    protected $cache = [];
    protected $id_lan = 1;

    public function __construct()
    {
        $this->load->library('db_lang_lib');
        $this->id_lan = $this->db_lang_lib->get_current_lang_id();
    }

    public function fetch_page($page = 1, $limit = 1)
    {
        $this->prepare()->order_by('rtpd.updated', 'desc');

        return parent::fetch_page($page, $limit);
    }

    public function count()
    {
        $this->prepare();

        return parent::count();
    }

    public function fetch_current()
    {
        if (empty($this->cache['fetch_current'])) {
            $items = $this
                ->set_predicates(['t.id_resource_type_page' => $this->core_model->get_current_page_id()])
                ->set_select($this->get_select() . ', pt.content')
                ->fetch_page(1, 1);
            $this->cache['fetch_current'] = !empty($items[0]) ? $items[0] : [];
        }

        return $this->cache['fetch_current'];
    }

    protected function prepare()
    {
        $id_lan = $this->load->library('db_lang_lib')->get_current_lang_id();

        return $this->db
            ->join('post_translate pt', '(pt.id_post = t.id_post AND pt.id_lan = ' . $this->id_lan . ')', 'left')
            ->join('resource_type_page rtp', 'rtp.id_resource_type_page = t.id_resource_type_page', 'left')
            ->join('resource_type_page_data rtpd', 'rtpd.id_resource_type_page=t.id_resource_type_page and rtpd.id_lan=' . $id_lan, 'left')
            ->join('resource r', 'r.id_item = t.id_resource_type_page AND r.id_resource_type = 3', 'left')
            ->join('resource rc', 'rc.id_resource = r.parent_id', 'left')
            ->join('post_category pc', 'pc.id_resource_type_page = rc.id_item', 'left')
            ->join('post_category_translate pct', '(pct.id_post_category = pc.id_post_category AND pct.id_lan = ' . $this->id_lan . ')', 'left')
            ->join('resource_type_page rtpc', 'rtpc.id_resource_type_page = pc.id_resource_type_page', 'left')
            ->where([
                'rtp.active'  => 1,
                'rtpc.active' => 1,
            ])
            ->where('pt.title IS NOT NULL');
    }

}
