<?php

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

class RT_URI extends CI_URI {

    /**
     * Current page
     * @var string 
     */
    public $current_page = 'home';

    /**
     * Current language
     * @var string 
     */
    public $current_language = '';

    function __construct() {
        parent::__construct();
        
        // Parse url and set default params
        $this->_fetch_uri_string();
        preg_match('/([\w]{2}\/)?(['.$this->config->item('permitted_uri_chars').']+)\/?/i', $this->uri_string(), $params);
        $this->current_language = (!empty($params[1])) ? strtolower(str_replace('/', '', $params[1])) : $this->config->item('language_short');
        $this->current_page = (isset($params[2])) ? $params[2] : $this->current_page;

        $allowed_lang = $this->config->item('allowed_language');
        
        // Redirect if lang prefix and base lang prefix same
        if (!empty($params[1]) && $this->current_language == $this->config->item('language_short')) {
            header("Location: /" . $this->current_page, TRUE, 302);
            exit;
        }
        
        // Set language
        $interface = (isset($allowed_lang[$this->current_language])) ? $allowed_lang[$this->current_language] : $this->config->item('language');
        $this->config->set_item('language', $interface);
    }

    /**
     * Get parameter from url
     * @param string $key
     * @return string
     */
    public function get_url_param($key = 0) {
        $n = (strlen($this->segment(1)) == 2) ? 3 : 2;
        $url_params = $this->uri_to_assoc($n);
        
        return (isset($url_params[$key])) ? $url_params[$key] : FALSE;
    }
    
    /**
     * Get next segment
     * @param string $key
     * @return mixed - if find then string else FALSE
     */
    public function get_next_segment($key = '') {
        if (!empty($key) && array_key_exists($key, $this->_get_next_segment)) {
            
            return $this->_get_next_segment[$key];
        }
        
        $matches = array();
        preg_match('/\/' . $key . '\/([^\/]*)/', '/'.$this->uri_string(), $matches);
        
        $this->_get_next_segment[$key] = (!empty($matches[1])) ? $matches[1] : FALSE;
        
        return $this->_get_next_segment[$key];
    }
    
    /**
     * Cache
     * @var array
     */
    protected $_get_next_segment = array();

}
