<?php

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

/**
 * Description of Build_link
 *
 * @author Olexandr Vlasiuk
 */
class Build_link
{

    public function set_link($file = '', $array = [])
    {
        preg_match_all('|{{{doc_link_(.*)}}}|U', $file, $substrs);
        foreach ($substrs[1] as $substr) {
            $link[$substr] = trim($this->build($array, $substr, ''), '/');
            if (!empty($link[$substr])) {
                $link[$substr] = '<a href="' . '/' . get_instance()->config->item('admin_page') . '/mconfig/index/ciext_help/index?page=' . $link[$substr] . '">>>></a>';
            }
        }
        foreach ($link as $k => $v) {
            $file = str_replace('{{{doc_link_' . $k . '}}}', $v, $file);
        }

        return $file;
    }

    protected function build($array = [], $key = '', $path = '')
    {
        foreach ($array as $k => $item) {
            if ($k == $key) {

                return $path . '/' . $k;
            } else {
                if (is_array($item)) {
                    $link = $this->build($item, $key, $path . (($k != 'pages') ? '/' . $k : ''));
                    if (!empty($link)) {

                        return $link;
                    }
                }
            }
        }

        return '';
    }

    public function get_path($array = [], $key = '', $path = '')
    {
        foreach ($array as $k => $item) {
            if (!empty($item['uri']) && strpos($key, $item['uri'])) {
                $base_link = $path . '/' . $k;
                if (empty($item['pages'])) {
                    
                    return $base_link;
                } else {
                    $link = $this->get_path($item, $key, $base_link);

                    return $link ?: $base_link;
                }
            } else {
                if (is_array($item)) {
                    $link = $this->get_path($item, $key, $path . (($k != 'pages') ? '/' . $k : ''));
                    if (!empty($link)) {

                        return $link;
                    }
                }
            }
        }

        return '';
    }

}
