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


//define('ACCESS_KEY', "AKIAXWSGWKL2LMYZ2XSV");
///define('SECRET_KEY', "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");
//use Aws\Credentials\Credentials;
//use Aws\S3\S3Client;
//use Aws\S3\Exception\S3Exception;


//require_once(APPPATH.'modules/comdono/controllers/Facebook.php');

class Cadastro extends Comdono_Controller{
    
    
	function __construct()
	{
		parent::__construct();
		
        require APPPATH . 'libraries/vendor/autoload.php';
		
		$this->load->model('cad_model');
		$this->load->model('administrativo/fluxo_model');
		
		Assets::add_module_css('comdono', array(
            'btn-switch',
            'jasny-bootstrap.min'
        ));
        Assets::add_module_js('comdono', array(
            'jasny-bootstrap.min'
        ));
	}
	
	
	private $step_preview = 11;
	private $cont = 1;
	
	
	
	public function mostra_assets(){
        ///die();
        $open_app = glob(APPPATH.'modules/*/assets/img/*');
        echo '<br>Arquivos de Aplication<br>';
        $this->verifica_arqv($open_app);
        
        //$open_build = glob(BUPATH.'modules/*/assets/img/*');
        //echo '<br>Arquivos de Builder<br>';
        //$this->verifica_arqv($open_build);
    
    }
    
    public function verifica_arqv($open_dir){
           $i = 0;
           
           foreach($open_dir as $dir){
               if(is_dir($dir)){
                   $pasta = glob($dir.'/*');
                $this->verifica_arqv($pasta);  
             }else{
                 $arquivo = $dir;
                 $caminho = str_replace('var/www/desenvolvimento/application/', "", $dir);
                 echo "arquivo - ".$arquivo;
                 echo "<br>";
                 echo "caminho - ".$caminho;
                 echo "<br>";
                 
                 //$this->enviaArquivo($caminho,$arquivo);
                }
           }
    }
	
	/*private function enviaArquivo($caminho,$arquivo)
	{
	    $credentials = new Credentials(ACCESS_KEY, SECRET_KEY);
        $s3 = new S3Client(['version' => 'latest','region' => 'us-west-2','credentials' => $credentials]);
	    
	    $putObject = [
                    'ACL' => 'public-read',
                    'Bucket' => "comdono",
                    'Key'    => $caminho,
                    'SourceFile' => $arquivo,
                    'ContentDisposition' => 'inline; filename='.$arquivo,
                    ];
                ///var/www/desenvolvimento/application/modules/newsletter/assets/img/twitter.png
                //$respThumbnail = $s3->putObject($putThumbnail);
                //$respMedium = $s3->putObject($putMedium);
                $response = $s3->putObject($putObject);
                $ObjectURL = $response['ObjectURL'];
                
                $ObjectURL = Upload::putObjectResize($tmp_name, $nameLocal, 900, $field_info->upload_path_s3);
                
                echo("<img src='$ObjectURL'><br>");
	}*/
	
	
	public function index()
    {
        Template::unset(['topnav','footer']);
        
        
        /*$imoveis = $this->cad_model-> getImoveis();
        foreach($imoveis as $imovel)
        {
            $novoTitulo = HImovel::montaTitulo($imovel);
            $key = convertAccentsAndSpecialToNormal(strtolower($novoTitulo));
            $data['key_anuncio'] = $key;
            $this->cad_model->updateImovel($imovel->id_imovel,$data);
        }*/
        
        $dasd = $this->get_http_referer();
        //var_dump($dasd);
        $baseCad = base_url('cadastro');
        $pos = strpos($dasd, $baseCad);
        
        //var_dump($baseCad);
        //die();
        if ($pos !== 0) {
            $this->setRefRedirect();
        }
        
        //var_dump($this->refRedirect());
        
        
        if($this->logado() && $this->meuCadastro->etapa > 1)
        {
            Assets::add_module_js('comdono', array(
                'contato'
            ));
            
            $cad = $this->meuCadastro;
            
            if($cad->etapa == 5 || $cad->etapa == 7){
                
                $this->cad_model->updateCadastro($this->session->id_cadastro, ['etapa'=>8]);
            }
            
            
            
            if($cad->etapa == 8)
                redirect();
                
                
            $data['braco_direito'] = $this->cad_model->getBracoDireito($cad->id_cadastro);
            
            //var_dump($data['braco_direito']);
            
            $data['cad'] = $cad;    
            $data['etapa'] = $cad->etapa;
             
            $data["page"] = 3;
            
            Template::set($data);
            //Template::set_view('cadastro_view');
            Template::set_view('cadastro_step_view');
        }
        else
        {
            $data['info'] = "#dicacomdono<br/>Para criar uma senha forte, use caracteres maiúsculos, minúsculos, números e símbolos. Assim, seus dados continuam protegidos.";

            $data['etapa'] = $this->meuCadastro->etapa??0;
            
            $data['cad'] = $this->meuCadastro??[];    
            
            $data["page"] = 3;
            
            $data['url'] = $this->loginUrl();
            
            
            Template::set_modal($data,[
                'comdono/modal/contato_view'
            ]);
            
            
            $data['email_anunciar'] = $this->session->flashdata('email_anunciar');
            
            Template::load_view('cadastro_view', $data, '', '', $data['view']);
            Template::set($data);
            Template::set_view('modern_view');
            
            //Template::set_view('cadastro_view');
        }
        
        Assets::add_module_js('comdono', array(
            'cadastro',
            'forca_senha',
            'contato'
        ));
        
        Assets::add_css(array(
            'plugins/cb-slideshow/css/style1',
            //'css/style'
        ));
        Assets::add_js(array(
            'plugins/cb-slideshow/js/modernizr'
        ));
        
        Assets::add_css(array(
            /*'plugins/clockpicker/css/bootstrap4-clockpicker',
            'plugins/datepicker/css/gijgo.min',
            'plugins/growl-alert/css/growl'*/
            
        ));
        
        Assets::add_js(array(
            /*'plugins/clockpicker/js/bootstrap4-clockpicker.min',
            'plugins/clockpicker/js/theme',
            'plugins/datepicker/js/gijgo.min',
            'plugins/datepicker/js/messages.pt-br',
            'plugins/datepicker/js/theme'*/
        ));
        
        
        
        Template::render();
    }
    
    //Download
    public function pdf_contrato_imovel($id_imovel)
    {
        ini_set('max_execution_time', 300);
        
        if($this->session->perfil == 1)
            $data['imovel'] = $imovel = $this->cad_model->getImovel(['id_imovel'=>$id_imovel]);
        else 
            $data['imovel'] = $this->cad_model->getImovel(['id_imovel'=>$id_imovel,'id_cadastro' => $this->session->id_cadastro]);
        
        if($data['imovel'] == null ){
            echo('Permissão negada');
            die();
        }
        
        $data['donoCadastro'] = $this->cad_model->getCadastro([['id_cadastro',$data['imovel']->id_cadastro]]);
        Template::load_view('doc_contrato_prestacao_servico_pdf', $data, '', '', $html);
        
	    if(!empty($html))
	    {
            $mpdf = new \Mpdf\Mpdf(['tempDir' => 'assets/uploads/']);
            $filename = 'contrato_prestacao_servico-'.$id_imovel.'-'.date('m-Y').'.pdf';

            //$mpdf->WriteHTML($stylesheet,1);
            $mpdf->WriteHTML($html);
            $mpdf->Output($filename, 'D');
	    }
    }
    
    //view
    public function view_contrato_imovel($id_imovel = 1300)
    {
        $data['imovel'] = $this->cad_model->getImovel(['id_imovel'=>$id_imovel, 'id_cadastro' => $this->session->id_cadastro]);
        
        $data['donoCadastro'] = $this->cad_model->getCadastro([['id_cadastro',$data['imovel']->id_cadastro]]);
        
	    Template::set($data);
        Template::set_view('doc_contrato_prestacao_servico_pdf');
        Template::render();
    }
    
    
    
    public function imovel()
    {
        $uri3 = $this->uri->segment(3);
        $uri4 = $this->uri->segment(4);
        $uri = $this->uri->segment_array();
        
        //dd($uri3);
        
        if(!$this->tank_auth->is_logged_in())
        {
            $referer = base_url('cadastro/imovel');
            $this->session->set_userdata('http_referer', $referer);
            
            if($uri3 == "anuncieseuimovel"){
                $this->session->set_userdata(['botaoCadImovel' => true]);
            }
            
            redirect('cadastro'); 
        }
        
        if($uri3 == "anuncieseuimovel"){
            redirect('cadastro/imovel'); 
        }
        
        $step_preview = $this->step_preview;
        
        $id_ultimo_imovel = $this->session->cadastro_concluido;
        
        if(end($uri) == 'resultado')
        {
            if($id_ultimo_imovel == null)
                redirect('cadastro/imovel');
            redirect('cadastro/imovel_resultado');  
            // força o método ser sempre index para gerar css e js único
            //$this->router->method = 'index';
            //$this->router->module = 'campanha';
            /*Template::set_view('resultado_cad_imovel_view');
            Template::render();*/
        }
        elseif (end($uri) == 'preview' || $uri3 >= $step_preview) {
            redirect('cadastro/preview');
        }
        else
        {
            if($id_ultimo_imovel != null)
                redirect('cadastro/imovel_resultado');
            
            $getCadastro = $this->cad_model->get_cadastro();
            
            $data['imovel'] = '';
            $data['step'] = 1;
            $data['meuCadastro'] = json_encode($getCadastro); 
            $data['donoCadastro'] = $getCadastro; 
            
            //dd($data['meuCadastro']);
            
            while(empty($data['imovel'])) {
                $data['imovel'] = $this->cad_model->getImovelCad(['status <' => 2 ,'id_imovel_rel' => 0]); 
                if(empty($data['imovel'])){
                    
                    $rid = $this->cad_model->insertImovel(['id_cadastro'=>$this->session->id_cadastro,'data_hora_imovel'=>date("Y-m-d H:i:s")]);
                    
                    $imovel = $this->cad_model->getImovelCad(['id_imovel' => $rid]);
                    
                    //$imovel, $origem = 'iniCardImovel', $id_lista = 1, $id_responsavel = 0, $obs = null, $perfilExecutor = null
                    MFluxo::iniCardImovel($imovel, 'cadImovel',3,0,null,0);
                    //$msg = (array)$this->cad_model->get_cadastro();
                    //$msg['id_imovel'] = $rid;
                    
                    $msg['ID'] = $imovel->id_imovel;
                    $msg['Link Painel'] = base_url('administrativo/dashboard/imovel/').$imovel->id_imovel;
                    
                    HEmail::alerta('Iniciou cadastro de imovel', $msg);
                }
            }
            $this->session->set_userdata(['id_imovel' => $data['imovel']->id_imovel]);
            
            if(!is_dir('./modules/anunciante/' . $this->session->id_cadastro .'/'.$data['imovel']->id_imovel))
                mkdir('./modules/anunciante/' . $this->session->id_cadastro .'/'.$data['imovel']->id_imovel, 0774, true);
            
            
            $data['imagens'] = $this->cad_model->getImgsImovel($data['imovel']->id_imovel);
            
            if(!empty($data['imagens']) && $data['imagens'] !== null){ 
                $data['img_base'] = base_url('modules/anunciante/'.$data['imovel']->id_cadastro.'/'.$data['imovel']->id_imovel.'/galeria/');
            }
            
            if($uri3 != null && ($uri3 <= ($step_preview - 1) || $uri3 >= 1)){
                $data['step'] = $uri3;
            }
            else
            {
                $data['step'] = $data['imovel']->step == '0'? 1: $data['imovel']->step;
            }
            
            if ($data['step'] >= $step_preview) {
                redirect('cadastro/preview');
            }
            
            $data['tiposImovel'] = HBusca::getSelectTiposImovel();
            $data['imoveis_rel'] = $this->cad_model->getImoveis(['id_imovel_rel' => $data['imovel']->id_imovel ]);
            
            $data['arrayImovel'] = HImovel::getDetalhesImovel($data['imovel']);
            $data['arrayCondominio'] = HImovel::getDetalhesComdominio($data['imovel']);
            
            //Template::load_view('comdono/termos_view', '', '', '', $data['termos']);
            
            $data["open_modelo_anuncio"] = true;
        
            Template::load_view('comdono/modal/modelo_anuncio_view', $data, '', '', $data['modal_modelo_anuncio']);
            
            $this->set_imovel_css_js();
            
            $data['step_preview'] = $step_preview;
            
            $data['doc_juridico'] = true;
            
            //dd($data['imovel']);
           
            Template::load_view('doc_contrato_prestacao_servico_view', $data, '', '', $data['doc_contrato']);
            Template::load_view('doc_minuta_view', $data, '', '', $data['doc_minuta']);
            
            Template::set($data);
            Template::set_view('cadastro_imovel_view');
            Template::render();
        }
    }
    
    public function teste()
    {
            //Template::load_view('comdono/termos_view', '', '', '', $data['termos']);
            
            $data["open_modelo_anuncio"] = true;
        
            Template::load_view('comdono/modal/modelo_anuncio_view', $data, '', '', $data['modal_modelo_anuncio']);
            
            $this->set_imovel_css_js();
            
            Template::set($data);
            Template::set_view('teste_upload');
            Template::render();
       
    }
    
    private function set_imovel_css_js()
    {
        Assets::add_css(array(
            'plugins/blueimp/css/jquery.fileupload',
            'plugins/blueimp/css/jquery.fileupload-ui',
            'plugins/blueimp/css/blueimp-gallery.min',
            'plugins/blueimp/css/custom',
            'plugins/unitegallery/css/unite-gallery',
            'plugins/unitegallery/css/ug-theme-default',
            'plugins/fancyBox-v3.5.7/css/jquery.fancybox.min'
        ));
        
        Assets::add_module_css('comdono', array(
            'cad_maps'
        ));
        
        Assets::add_js(array(
            'plugins/blueimp/js/jquery.ui.widget',
            'plugins/blueimp/js/tmpl.min',
            'plugins/blueimp/js/load-image.all.min',
            'plugins/blueimp/js/canvas-to-blob.min',
            'plugins/blueimp/js/blueimp-gallery.min',
            'plugins/blueimp/js/jquery.blueimp-gallery.min',
            'plugins/blueimp/js/jquery.iframe-transport',
            'plugins/blueimp/js/jquery.fileupload',
            'plugins/blueimp/js/jquery.fileupload-process',
            'plugins/blueimp/js/jquery.fileupload-image',
            'plugins/blueimp/js/jquery.fileupload-validate',
            'plugins/blueimp/js/jquery.fileupload-ui',
            'plugins/unitegallery/js/unitegallery.min',
            'plugins/unitegallery/js/ug-theme-default',
            'plugins/sortable/jquery-sortable.min',
            'plugins/unitegallery/js/imovel',
            'plugins/fancyBox-v3.5.7/js/jquery.fancybox.min',
            '../painel/plugins/ckeditor-4.6.2/ckeditor',
            '../painel/plugins/ckeditor-4.6.2/samples/js/sample',
            '../painel/plugins/ckeditor-4.6.2/adapters/jquery',
            'plugins/morecontent/jquery.morecontent.lite'
        ));
        
        Assets::add_module_js('comdono', array(
            'config_uri_ajax',
            'upload_fotos_sortable',
            'initGoogleMaps',
            'config-ckeditor',
            'width-dynamic',
            'cadastro_imovel'
        ));
    } 
    
    /*private function set_imovel_css_js()
    {
        Assets::add_css(array(
            'plugins/blueimp/css/jquery.fileupload',
            'plugins/blueimp/css/jquery.fileupload-ui',
            'plugins/blueimp/css/blueimp-gallery.min',
            'plugins/blueimp/css/custom',
            'plugins/unitegallery/css/unite-gallery',
            'plugins/unitegallery/css/ug-theme-default',
            'plugins/fancyBox-v3.5.7/css/jquery.fancybox.min'
        ));
        
        Assets::add_module_css('comdono', array(
            'cad_maps'
        ));
        
        Assets::add_js(array(
            'plugins/blueimp/js/jquery.ui.widget',
            'plugins/blueimp/js/tmpl.min',
            'plugins/blueimp/js/load-image.all.min',
            'plugins/blueimp/js/canvas-to-blob.min',
            'plugins/blueimp/js/blueimp-gallery.min',
            'plugins/blueimp/js/jquery.blueimp-gallery.min',
            'plugins/blueimp/js/jquery.iframe-transport',
            'plugins/blueimp/js/jquery.fileupload',
            'plugins/blueimp/js/jquery.fileupload-process',
            'plugins/blueimp/js/jquery.fileupload-image',
            'plugins/blueimp/js/jquery.fileupload-validate',
            'plugins/blueimp/js/jquery.fileupload-ui',
            'plugins/unitegallery/js/unitegallery.min',
            'plugins/unitegallery/js/ug-theme-default',
            'plugins/unitegallery/js/imovel',
            'plugins/fancyBox-v3.5.7/js/jquery.fancybox.min',
            '../painel/plugins/ckeditor-4.6.2/ckeditor',
            '../painel/plugins/ckeditor-4.6.2/samples/js/sample',
            '../painel/plugins/ckeditor-4.6.2/adapters/jquery'
        ));
        
        Assets::add_module_js('comdono', array(
            'upload_fotos',
            'initGoogleMaps',
            'config-ckeditor',
            'cadastro_imovel'
        ));
    }*/
    
    private function carrega_tipos_imoveis()
    {
        return [
                "Apartamento" => [
                    'Apartamento Padrão' => 'Padrão',
                    'Kitnet/Studio' => 'Kitnet/Studio',
                    'Loft' => 'Loft',
                    'Flat' => 'Flat',
                    'Cobertura' => 'Cobertura',
                    'Duplex' => 'Duplex',
                    'Triplex' => 'Triplex',
                    'Quarto' => 'Quarto',
                    ],
                "Casa e sobrado" => [
                    'Casa Padrão' => 'Padrão',
                    'Casa de Condomínio' => 'Casa de Condomínio',
                    'Casa de Vila' => 'Casa de Vila',
                    'Sobrado' => 'Sobrado',
                    'Quarto' => 'Quarto',
                    ],
                "Outros" => [
                    'Terreno' => 'Terreno',
                    'Rural' => 'Rural',
                    'Comercial' => 'Comercial',
                    ],
            ];
    }
    
    public function imovel_resultado()
    {
        $id_ultimo_imovel = $this->session->cadastro_concluido;
        if($id_ultimo_imovel == null)
                redirect('cadastro/imovel');
                
        Assets::add_module_js('comdono', array(
                'cadastro_imovel_resultado'
            ));
        
        Template::set_view('resultado_cad_imovel_view');
        Template::render();
    }
    
    public function resultado()
    {
        $data['resultado'] = 1;
        
        Template::set($data);
        Template::set_view('resultado_cadastro_view');
        Template::render();
    }
    
    public function preview()
    {
        $imovel = $this->cad_model->getImovelCad(['status <' => 2 ,'id_imovel_rel' => 0]); 
        if($imovel == null)
            redirect('cadastro/imovel');
        
        //$data['imagens'] = $this->cad_model->getImgsImovel($data['imovel']->id_imovel);
        $imovel->imagens = $this->cad_model->getImgsImovel($imovel->id_imovel);
        
        $data['imovel'] = $imovel;
        
        if($imovel != null)
        {
            $data['arrayImovel'] = HImovel::getDetalhesImovel($imovel);
            $data['arrayCondominio'] = HImovel::getDetalhesComdominio($imovel);
        }
        
        //var_dump($this->$step_preview);
        
        $data['preview'] = true;
        $data['step'] = $this->step_preview;
        
        $data["open_modal"] = true;
        $data["open_modal_detalhes"] = true;
        $data["open_modal_resultado"] = true;
        
        
        Assets::add_css(array(
            'plugins/owlcarousel2-2.3.4/css/owl.carousel.min',
            'plugins/owlcarousel2-2.3.4/css/owl.theme.default.min',
            'plugins/unitegallery/css/unite-gallery',
            'plugins/unitegallery/css/ug-theme-default',
            'plugins/multiple-emails/css/multiple-emails',
            'plugins/justified-gallery-master/justifiedGallery.min',
            'plugins/fancyBox-v3.5.7/css/jquery.fancybox.min',
            'plugins/player/css/styles'
        ));
        
        Assets::add_js(array(
            'plugins/owlcarousel2-2.3.4/js/owl.carousel.min',
            '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',
            'plugins/justified-gallery-master/justifiedGallery.min',
            'plugins/fancyBox-v3.5.7/js/jquery.fancybox.min',
            'plugins/player/js/mediaelement-and-player.min'
        ));
        
        Assets::add_module_js('comdono', array(
            'config_uri_ajax',
            'loading_image',
            'carousel_imovel',
            'carousel_busca',
            'imovel',
            'cadastro_imovel',
            'cadastro_imovel_resultado'
        ));
        
        Template::set_modal($data,[
            /*'comdono/modal/pedido_fotos_view',*/
            'comdono/modal/login_view',
            'comdono/modal/detalhes_imovel_view',
            'comdono/modal/resultado_view',
            'comdono/modal/compartilhar_view',
        ]);
        
        $data["cadastro"] = $this->cad_model->get_cadastro([], $imovel->id_cadastro);
        
        $data['imovel']->imagens = Himg::galeriaPremium($imovel->imagens);
        
        $data['galeria'] = json_encode($data['imovel']->imagens);
        
        Template::set_modal($data,[
            'comdono/modal/tour_view',
        ]);
        
        if($imovel->fotos_profissionais !== "")
        {
            Template::set_modal($data,[
                'comdono/modal/pedido_fotos_view'
            ]);
        }
        
        Template::set($data);
        Template::set_view('imovel_detalhes_premium_view');
        
        Template::render();
    }
    
    /*public function resultado()
    {
        $resultado = $this->uri->segment(4);
        if($resultado == 'cadastro_imovel')
            $data['resultado'] = 2;
        else
            $data['resultado'] = 1;
        
        Template::set($data);
        Template::set_view('resultado_view');
        Template::render();
    }*/
    
}