<?php

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

/**
 * CRUD model
 *
 * @author CIEXT skeleton
 */
class Post_category_crud extends \Ciext\Model\AbstractEventModel
{

    protected $crud;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('rtgrid/rtgrid_api');
        $this->crud = new rtgrid_api();

        // Access check
        if (!$this->rt_user->isAllowed('post', 'view_post')) {
            $this->admin_lib->show_denied();
        }
        if (!$this->rt_user->isAllowed('post', 'edit_category')) {
            $this->crud->unset_action('edit');
            $this->crud->unset_action('delete');
            $this->crud->unset_action('add');
        }

        $this->config->load('post/config');
    }

    public function render()
    {
        $this->crud->set_table('post_category');
        $this->crud->columns('translate_title, view_order, active');
        $this->crud->fields('view_order, id_resource_type_page');

        $this->crud->required_fields('translate_title');

        if (!$this->crud->is_grid()) {
            $this->crud->callback_after_edit(function ($post, $id) {
                $ci = &get_instance();

                $ci->load->library('db_lang_lib');
                $id_lan = $ci->db_lang_lib->get_current_lang_id();
                $title = $ci->db->select('title')
                    ->where([
                        'id_post_category' => $id,
                        'id_lan' => $id_lan,
                    ])
                    ->get('post_category_translate')
                    ->row_array();

                $page = 'mconfig/index/post/posts/' . $id;
                $menu = $ci->db->select('id_admin_menu')->where(['page' => $page, 'acl_resource' => 'post'])->get('admin_menu')->row_array();
                $parent = $ci->db->select('id_admin_menu')->where(['parent_id' => 0, 'acl_resource' => 'post'])->get('admin_menu')->row_array();
                $data = [
                    'name'         => $title['title'],
                    'page'         => $page,
                    'parent_id'    => $parent['id_admin_menu'],
                    'view_order'   => $post['view_order'],
                    'acl_resource' => 'post',
                    'acl_action'   => 'view_post',
                    'active'       => true,
                ];
                if (empty($menu)) {
                    $ci->db->insert('admin_menu', $data);
                } else {
                    $ci->db->update('admin_menu', $data, ['id_admin_menu' => $menu['id_admin_menu']]);
                }
            });
        } else {
            $this->crud->join('resource_type_page rtp', 'rtp.id_resource_type_page=post_category.id_resource_type_page', 'left');

            $this->crud->before_action('delete', function ($items) {
                $ids = array_map(function ($v) {
                    return 'mconfig/index/post/posts/' . $v;
                }, $items);

                get_instance()->db->where_in('page', $ids)->delete('admin_menu');

                return true;
            });
        }

        $this->callbacks()->display_as()->observers();

        // Notify
        $this->notify(__FUNCTION__, ['crud' => $this->crud]);

        return $this->crud->render();
    }

    protected function callbacks()
    {
        $this->crud->multilang(new multilang('translate_title', 'post_category_translate', 'title', function($name, $value){
            return (new \Rtgc_edit_link())->field($name, $value);
        }));
        $this->crud->callback('translate_title', 'rtgc_edit_link');
        $this->crud->callback('view_order', 'rtgc_view_order', ['crud' => $this->crud]);
        $this->crud->callback('active', 'rtgc_active');
        $this->load->library('resmng/respage_rtgrid', [
            'crud'                           => $this->crud,
            'alias_field'                    => 'translate_title',
            'id_resource_type_page_template' => $this->config->item('post_category_id_resource_type_page_template'),
            'parent_id'                      => $this->config->item('post_category_parent_id'),
            'route'                          => 'page\/\d+',
        ]);

        return $this;
    }

    protected function display_as()
    {
        $this->crud->display_as('translate_title', $this->lang->line('Title'));
        $this->crud->display_as('view_order', $this->lang->line('View order'));
        $this->crud->display_as('active', $this->lang->line('Published'));
        $this->crud->display_as('id_resource_type_page', $this->lang->line('Page'));

        return $this;
    }

    protected function observers()
    {
        $this->load->helper('rtgrid/rtgrid_obs');
        $action = 'edit_category';
        $moreBtn = ' <a href="{link}">>>></a>';

        $this->crud->attach(make_rtgrid_add_obs('post', $action, $this->lang->line('Post category was added') . $moreBtn));
        $this->crud->attach(make_rtgrid_edit_obs('post', $action, $this->lang->line('Post category was edited') . $moreBtn));
        $this->crud->attach(make_rtgrid_delete_obs('post', $action, $this->lang->line('Post category was deleted')));

        return $this;
    }

}
