<?php

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

class sitemap_install extends MX_Controller {

    protected $module_config = array();

    public function __construct() {
        $this->lang->load('sitemap/install');
        // Set acl module name
        $this->module_config['module_acl_name'] = 'sitemap';
        // Set title
        $this->module_config['module_title'] = $this->lang->line('module_name');
        // Set actions
        $this->module_config['module_actions'] = $this->lang->line('module_actions');
        // Set menu items
        $this->module_config['module_menu_items'] = $this->lang->line('module_menu_items');
    }
    
    public function install() {
        // Create table
        $file = dirname(__DIR__) . '/data/install.sql';
        if (file_exists($file)) {
            $sql = file_get_contents($file);
            foreach (explode(';', trim($sql)) as $table) {
                if (!empty($table)) {
                    $this->db->query($table);
                }
            }
        }

        $this->load->library('ciext/installer');
        $this->installer->install($this->module_config['module_acl_name'], $this->module_config['module_title'], $this->module_config['module_actions'], $this->module_config['module_menu_items']);
        
        // Add route
        $file = 'application/config/routes.php';
        $data = file_get_contents($file);
        if (!strpos($data, '// Sitemap')) {
            $route = '// Sitemap' . PHP_EOL
                    . '$route[\'sitemap.xml\'] = \'sitemap/sitemap_site/show_sitemap\';' . PHP_EOL . PHP_EOL
                    . '// Redirect to core module';
            $data = str_replace('// Redirect to core module', $route, $data);
            file_put_contents($file, $data);
        }

        return array('content' => $this->lang->line('module_installed'), 'title' => $this->module_config['module_title']);
    }

    public function uninstall() {
        $this->load->library('ciext/installer');
        $this->installer->uninstall($this->module_config['module_acl_name']);
        
        // Remove route
        $file = 'application/config/routes.php';
        $route = '// Sitemap' . PHP_EOL
                . '$route[\'sitemap.xml\'] = \'sitemap/sitemap_site/show_sitemap\';' . PHP_EOL . PHP_EOL;
        file_put_contents($file, str_replace($route, '', file_get_contents($file)));

        return array('content' => $this->lang->line('module_removed'), 'title' => $this->module_config['module_title']);
    }

}
