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

class Imovel extends Comdono_Controller {

	function __construct()
	{
		parent::__construct();
		
		Assets::add_css(array(
            'plugins/owlcarousel2-2.3.4/css/owl.carousel.min',
            'plugins/owlcarousel2-2.3.4/css/owl.theme.default.min',
            
            'plugins/justified-gallery-master/justifiedGallery.min',
            'plugins/fancyBox-v3.5.7/css/jquery.fancybox.min',
        ));
        
        Assets::add_js(array(
            'plugins/owlcarousel2-2.3.4/js/owl.carousel.min',
            
            'plugins/justified-gallery-master/justifiedGallery.min',
            'plugins/fancyBox-v3.5.7/js/jquery.fancybox.min',
        ));
        
        Assets::add_module_js('comdono', array(
            'actions',
            //'login'
        )); 
        
		$this->load->helper('comdono/comdono');
		$this->load->model('busca_model');
	}
    
    public function index()
    {
        Assets::add_css(array(
            'plugins/unitegallery/css/unite-gallery',
            'plugins/unitegallery/css/ug-theme-default',
            'plugins/multiple-emails/css/multiple-emails'
        ));
        
        Assets::add_js(array(
            'plugins/unitegallery/js/unitegallery.min',
            'plugins/unitegallery/js/ug-theme-default',
            'plugins/unitegallery/js/imovel',
            'plugins/morecontent/jquery.morecontent.lite',
            'plugins/multiple-emails/js/multiple-emails',
        ));
        
        Assets::add_module_js('comdono', array(
            'loading_image',
            'carousel_imovel',
            'imovel'
        ));
        $id_imovel = $this->uri->segment(2);
        $key_anuncio = $this->uri->segment(3);
        
        $imovel = $this->busca_model->getImovelById($id_imovel);
        
        
        if($key_anuncio == null && $imovel != null)
           redirect('imovel/'.$id_imovel.'/'.$imovel->key_anuncio);
        if($imovel != null && $key_anuncio != null && $imovel->key_anuncio != $key_anuncio)
           redirect('imovel/'.$id_imovel.'/'.$imovel->key_anuncio);
        
        if($imovel == null){
            $imovel = $this->busca_model->adminGetImovelById($id_imovel);
            if($imovel == null)
                redirect('busca');
            $data['navAdmin'] = true;
        }
           
        $data['imovel'] = $imovel; 
         if($imovel->lancamento == "Sim")
            redirect('lancamento/'.$id_imovel);
        
        
        if($imovel != null)
        {
            $this->session->set_flashdata('referer', 'imovel/'.$id_imovel.'/'.$imovel->key_anuncio);
            
            $link = "";
            if($this->input->get('utm_source', TRUE) !== null)
                $link = "?utm_source=".$this->input->get('utm_source', TRUE)."&utm_medium=".$this->input->get('utm_medium', TRUE)."&utm_campaign=".$this->input->get('utm_campaign', TRUE)."&utm_term=".$this->input->get('utm_term', TRUE)."&utm_content=".$this->input->get('utm_content', TRUE);
            
            $this->session->set_userdata('referer_login', 'imovel/'.$id_imovel.'/'.$imovel->key_anuncio.$link);
            
            $data['arrayImovel'] = HImovel::getDetalhesImovel($imovel);
            $data['arrayCondominio'] = HImovel::getDetalhesComdominio($imovel);
            
            $where1[] = ['bairro',$imovel->bairro];
            $where1[] = [['a.id_imovel !=',$imovel->id_imovel],['lancamento','Sim']];
            $where1[] = ['a.id_imovel_rel',0];
            $data['imoveisBairro'] = $this->busca_model->getImoveis($where1);
            
            $where2[] = ['endereco',$imovel->endereco];
            $where2[] = [['a.id_imovel !=',$imovel->id_imovel],['lancamento','Sim']];
            $where2[] = ['a.id_imovel_rel',0];
            $data['imoveisEndereco'] = $this->busca_model->getImoveis($where2);
            
            $data['contNegociacoes'] = count($this->busca_model->getNegoviacoesImovel($id_imovel));
            
            $contVisualizacoes = $imovel->visualizacoes;
            $data['contVisualizacoes'] = $contVisualizacoes;
            
            $session_visualizacoes = $this->session->session_visualizacoes;
            if(!isset($session_visualizacoes[$id_imovel]) && !($data['navAdmin']??false))
            {
                $session_visualizacoes[$id_imovel] = true;
                $this->session->set_userdata('session_visualizacoes', $session_visualizacoes);
                $contVisualizacoes++;
                $this->busca_model->updateImovel($id_imovel,['visualizacoes'=>$contVisualizacoes]);
            }
            
            $data['imovelFalarComdono'] = (object)[
                'id_imovel' => $imovel->id_imovel,
                'id_cadastro' => $imovel->id_cadastro,
                ];
        }
        
        $data['trigger_click'] = isset($this->session->origem['click_action']) ? $this->session->origem['click_action'] : null;
        
        $data['favoritos'] = $this->busca_model->get_favoritos();
        $data["link"] = base_url().$this->uri->uri_string();
        $data["cadastro"] = $this->cad_model->get_cadastro([], $imovel->id_cadastro);
        
        $data['url'] = $this->loginUrl();
        
        $data['gcaptcha'] = $this->session->gcaptcha;
        $data['public_key'] = $this->db->where('name','captcha_public_key')->get('sys_config')->row()->value;
        
        Template::set_modal($data,[
            'comdono/modal/login_chat_view',
            'comdono/modal/detalhes_imovel_view',
            'comdono/modal/resultado_view',
            'comdono/modal/compartilhar_view'
        ]);
        
        $view = "";
        
        //if($imovel->tipo_empreendimento == 'premium'){
            
            Assets::add_css(array(
                'plugins/player/css/styles'
            ));
            Assets::add_js(array(
                'plugins/player/js/mediaelement-and-player.min'
            ));
            
            //$data['galeria'] = json_encode($imovel->imagens);
            
            $data['imovel']->imagens = Himg::galeriaPremium($imovel->imagens);
            
            $data['galeria'] = json_encode($data['imovel']->imagens);
            
            $view = 'imovel_detalhes_premium_view';
            
            Template::set_modal($data,[
                'comdono/modal/tour_view',
            ]);
            
        //}else{
            //$view = 'imovel_detalhes_view';
        //}
        
        //https://dev.comdono.com/imovel/1189/apartamento-4-quartos-asa-norte-brasilia-df?utm_source=google-ads&utm_medium=text-ads&utm_campaign=apto-wiliam
        
        $origem = [
                'origem'        => 'datelhes_imovel',
                'link'          => base_url(uri_string()),
                'utm_source'    => $this->input->get('utm_source', TRUE),
                'utm_medium'    => $this->input->get('utm_medium', TRUE),
                'utm_campaign'  => $this->input->get('utm_campaign', TRUE),
                'utm_term'      => $this->input->get('utm_term', TRUE),
                'utm_content'   => $this->input->get('utm_content', TRUE),
        ];
        
        $this->session->set_userdata('origem', $origem);
        
        //var_dump($this->session->userdata());die();
        
        $this->loadSeo();
        
        Template::set($data);
        Template::set_view($view);
        Template::render();
    }
    
    private function loadSeo()
    {
        if($this->uri->segment(1) == 'imovel')
	    {
	        $page = $this->uri->segment(1);
            $id_imovel = $this->uri->segment(2);
            $url_page = $this->uri->segment(3);
            $title_page = ucwords(str_replace ("-" , " ", $url_page)); 
            $where[] = [['a.id_imovel',$id_imovel]];
            $data["url_header"] = base_url().$this->uri->uri_string();
            $imovel_header = $this->busca_model->getImovel($where);
            
            if($imovel_header !== NULL){
                $data["page_seo"] = true;
                
                $data["imovel_header"] = $imovel_header;
                $text = "Anuncie ou compre seu imóvel Comdono";
                $description = strip_tags($imovel_header->caracteristicas !== "" ? $imovel_header->caracteristicas : $text);
                
                $description = str_replace("\n", "", $description);
                $description = str_replace("\r", "", $description);
                $description = preg_replace('/\s/',' ',$description);
                $qtd_str = strlen($description);
                
                if ($qtd_str > 230) {
                    $data["imovel_description"] = substr($description,0,227).'...';
                    $description_resumo = substr($description,0,227).'...';
                }else{
                    $data["imovel_description"] = $description;
                }
                
                if($imovel_header->doc_perfil == "cpf"){
                    $data["title_page"] = $title_page." - Compre COMDONO";
                }else{
                    if($imovel_header->tipo_imovel == "Comercial"){
                        $data["title_page"] = "Venda de ".$title_page;
                    }else{
                        $data["title_page"] = "Venda de ".$title_page." - ".$imovel_header->dn_nome_nomefantasia;
                    }
                }
            }
	    }
        
        Template::set($data);
    }
    
    public function cron()
    {
        dd('Deu rum');
        
        $this->load->library('newsletter/newsletter');
        
        $where[] = ['id_imovel_rel', 0];
        $where[] = ['lancamento', ''];
        $imoveis = $this->busca_model->getImoveis($where);
        
        foreach ($imoveis as $imovel)
        {
            $date_anterior = mktime(date("H"), date("i"), date("s"), date("m") - 1, date("d") , date("Y"));
            
            $w = [];
            
            $w[] = ['id_imovel', $imovel->id_imovel];
            $w[] = ['datetime >', $date_anterior];
            $favoritos = $this->busca_model->getFavoritos($w);
            
            $w = [];
            
            $w[] = ['id_imovel', $imovel->id_imovel];
            $w[] = ['data_chat >', $date_anterior];
            $necociacoes = $this->busca_model->getNegoviacoes($w);
            
            $w = [];
            
            $w[] = ['id_imovel', $imovel->id_imovel];
            $w[] = ['data_simulacao >', $date_anterior];
            $simulacoes = $this->busca_model->getSimulacoes($w);
            
            
            $cad = $this->busca_model->getCadastro([['id_cadastro', $imovel->id_cadastro]]);
            
            $dt_email = [
                'nome'           => $this->altera_nome($cad->nome),
                'email'          => $cad->email,
                'endereco'       => $imovel->endereco.', '.$imovel->numero.', '.$imovel->complemento.', '.$imovel->bairro,
                'visualizacao'   => $imovel->visualizacoes,
                'favorito'       => count($favoritos),
                'negociacao'     => count($necociacoes),
                'financiamento'  => count($simulacoes),
                ];
                
            var_dump($dt_email);
            echo("<br>");
            
            $this->newsletter->enviar_email_campanha($cad->email, 53, $dt_email);
             /*
            echo("
            <br> - ENDERECO: ".$imovel->endereco."
            <br> - Visualizações: ".$imovel->visualizacoes."
            <br> - Seu imóvel como favorito: ".count($favoritos)."
            <br> - Em negociação: ".count($necociacoes)."
            <br> - Solicitações de financiamento: ".count($simulacoes)."
            <br>");*/
        }
    }
    
    private function altera_nome($str){
        $nome = explode(' ', $str);
        $first = array_shift($nome);
        $last = array_pop($nome);
        $nome_novo = trim($first." ".$last);
        
        return $nome_novo;
    }
    
    
    
    /*public function teste(){
        
        var_dump($this->cad_model->getCadastro([['id_cadastro', 1]]));
        var_dump($this->db->last_query());
    }*/
    
    public function save_push_alert(){
        
        $post_key = $this->input->post('subs_id');
        
        if($post_key != NULL){
        
            if($this->session->id_cadastro != NULL){
                
                $key = $this->cad_model->get_push_key($this->session->id_cadastro);
                
                if($key != NULL){
                    $json = json_decode($key, true);
                    
                    //Tudo certo
                    if(in_array($post_key, $json)){
                        die();
                    }else{
                        $i = count($json) + 1;
                        $json['dispositivo_'.$i] = $post_key;
                        
                        $this->cad_model->insere_push_key($this->session->id_cadastro, json_encode($json));
                    }
                }else{
                    $json = '{"dispositivo_1": "'.$post_key.'"}';
                    
                    $this->cad_model->insere_push_key($this->session->id_cadastro, $json);
                }
                
            }else{
                die();
            }
        }
    }
    
    //ERROR HERES
    public function send_push_alert_interessado(){
        
        $imovel = $this->input->post();
        
        if($imovel['id_cadastro'] != NULL){
            $this->load->library('comdono/PushAlert');
            $this->pushalert->envia_interessado_chat($imovel['id_cadastro']);
        }
            
        return [];
    }
}