<?php

include_once dirname(__DIR__) . '/libraries/sitemap.php';

class sitemap_model_site extends CI_Model
{

    public function generate()
    {

        $sitemap_modules = $this->get_modules();

        $liba = array();

        foreach ($sitemap_modules as $v) {
            $module = $v . '_sitemap_api';
            $this->load->library($v . '/' . $module);
            $liba = array_merge($liba, $this->{$module}->get_mudule_map());
        }

        return $liba;
    }

    public function get_modules()
    {
        $sitemap_modules = array();

        $query = $this->db->
                        select('acl_resource_name')->
                        order_by('id_acl_resource', 'DESC')->
                        where('active', TRUE)->
                        get('acl_resource')->result_array();

        if (!empty($query)) {
            foreach ($query as $v) {
                foreach (array_keys($this->config->item('modules_locations')) as $loc) {
                    if (file_exists($loc . $v['acl_resource_name'] . '/libraries/' . $v['acl_resource_name'] . '_sitemap_api.php')) {
                        $sitemap_modules[] = $v['acl_resource_name'];
                    }
                }
            }
        }
        return $sitemap_modules;
    }

    public function get_links($data = array())
    {

        $query = $this->db->
                        select('id_resource_type_page, name, alias')->
                        order_by('id_resource_type_page', 'ASC')->
                        where('active', TRUE)->
                        get('resource_type_page')->result_array();

        $data = $this->generate();

        $str = '<ul>';
        foreach ($query as $v) {
            if (array_key_exists($v['id_resource_type_page'] . '_html', $data)) {
                $html = $data[$v['id_resource_type_page'] . '_html']->get_html();
                if (!empty($html)) {
                    $str.= $html;
                }
            } else {
                $str.='<li><a href="' . base_url($v['alias']) . '">' . $v['name'] . '</a></li>';
            }
        }
        $str.= '</ul>';

        return $str;
    }

}
