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

class Compartilhar_ajax extends Builder_Controller {

	function __construct()
	{
		parent::__construct();
	} 
	
	public function index() 
    {
        if ($this->input->post() == TRUE) 
        {
            
            $this->load->library('form_validation');
            
            $emails = json_decode($this->input->post('email_comp'));
            
            //$this->form_validation->set_rules('email_comp', 'E-mail', 'required|valid_email|trim');
            $this->form_validation->set_rules('remetente', 'Remetente', 'required|trim');
            $this->form_validation->set_rules('imovel_comp', 'Imóvel', 'required|trim');
            
            if ($this->form_validation->run() != FALSE) 
            {
                $remetente    = $this->input->post('remetente'); 
                $link_imovel  = $this->input->post('imovel_comp');
                
                $this->send_message_by_email($remetente, $emails, $link_imovel);
            } 
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => validation_errors()
                ));
            }
        }
    }
    
    public function send_message_by_email($remetente, $emails, $link_imovel)
    {
        $data = array(
            'remetente' => $remetente,
            'link' => $link_imovel
        );
        
        $this->load->library('newsletter/newsletter');
        
        $message = "<p>Sua mensagem foi enviada.</p>";
        
        $success = false;
        foreach($emails as $emailComp)
        {
            if ($this->newsletter->enviar_email_campanha($emailComp, 19, $data)) 
            {
                $success = true;
            } 
        }
        
        if ($success) 
            {
                echo json_encode(array(
                    'valid' => true,
                    'msg' => $message,
                ));
            } 
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => 'O e-mail informado não pôde ser enviado. Por favor, tente novamente mais tarde.'
                ));
            }
    }
 }