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

class Confirmacao extends Builder_Controller
{
    
    function __construct() 
    {
        parent::__construct();
    }
   
   public function index()
   {
       var_dump('aasdnisakmdslakmd');
   }
   
    public function confirmacao() 
    {
        $key_log = $this->uri->segment(4);
        $this->load->model('newsletter/newsletter_model');
        $row = $this->newsletter_model->clicou_email_campanha($key_log);
        $key = $this->uri->segment(5);
        
        $id = $this->newsletter_model->confirma_key($key);
        if ($id != NULL) 
        {
            $i = $this->newsletter_model->verifica_cadastro($key);
            if ($i == 1) 
            {
                redirect('qiclub');
            } 
            else
            {
                if ($this->newsletter_model->activate_email_cadastro($key)) 
                {
                    
                    $modal_msg['msg'] = 'E-mail confirmado com sucesso!';
                    $this->session->set_flashdata('msg', $modal_msg);
                    redirect('qiclub');
                } 
                else
                {
                    redirect('qiclub');
                    //echo "<p>Dados incorretos ou o link de ativação expirou.</p>";
                }
            }
        } 
        else
        {
            redirect('qiclub');
        }
        
    }
    
    /*public function confirmacao() 
    {
        $key_log = $this->uri->segment(4);
        $this->load->model('newsletter/newsletter_model');
        $row = $this->newsletter_model->clicou_email_campanha($key_log);
        $data['key_confirma_cad'] = $this->uri->segment(5);
        $this->session->set_userdata($data);
        
        redirect('newsletter/confirmacao/confirmacao_email');
    }*/
    
    public function confirmacao_email()
    {
        //http://builder.viewbrasil.com.br/viewbrasil/confirmacao/2325424be64408abd3a750ca71a7a09bc
        $key = $this->session->key_confirma_cad;
        $link = ("http://blog.viewbrasil.com.br");
        if(!isset($key) || $key == NULL)
        {
            redirect($link);
        }
        $this->load->model('newsletter/newsletter_model');
        if($this->newsletter_model->verifica_cadastro($key) == 1)
        {
            redirect($link);
        }
        
        $this->load->library('form_validation');
        
		if ($this->input->post() == TRUE) 
        {
            $this->form_validation->set_rules('nome', 'Nome', 'required|trim');
    		$this->form_validation->set_rules('sobrenome', 'Sobrenome', 'required|trim');
    		$this->form_validation->set_rules('sexo', 'Sexo', 'required');
    		//$this->form_validation->set_rules('g-recaptcha-response', 'captcha', 'required|callback_check_captcha');
    		
    		if ($this->form_validation->run() != FALSE)
    		{
    		    $post = $this->input->post();
                $data['nome'] = $post['nome'];
                $data['sobrenome'] = $post['sobrenome'];
                $data['sexo'] = $post['sexo'];
                
                $this->session->unset_userdata('key_confirma_cad');
                $return = $this->activate($key,$data);
                if($return === true)
    		    {
    		        $id = $this->newsletter_model->confirma_key($key);
    		        $data['key_log'] = md5($id.'1');
    		        $data['form'] = false;
    		    }
           }
        }
		
        $data['page_title'] = "View Brasil - Marketing Digital";
        $data['url'] = base_url() . "newsletter/confirmacao/confirmacao_email";//newsletter/newsletter/activate/29c44957ecdf19c639080d957b9e328b7
        
        Assets::js(array("https://www.google.com/recaptcha/api.js"));	
    	Assets::add_module_js('newsletter',array(
				'confirmacao.js'
		));
        
        Assets::add_module_css('newsletter',array(
		    'styles-confirmacao'
		));
		
		Template::set_message(validation_errors());
		
		//$data['header'] = false;
		//$data['footer'] = false;
		
        Template::set($data);
	    Template::set_view('confirmacao_view');
		Template::render();
    
    }
    
    
    
    
    
    public function activate($key,$post) 
    {
        $link = ("http://blog.viewbrasil.com.br");
        $this->load->model('newsletter/newsletter_model');
        $id = $this->newsletter_model->confirma_key($key);
        if ($id != NULL) 
        {
            $i = $this->newsletter_model->verifica_cadastro($key);
            
            if ($i == 1) 
            {
                redirect($link);
                // "<p>Email Ja foi Confirmado</p>"
            } 
            else
            {
                $dados['nome'] = $post['nome'];
                $dados['sobrenome'] = $post['sobrenome'];
                $dados['sexo'] = $post['sexo'];
                
                if ($key == "29c44957ecdf19c639080d957b9e328b7") 
                {
                    var_dump($dados);
                    break;
                }
                
                if ($this->activate_email($key, $dados)) 
                {
                    $r_act_membro = $this->active_membro($id);
                    
                    if (isset($r_act_membro->status) && $r_act_membro->status == 'subscribed') 
                    {
                        $this->newsletter_model->adicionou_membro($id);
                    }
                    $email = $this->newsletter_model->get_email($id);
                    $this->load->library('newsletter/newsletter');
                    $this->newsletter->enviar_email_campanha($email->email, 2);
                    
                    return true;
                    //echo "<p>Seu cadastro foi ativado com sucesso, e alguma mensagem aqui.</p>";
                    //redirect($link);
                } 
                else
                {
                    redirect($link);
                    //echo "<p>Dados incorretos ou o link de ativação expirou.</p>";
                }
            }
        } 
        else
        {
            redirect($link);
            //echo  "<p>Dados incorretos</p>";
        }
    }
    
    function activate_email($key, $dados) 
    {
        $this->load->model('newsletter/newsletter_model');
        $result = $this->newsletter_model->activate_email_cadastro($key, $dados);
        return $result;
    }
    
    public function teste_email()
    {
        echo 'inicio';
        $this->enviar_email_campanha(4, 1);
    }
    
    function enviar_email_campanha($id_email, $id_campanha) 
    {
        $this->load->model('newsletter/newsletter_model');
        $email = $this->newsletter_model->get_email($id_email);
        $r_log = $this->newsletter_model->verifica_log_email($email->email, $id_campanha);
        if ($r_log === false) 
        {
            $campanha = $this->newsletter_model->get_campanha($id_campanha);
            
            /* echo "<pre>";
             var_dump($email->email, $campanha->id_campanha);*/
            
            $data = array(
                'email' => $email->email,
                'nome' => $email->nome,
                'sexo' => $email->sexo,
                'key_log' => md5($id_email . $id_campanha) ,
                'key_concat' => $email->id . $email->activation_key ,
                'subject' => $campanha->subject,
                'view_html' => $campanha->view_html,
            );
            var_dump($data);break;
            $rst_email = $this->_envia_email_campanha($data);
            //var_dump($rst_email);
            if ($rst_email === true) 
            {
                $this->enviou_email_campanha($id_email, $id_campanha, 1);
            } 
            else
            {
                $this->enviou_email_campanha($id_email, $id_campanha, 0);
            }
        }
    }
    
    public function check_captcha($str)
    {
        $result = json_decode($this->check_google_captcha($str));
        if(isset($result->success) && $result->success == TRUE)
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    
    public function _envia_email_campanha($data) 
    {
        
        $this->load->library('email');
        $config['protocol'] = 'mail';
        $config['mailpath'] = '/usr/sbin/sendmail';
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        
        $this->load->library('email');
        $this->email->from('contato@viewbrasil.com.br', "View Brasil");
        $this->email->to($data['email']);
        $this->email->subject($data['subject']);
        $this->email->message($this->load->view('newsletter/campanha/' . $data['view_html'], $data, TRUE));
        
        if ($this->email->send() === true) 
        {
            return true;
        } 
        else
        {
            return $this->email->print_debugger();
        }
    }
    
    function enviou_email_campanha($id_email, $id_campanha, $st) 
    {
        //`id`, `id_email`, `id_campanha`, `enviado`, `abriu`, `clicou`, `enviado_em`
        $insert = array(
            'id_email' => $id_email,
            'id_campanha' => $id_campanha,
            'key_log' => md5($id_email . $id_campanha) ,
            'enviado' => $st,
            'enviado_em' => date('Y-m-d H:i:s') ,
        );
        $this->load->model('newsletter/newsletter_model');
        $this->newsletter_model->insere_log($insert);
        if ($st == 1) 
        {
            $this->newsletter_model->enviou_campanha($id_campanha);
        } 
        else
        {
            $this->newsletter_model->falhou_campanha($id_campanha);
        }
    }
    
    public function check_google_captcha($response)
	{	       
        $url = 'https://www.google.com/recaptcha/api/siteverify';
    
    	// init curl
        $ch = curl_init();
        
        $secret = '6Lfu8ygTAAAAAJ_TkNlIZpwNtELOzcowJ6DvEN8c';
        //$response = $this->input->post('response');

        //Set the URL to work with
        curl_setopt($ch, CURLOPT_URL, $url);

        // ENABLE HTTP POST
        curl_setopt($ch, CURLOPT_POST, TRUE);

        //Set the post parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'secret='.$secret.'&response='.$response);

        //Handle cookies for the login
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-google.txt');

        //curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17');
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_VERBOSE, TRUE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        //Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
        //not to print out the results of its query.
        //Instead, it will return the results as a string return value
        //from curl_exec() instead of the usual TRUE/FALSE.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //execute the request (the login)
        $response = curl_exec($ch);

        //the login is now done and you can continue to get the
        //protected content.

        curl_close($ch);
        
	    return $response;
	}
    
    public function active_membro($id_email) 
    {
        $this->load->model('newsletter/newsletter_model');
        $result = $this->newsletter_model->get_email($id_email);
        // create a new cURL resource
        //$post = $this->input->post();
        $ch = curl_init();
        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "https://us13.api.mailchimp.com/3.0/lists/5f1750514a/members/" . md5($result->email));
        curl_setopt($ch, CURLOPT_USERPWD, "Authorization:2f7b5f3ecc8ef4835ad5a2d1fdaa0d0d-us13");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'content-type: application/json'
        ));
        
        $data = array(
            'email_address' => $result->email,
            'status' => 'subscribed',
            'merge_fields' => array(
                'FNAME' => $result->nome,
                'LNAME' => $result->sobrenome
            )
        );
        
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        
        $data = json_encode($data);
        // return into variable if true
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // debug if true
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        
        curl_setopt($ch, CURLOPT_HEADER, 1);
        // grab URL and pass it to the browser
        $response = curl_exec($ch);
        // Then, after your curl_exec call:
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        
        $resultado = json_decode($body);
        // close cURL resource, and free up system resources
        curl_close($ch);
        return $resultado;
    }
    
    private function validaEmail($email) 
    {
        $array_invalidos = array(
            '@mailinator.com',
            '@harakirimail.com'
            );
        $syntaxe = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';
        if (preg_match($syntaxe, $email))
        {
            foreach($array_invalidos as $invalido)
            {
                $result = strrpos($email, $invalido); //Resultado: 8
                if($result != null)
                {
                   return false;
                }
            }
                    
              return true;
        }
        else 
        {
            return false;
        }
       
    }
    
    
}