<?php

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

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

    protected $crud;

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

        // Load language file
        $this->load->library('gettext_language');
        $this->gettext_language->load(__DIR__ . '/../language/' . $this->config->item('language') . '.po');

        // Acceess check
        if (!$this->rt_user->isAllowed('product', 'view_product')) {
            $this->admin_lib->show_denied();
        }
        if (!$this->rt_user->isAllowed('product', 'edit_product')) {
            $this->crud->unset_action('edit');
            $this->crud->unset_action('delete');
            $this->crud->unset_action('add');
        }
    }

    public function render()
    {
        $this->crud->set_table('product_group');
        $this->crud->columns('name, view_order');
        $this->crud->fields('name, view_order, attributes, id_resource_type_page');

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

        if (!$this->crud->is_grid()) {
            $this->crud->callback_after_edit(function($post, $id) {
                $ci = & get_instance();
                $page = 'mconfig/index/product/products/' . $id;
                $q = $ci->db->where('page', $page)->get('admin_menu')->row_array();
                if (empty($q)) {
                    $parent = $ci->db->select('id_admin_menu')->where('name', 'Products')->get('admin_menu')->row_array();
                    if (empty($parent)) {
                        $ci->db->insert('admin_menu', array(
                            'name'         => 'Products',
                            'page'         => 'mconfig/index/product/products/',
                            'parent_id'    => 0,
                            'view_order'   => '1',
                            'image'        => 'fa-product-hunt',
                            'acl_resource' => 'product',
                            'acl_action'   => 'view_product',
                            'active'       => true,
                        ));

                        $parent['id_admin_menu'] = $this->db->insert_id();
                    }

                    $ci->db->insert('admin_menu', array(
                        'name'         => $post['name'],
                        'page'         => $page,
                        'parent_id'    => $parent['id_admin_menu'],
                        'view_order'   => $post['view_order'],
                        'acl_resource' => 'product',
                        'acl_action'   => 'view_product',
                        'active'       => true,
                    ));
                }
            });
        } else {
            $this->crud->before_action('delete', array($this, 'before_delete'));
        }

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

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

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

    public function before_delete($items = array())
    {
        $ids = array_map(function($v) {
            return 'mconfig/index/product/products/' . $v;
        }, $items);

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

        return TRUE;
    }

    protected function callbacks()
    {
        $this->crud->callback('name', 'rtgc_edit_link');
        $this->crud->callback('view_order', 'spinner');
        $this->load->library('product/callback/rtgc_set_relation_n_n');
        $this->crud->set_relation_n_n('attributes', 'product_group_linker', 'product_attr', 'name');
        $this->load->library('resmng/respage_rtgrid', [
            'crud'                           => $this->crud,
            'alias_field'                    => 'name',
            'id_resource_type_page_template' => $this->config->item('product_group_page_template'),
            'parent_id'                      => $this->config->item('product_group_page_parent_id'),
            'route'                          => $this->config->item('product_group_page_route'),
            'private'                        => false
        ]);

        return $this;
    }

    protected function display_as()
    {
        $this->crud->display_as('name', $this->lang->line('Name'));
        $this->crud->display_as('view_order', $this->lang->line('View order'));
        $this->crud->display_as('attributes', $this->lang->line('Attributes'));

        return $this;
    }

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

        $this->crud->attach(make_rtgrid_add_obs('product', $action, $this->lang->line('Product template was added') . $moreBtn));
        $this->crud->attach(make_rtgrid_edit_obs('product', $action, $this->lang->line('Product template was edited') . $moreBtn));
        $this->crud->attach(make_rtgrid_delete_obs('product', $action, $this->lang->line('Product template was deleted')));

        return $this;
    }

}
