<?php

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

class sitemap_admin_model extends CI_Model
{

    public function prepare_sitemap()
    {
        $data = $this->get_sitemap_data();

        $links = array();

        foreach ($data as $item) {
            $loc = $item->get_loc();
            if (!empty($loc)) {
                if (!$this->getResponse($item->get_loc())) {
                    $links[] = $item->get_loc();
                }
            }
        }
        if (!empty($links)) {
            $this->set_error_links(array_unique($links));
        }

        return array('status' => TRUE);
    }

    public function generate()
    {
        $this->createXML($this->get_sitemap_data());

        return TRUE;
    }

    /**
     * Set error links to DB
     * 
     * @param array $data
     * @return void
     */
    protected function set_error_links($data)
    {
        $this->db->query('DELETE FROM sitemap_error_link');

        foreach ($data as $link) {
            $this->db->insert('sitemap_error_link', array('link' => $link));
        }
    }

    /**
     * Get error links to DB
     * 
     * @return array
     */
    public function get_error_links()
    {
        $query = $this->db->
                        select('link')->
                        order_by('id_sitemap_error_link', 'ASC')->
                        get('sitemap_error_link')->result_array();
        $result = array();
        foreach ($query as $link) {
            $result[] = $link['link'];
        }


        return $result;
    }

    /**
     * Check url by curl response 
     * 
     * @param string $url
     * @return boolean
     */
    protected function getResponse($url)
    {
        $result = TRUE;

        $curlObj = curl_init();
        curl_setopt($curlObj, CURLOPT_URL, $url);
        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curlObj);
        $httpCode = curl_getinfo($curlObj, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            $result = FALSE;
        }
        curl_close($curlObj);

        if (strpos($response, 'content="noindex') !== false) {
            $result = FALSE;
        }

        return $result;
    }

    /**
     * Get all sitemap data from project
     * 
     * @return array
     */
    protected function get_sitemap_data()
    {
        $sitemap_modules = $this->get_modules();
        $sitemap_modules = array_unique($sitemap_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;
    }

    /**
     * Read robots.txt and return array data
     * 
     * @return array
     */
    protected function get_robots_data()
    {
        $file = dirname(dirname(dirname(dirname(__DIR__)))) . '/robots.txt';
        $result = array();
        if (file_exists($file)) {
            $file_data = file_get_contents($file);

            $file_data = str_replace('User-agent: *', '', $file_data);
            $file_data = str_replace('Host: www.muzokon.ru', '', $file_data);
            $file_data = str_replace('Sitemap: www.muzokon.ru/sitemap.xml', '', $file_data);

            $data = explode('Disallow: *', $file_data);
            foreach ($data as $item) {
                $item = trim($item);
                if (!empty($item)) {
                    $result[] = $item;
                }
            }
        }

        return $result;
    }

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

        $mapdata = '<?xml version="1.0" encoding="UTF-8"?>
                  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        $error_link = $this->get_error_links();
        $robots_data = $this->get_robots_data();

        foreach ($data as $key => $val) {
            $location = $val->get_loc();
            $lastmod = $val->get_lastmod();
            $changefreq = $val->get_changefreq();
            $priority = $val->get_priority();
            foreach ($robots_data as $item) {
                if (strpos($location, $item) !== false) {
                    $location = '';
                }
            }
            if (!empty($location) && !empty($lastmod) && !empty($changefreq) && !empty($priority) && !in_array($location, $error_link)) {
                $mapdata.= '<url><loc>' . $location . '</loc><lastmod>' . $lastmod . '</lastmod><changefreq>' . $changefreq . '</changefreq><priority>' . $priority . '</priority></url>';
            }
        }
        $mapdata.= '</urlset>';

        $this->load->library('ciext/configurator');
        $conf = new configurator();
        $conf->set_resource('sitemap');
        $data = $conf->get_config();

        if (empty($data['cache_life'])) {
            $data['cache_life'] = $this->config->item('cache_life_time');
        }

        $this->cache->save('sitemap_xml', $mapdata, $data['cache_life']);

        return $mapdata;
    }

    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 set_modules($save_array = array())
    {

        if (!empty($save_array)) {

            $this->db->empty_table('sitemap_config');

            foreach ($save_array as $k => $v) {

                $data = array(
                    'module_name' => $k,
                    'changefreq' => $v['changefreq'],
                    'priority' => $v['priority'],
                    'basepage' => $v['basepage']
                );
                $this->db->insert('sitemap_config', $data);
            }
        }
    }

    public function get_modules_db()
    {

        $options = array('always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never');
        $temp = '';

        $pages = $this->get_base_page();

        $sitemap_modules_db = $this->db->
                        select('module_name,changefreq,priority,basepage')->
                        get('sitemap_config')->result_array();

        foreach ($sitemap_modules_db as $k => $v) {


            foreach ($options as $key => $value) {
                if ($value == $v['changefreq']) {
                    $temp.= '<option selected="selected" value="' . $value . '">' . $value . '</option>';
                } else {
                    $temp.= '<option value="' . $value . '">' . $value . '</option>';
                }
            }

            $sitemap_modules_db[$k]['changefreq'] = $temp;
            $temp = '';

            $temp = '<option value="0">---</option>';
            if (!empty($pages)) {
                foreach ($pages as $key => $value) {

                    if ($value['id_resource_type_page'] == $v['basepage']) {
                        $temp.= '<option selected="selected" value="' . $value['id_resource_type_page'] . '">' . $value['name'] . '</option>';
                    } else {
                        $temp.= '<option value="' . $value['id_resource_type_page'] . '">' . $value['name'] . '</option>';
                    }
                }
            }
            $sitemap_modules_db[$k]['basepage'] = $temp;
            $temp = '';
        }

        return $sitemap_modules_db;
    }

    public function get_base_page()
    {

        $sql = $this->db->
                        select('id_resource_type_page, name')->
                        //where('route != ""')->
                        get('resource_type_page')->result_array();

        return $sql;
    }

}
