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

/**
 * Description of site_menu
 *
 * @author Igor Ratsun
 */
class site_menu  extends MX_Controller {
    
    public function index($id = NULL) {
        $this->load->library('ciext/ciext');
        $this->ciext->load_jquery();
        $this->load->model('site_menu/site_menu_model');
        $content = array(
            'level_0' => $this->site_menu_model->get_items((int) $id)
        );
        
        $config = $this->site_menu_model->get_configuration($id);
        if (!empty($config['template'])) {
            $template = $this->parser->parse_string($config['template'], $content, TRUE);
        } else {
            $template = $this->parser->parse('site_menu/template', $content, TRUE);
        }
        
        // Clear class=""
        $template = str_replace('class=""', '', $template);
        
        // Remove markers
        preg_match_all('/\{remove_marker_start\}[\w\W]*?\{remove_marker_end\}?/i', $template, $match);
        if (isset($match[0]) && is_array($match[0])) {
            foreach ($match[0] as $v) {
                $template = str_replace($v, '', $template);
            }
        }

        return $template;
    }
    
    public function breadcrumbs($id = NULL, $last_item = '') {
        $this->lang->load('site_menu/site');
        $this->load->model('site_menu/site_menu_model');
        // Set last item if needed
        if (!empty($last_item)) {
            $this->site_menu_model->set_breadcrumbs_last_item($last_item);
        }
        $url = '/' . $this->uri->uri_string();
        $items = $this->site_menu_model->select_items((int) $id, FALSE);
        $breadcrumbs = $this->site_menu_model->get_breadcrumbs_array($url, $items);
        $breadcrumbs[1000] = array(
            'href' => ($this->config->item('language_short') == $this->uri->current_language) ? '/' : '/' . $this->uri->current_language . '/' . $this->config->item('home_page'),
            'name' => $this->lang->line('Home')
        );
        krsort($breadcrumbs);
        
        if (isset($breadcrumbs[0]['href']) && $breadcrumbs[0]['href'] == $url) {
            $this->site_menu_model->set_breadcrumbs_last_item($breadcrumbs[0]['name']);
            unset($breadcrumbs[0]);
        }
        
        $content = array(
            'sub_items' => $breadcrumbs,
            'current' => $this->site_menu_model->get_breadcrumbs_last_item()
        );
        
        return $this->parser->parse('site_menu/breadcrumbs', $content, TRUE);
    }
}
