<?php

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

/**
 * Description of site_menu_model
 *
 * @author Igor Ratsun
 */
class site_menu_model extends CI_Model {

    protected $get_parent = array(0 => '---');
    protected $items_from_db = NULL;
    protected $configuration = NULL;
    protected $breadcrumbs_last_item = '';
    
    public function get_breadcrumbs_last_item() {
        return $this->breadcrumbs_last_item;
    }
    
    /**
     * Set last item to breadcrumbs
     * @param string $page - name of current page
     * @param boolean $force - if TRUE then forced replace last item
     */
    public function set_breadcrumbs_last_item($page, $force = FALSE) {
        if (empty($this->breadcrumbs_last_item) || $force) {
            $this->breadcrumbs_last_item = $page;
        }
    }

    protected function _get_parents() {
        if ($this->get_parent == array(0 => '---')) {
            $id_type = $this->get_menu_type();
            $sql = $this->db->
                            select('sm.id_site_menu, smt.name')->
                            where('sm.id_site_menu_type', $id_type)->
//                            where('sm.active', TRUE)->
                            where('sm.id_site_menu = smt.id_site_menu')->
                            where('lan.id_lan = smt.id_lan')->
                            where('lan.short_name', $this->uri->current_language)->
                            get('site_menu sm, site_menu_translate smt, lan')->result_array();
            foreach ($sql as $value) {
                $this->get_parent[$value['id_site_menu']] = $value['name'];
            }
        }

        return $this->get_parent;
    }

    public function get_parent_column($value, $row) {
        $parents = $this->_get_parents();
        return (isset($parents[$value])) ? $parents[$value] : '';
    }

    public function get_edit_parent_column($name = '', $value = '') {
        $parents = $this->_get_parents();
        $primary_key = intval($this->uri->get_next_segment('edit'));

        $tpl = '<select name="' . $name . '">';
        foreach ($parents as $k => $v) {
            if ($k == $primary_key && $k != 0) {
                continue;
            }
            $tpl .= '<option value="' . $k . '" ' . ($k == $value ? 'selected="selected"' : '') . '>' . $v . '</option>';
        }

        return $tpl . '</select>';
    }

    public function get_pages($name = '', $value = '') {
        $this->load->model('ciext/core_model');

        $data = $this->db->
                        select('name, alias')->
                        where('active', TRUE)->
                        get('resource_type_page')->result_array();
        $html = '<select id="get_pages"><option value="">--- ' . $this->lang->line('Specify manually') . ' ---</option>';
        foreach ($data as $v) {
            $href = str_replace(base_url(), '/', $this->core_model->create_page_url($v['alias']));
            $html .= '<option value="' . $href . '"' . (($href == $value) ? ' selected="selected"' : '') . '>' . $v['name'] . '</option>';
        }
        $html .= '</select>';

        $js = '<div><input type="text" id="get_pages_input" name="' . $name . '" value="' . $value . '" style="display:none; width:80%; margin-top:10px"/></div>
            <script type="text/javascript">
            $(function(){
                if (!$("#get_pages").val()) {
                    $("#get_pages_input").show();
                }
                $("#get_pages").change(function(){
                    var val = $(this).val();
                    if (!val) {
                        $("#get_pages_input").show();
                    } else {
                        $("#get_pages_input").val(val);
                        $("#get_pages_input").hide();
                    }
                });
            });
            </script>';

        return $html . $js;
    }

    public function get_menu_type() {

        $from_route = (int) $this->uri->get_next_segment('manager');

        if (!empty($from_route)) {

            return $from_route;
        }

        // Find first menu in db
        $from_db = $this->db->
                        select('id_site_menu_type')->
                        where('active', TRUE)->
                        get('site_menu_type')->row_array();

        return isset($from_db['id_site_menu_type']) ? $from_db['id_site_menu_type'] : 0;
    }

    public function get_tabs() {
        $active_item = $this->get_menu_type();
        $q = $this->db->
                        select('id_site_menu_type, name')->
                        where('active', TRUE)->
                        get('site_menu_type')->result_array();

        foreach ($q as &$item) {
            $item['class'] = ($item['id_site_menu_type'] == $active_item) ? 'class="active"' : '';
        }
        unset($item);

        return $q;
    }

    public function get_breadcrumbs_array($url_or_parent, $items = array()) {
        $lang = ($this->config->item('language_short') == $this->uri->current_language) ? '' : '/' . $this->uri->current_language;
        foreach ($items as $item) {
            if (!empty($item['href'])) {
                $item['href'] = $lang . $item['href'];
            }
            if ((!empty($url_or_parent) && $item['href'] == $url_or_parent) || $item['id_site_menu'] == $url_or_parent) {
                $rs = array($item);

                return ($item['parent_id'] != 0) ? array_merge($rs, $this->get_breadcrumbs_array((int) $item['parent_id'], $items)) : $rs;
            }
        }

        if (is_string($url_or_parent) && !empty($url_or_parent)) {
            $segments = explode('/', $url_or_parent);
            unset($segments[count($segments) - 1]);

            return $this->get_breadcrumbs_array(implode('/', $segments), $items);
        }

        return FALSE;
    }

    public function select_items($id_type = 0, $active = TRUE) {
        $cache_type = (int) $active;
        if (empty($this->items_from_db[$cache_type][$id_type])) {
            if ($active) {
                $this->db->where('sm.active', TRUE);
            }
            $q = $this->db->
                            select('sm.id_site_menu, smt.name, sm.href, sm.parent_id')->
                            where('sm.id_site_menu = smt.id_site_menu')->
                            where('lan.id_lan = smt.id_lan')->
                            where('lan.short_name', $this->uri->current_language)->
                            where('sm.id_site_menu_type', $id_type)->
                            order_by('sm.view_order, sm.parent_id', 'ASC')->
                            get('site_menu sm, site_menu_translate smt, lan')->result_array();
            
            $this->items_from_db[$cache_type][$id_type] = $q;
        }

        return $this->items_from_db[$cache_type][$id_type];
    }

    public function get_items($id_type = 0) {
        $data = $this->select_items($id_type);
        $config = $this->get_configuration($id_type);
        $active_class = (!empty($config['active_class'])) ? $config['active_class'] : 'active';

        // Prepare data
        $current_page = '/' . $this->uri->uri_string();
        foreach ($data as &$v) {
            if ($this->uri->current_language != $this->config->item('language_short') && !empty($v['href'])) {
                $v['href'] = ($v['href'] == '/') ? '/' . $this->config->item('home_page') : $v['href'];
                $v['href'] = '/' . $this->uri->current_language . $v['href'];
            }
            if ($v['href'] == $current_page) {
                $v['active'] = $active_class;
                $v['href'] = '';
            } else {
                $v['active'] = '';
            }
        }
        unset($v);

        return $this->_get_child($data);
    }
    
    public function get_configuration($id_type = 0) {
        if (empty($this->configuration[$id_type])) {
            $this->configuration[$id_type] = $this->db->
                    select('active_class, template')->
                    where('id_site_menu_type', (int) $id_type)->
                    where('active', TRUE)->
                    get('site_menu_type')->row_array();
            
        }
        
        return $this->configuration[$id_type];
    }

    protected function _get_child(&$data, $parent_id = 0, $level = 0) {
        $level++;
        $return = array();
        foreach ($data as $item) {
            if ($item['parent_id'] == $parent_id) {
                $children = $this->_get_child($data, $item['id_site_menu'], $level);
                $return[] = array(
                    'level_' . $level => $children,
                    'remove_marker_start' => (empty($children)) ? '{remove_marker_start}' : '',
                    'remove_marker_end' => (empty($children)) ? '{remove_marker_end}' : '',
                    'id' => $item['id_site_menu'],
                    'name' => $item['name'],
                    'href' => $item['href'],
                    'active_menu_item_class' => $item['active']
                );
            }
        }

        return $return;
    }

}
