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

class Seo extends Comdono_Controller {

	function __construct()
	{
		parent::__construct();
        
		$this->load->helper('comdono/comdono');
		$this->load->model('busca_model');
		$this->load->model('site_model');
		$this->load->model('blog/blog_model');
	}
    
    public function sitemap()
    {
        $data['urls'] = [];
        
        //diversos
        $cad_sitemap = $this->db->get('cad_sitemap')->result()??[];
        foreach ($cad_sitemap as $sitemap)
        {
            $data['urls'][] = $this->montaUrl(base_url($sitemap->uri));
        }
        
        //imoveis - lancamento
        $imoveis = $this->busca_model->getImoveis();
        foreach ($imoveis as $id_imovel=>$imovel)
        {
            //$data['urls'][] = $this->montaUrl(base_url('imovel/'.$id_imovel.'/'.$imovel->key_anuncio));
            //if($imovel->id_imovel_rel == 0 && $imovel->lancamento == "Sim")
            if($imovel->lancamento == "Sim")
            {
                $key = HImovel::montaKeyLancamento($imovel);
                $data['urls'][] = $this->montaUrl(base_url('lancamento/'.$id_imovel.'/'.$key));
            }
            else
            {
                $data['urls'][] = $this->montaUrl(base_url('imovel/'.$id_imovel.'/'.$imovel->key_anuncio));
            }
        }
        
        //blog
        $posts = $this->blog_model->get_postagens();
        foreach ($posts as $post)
        {
            $data['urls'][] = $this->montaUrl(base_url('blog/postagem/'.strtolower($post['key'])));
        }
        
        //ajuda
        $categorias = $this->site_model->get_faqs();
        foreach ($categorias as $cat)
        {
            foreach($cat->perguntas as $idPerg=>$perg)
            {
                $titulo =  trim(str_replace(['<p><meta charset="utf-8" />','</p>'], '', $perg->pergunta) );
                $key = convertAccentsAndSpecialToNormal(strtolower($titulo));
                $data['urls'][] = $this->montaUrl(base_url('ajuda/'.$perg->id_perg.'/'.$key));
            }
        }
        
        Template::load_view('sitemap_view', $data, '', '', $conteudo);
        
        echo file_put_contents('sitemap.xml', $conteudo);
    }
    
    private function montaUrl($url)
    {
        return (object) [
				'loc' => $url,
				'lastmod' => date('Y-m-d', time()),
				'changefreq' => 'monthly',
				'priority' => 0.85
			];
    }
    
}