<?php

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

/**
 * Description of page_rtgrid_pi
 *
 * @author Igor Ratsun
 * @example 
  $this->crud->fields('id_resource_type_page, name');
  $this->load->library('resmng/respage_rtgrid', array(
  'crud'                           => $this->crud,
  'alias_field'                    => 'title', // value from this crud`s field will automatically insert in page data
  'id_resource_type_page_template' => 5,       // `id_resource_type_page_template` from table `resource_type_page_template`
  'parent_id'                      => 51,      // `parent_id` from table `resource`
  'route'                          => '',      // optional
  'private'                        => FALSE,   // optional
  ));
 */
class respage_rtgrid
{

    protected $ci;
    protected $crud;
    protected $id_resource_type_page_template;
    protected $parent_id;
    protected $route = '';
    protected $id_resource_type = 3;
    protected $private = FALSE;
    protected $alias_field = FALSE;

    public function __construct($param = array())
    {
        // Check params
        if (empty($param['crud'])) {
            show_error('Param `crud` required');
        }
        if (empty($param['id_resource_type_page_template'])) {
            show_error('Param `id_resource_type_page_template` required');
        }
        if (empty($param['parent_id'])) {
            show_error('Param `parent_id` required');
        }

        $this->crud = $param['crud'];
        $this->id_resource_type_page_template = $param['id_resource_type_page_template'];
        $this->parent_id = $param['parent_id'];

        if (isset($param['route'])) {
            $this->route = $param['route'];
        }
        if (isset($param['id_resource_type'])) {
            $this->id_resource_type = $param['id_resource_type'];
        }
        if (isset($param['private'])) {
            $this->private = $param['private'];
        }
        if (!empty($param['alias_field']) && !$this->crud->is_grid()) {
            if (strpos($this->crud->get_fields(), $param['alias_field']) === FALSE) {
                show_error('Field `' . $param['alias_field'] . '` not found in crud fields');
            }
            $this->alias_field = $param['alias_field'];
        }


        $this->ci = & get_instance();

        $this->ci->lang->load('resmng/respage_rtgrid');

        if (!$this->crud->is_grid()) {
            // Check fields
            if (strpos($this->crud->get_fields(), 'id_resource_type_page') === FALSE) {
                show_error('Field `id_resource_type_page` must be in fields list');
            }

            $this->ci->load->library('db_lang_lib');
            $this->crud->add_tab($this->ci->lang->line('Page data'), $this->ci->parser->parse('resmng/libraries/page_data', array(
                        'langs' => $this->ci->db_lang_lib->get_lang_by_id(),
                        'item'  => $this->get_page_values($this->ci->uri->get_next_segment('edit')),
                            ), TRUE
                    ), 1000);
            $this->crud->callback_before_edit(array($this, 'callback_page_before_edit'));

            $this->crud->callback_field('id_resource_type_page', function($name, $value) {
                $this->ci->js_css->add_js_string(
                        '$(function(){'
                        . ' $(\'input[name=' . $name . ']\').parent().parent().hide();'
                        . ' $(\'.btn[name=rtgrid_action_add], .btn[name=rtgrid_action_add_and_next], .btn[name=rtgrid_action_save], .btn[name=rtgrid_action_save_and_back_to_list]\').click(function(){'
                        . '  if ($(\'input[name="page_data[admin_name]"]\').val() == \'\' || $(\'input[name="page_data[alias]"]\').val() == \'\') {'
                        . '  $(\'#myTab a[href="#\' + $(\'input[name="page_data[admin_name]"]\').parents(".tab-pane").attr("id")).click();'
                        . '  }'
                        . ' });'
                        . (!empty($this->alias_field) ?
                                ' $(\'input[name="page_data[admin_name]"\').parent().parent().hide();'
                                . ' $(\'input[name="' . $this->crud->_field_alias($this->alias_field) . '"\').change(function(){'
                                . '  $(\'input[name="page_data[admin_name]"\').val($(this).val());'
                                . '  if ($(\'input[name="page_data[alias]"\').val() == \'\') {'
                                . '   $(\'input[name="page_data[alias]"\').val($(this).val());'
                                . '  }'
                                . ' });' : ''
                        )
                        . '});'
                );
                return '<input type="hidden" name="' . $name . '" value="' . $value . '" />';
            });
        } else {
            $this->crud->before_action('delete', array($this, 'before_delete_page'));
        }
    }

    public function get_page_values($item_id = 0)
    {
        if ($this->ci->input->post('page_data')) {

            return $this->ci->input->post('page_data');
        }
        $db = clone $this->ci->db;
        $q = $db->
                        select('p.name, p.alias, p.active, pd.id_lan, pd.seo_title, pd.seo_keywords, pd.seo_description')->
                        join('resource_type_page_data pd', 'pd.id_resource_type_page=p.id_resource_type_page', 'left')->
                        where('p.id_resource_type_page = s.id_resource_type_page', '', FALSE)->
                        where('s.id_' . $this->crud->get_table(), (int) $item_id)->
                        get('resource_type_page p, ' . $this->crud->get_table() . ' s')->result_array();
        $rs = array(
            'admin_name' => '',
            'alias'      => '',
            'active'     => '',
            'seo'        => array(),
        );
        if (!empty($q)) {
            foreach ($q as $v) {
                $rs['admin_name'] = $v['name'];
                $rs['alias'] = $v['alias'];
                $rs['active'] = $v['active'];
                $rs['seo'][$v['id_lan']]['title'] = $v['seo_title'];
                $rs['seo'][$v['id_lan']]['keywords'] = $v['seo_keywords'];
                $rs['seo'][$v['id_lan']]['desc'] = $v['seo_description'];
            }
        }

        return $rs;
    }

    public function callback_page_before_edit($post = array())
    {
        $db = clone $this->ci->db;
        $page_data = $this->ci->input->post('page_data');

        // Check id_resource_type_page
        $check = $db->select('id_resource_type_page')
                ->where('id_resource_type_page', (int) $post['id_resource_type_page'])
                ->get('resource_type_page')
                ->row_array();
        $id_resource_type_page = !empty($check['id_resource_type_page']) ? $check['id_resource_type_page'] : 0;

        if (!empty($page_data['admin_name']) && !empty($page_data['alias'])) {
            $config = array(
                'id_resource_type_page_template' => $this->id_resource_type_page_template,
            );
            $resource_type_page = array(
                'name'                           => $page_data['admin_name'],
                'id_resource_type_page_template' => $config['id_resource_type_page_template'],
                'alias'                          => $this->preparePageAlias($page_data['alias'], $id_resource_type_page),
                'route'                          => $this->route,
                'active'                         => (int) $page_data['active']
            );
            // Edit resource_type_page
            if (!empty($id_resource_type_page)) {
                $db->where('id_resource_type_page', $id_resource_type_page)->update('resource_type_page', $resource_type_page);
                $resource_type_page['id_resource_type_page'] = $id_resource_type_page;
            } else {
                $db->insert('resource_type_page', $resource_type_page);
                $resource_type_page['id_resource_type_page'] = $db->insert_id();
            }
            // clear $resource_type_page_data
            $db->where('id_resource_type_page', $resource_type_page['id_resource_type_page'])->delete('resource_type_page_data');
            // add new resource_type_page_data
            $resource_type_page_data = array();
            foreach ($page_data['seo'] as $id_lan => $val) {
                $resource_type_page_data[] = array(
                    'id_resource_type_page' => $resource_type_page['id_resource_type_page'],
                    'id_lan'                => $id_lan,
                    'seo_title'             => $val['title'],
                    'seo_keywords'          => $val['keywords'],
                    'seo_description'       => $val['desc'],
                );
            }
            $db->insert_batch('resource_type_page_data', $resource_type_page_data);

            // Add data to resource table if no exist
            $data = array(
                'id_item'          => $resource_type_page['id_resource_type_page'],
                'id_resource_type' => $this->id_resource_type,
                'parent_id'        => $this->parent_id,
                'private'          => $this->private,
            );
            $where = array(
                'id_item'          => $resource_type_page['id_resource_type_page'],
                'id_resource_type' => $this->id_resource_type,
            );
            $q = $db->where($where)->get('resource')->row_array();
            if (empty($q)) {
                $db->insert('resource', $data);
            } else {
                $db->where($where)->update('resource', $data);
            }

            $post['id_resource_type_page'] = $resource_type_page['id_resource_type_page'];
        }

        return $post;
    }

    public function before_delete_page($items = array())
    {
        $db = clone $this->ci->db;
        $q = $db->
                        select('id_resource_type_page')->
                        where_in('id_' . $this->crud->get_table(), $items)->
                        get($this->crud->get_table())->result_array();

        if (!empty($q)) {
            // Delete from resource
            foreach (array_column($q, 'id_resource_type_page') as $item) {
                $data = array(
                    'id_item'          => $item,
                    'id_resource_type' => $this->id_resource_type,
                );
                $db->where($data)->delete('resource');
            }

            // add new resource_type_page_data
            $db->where_in('id_resource_type_page', array_column($q, 'id_resource_type_page'))->delete('resource_type_page_data');

            // add new resource_type_page
            $db->where_in('id_resource_type_page', array_column($q, 'id_resource_type_page'))->delete('resource_type_page');
        }

        return TRUE;
    }

    protected function preparePageAlias($alias = '', $id_resource_type_page = 0)
    {
        $newAlias = url_title(str_replace(base_url(), '', $alias), 'dash', TRUE);

        // Check for existing in table
        $db = clone $this->ci->db;
        $check = $db->
                        select('id_resource_type_page')->
                        where('BINARY(alias)=' . $db->escape($newAlias), '', FALSE)->
                        where('id_resource_type_page<>' . (int) $id_resource_type_page, '', FALSE)->
                        get('resource_type_page')->row_array();
        if (!empty($check)) {

            return $this->preparePageAlias($newAlias . '-1', $id_resource_type_page);
        }

        return $newAlias;
    }

}
