<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require 'mailerPHP/PHPMailerAutoload.php';

/*
 * Orkin.php
 *
 * Created on March 30, 2017, 10:46 PM
 *
*/

/**
 <P>This class is used to receive request by Orkin

 @author 
 @see RMScheduler
 */

// http://localhost/RMScheduler/rm_webservices/index.php/MailSender
class MailSender extends CI_Controller {

function __construct() {
        @session_start();
        parent::__construct();
       // $this->load->library('security');
        $this->ci = & get_instance();
        $this->ci->load->database();
        $this->allow_get_array = TRUE;
        //$this->ci->load->model('Model_orkin');

    }
    
    public function index()
	{
		echo'test ';

	}
    
   
  public function sendEmailGET(){
    $bcc = "programacion@orkincr.com";
	$email    = "";
	$urlLink  = "";
	$commEmai = "";
	$host = "";
	$user = "";
	$pass = "";
	$subj = "";
	$nameUser = "";

	if ( $_SERVER["REQUEST_METHOD"] == "GET" ) {
 	  $email    = $_GET["email"];
	  $urlLink  = $_GET["url"];
	  $commEmai = $_GET["comm"];
	  $host 	= $_GET["host"];
	  $user 	= $_GET["user"];
	  $pass 	= $_GET["pass"];
	  $subj 	= $_GET["subj"];
	  $nameUser = $_GET["nameUser"];
	}

	$urlLink =  str_replace("%26","&",$urlLink);
	$urlLink =  str_replace(" ","%20",$urlLink);
	$urlLink = str_replace("#","%23",$urlLink);
	$subj    =  str_replace("%20"," ",$subj);
	$nameUser  =  str_replace("%20"," ",$nameUser);


	
	$config = Array(
            'protocol' => "smtp",
            'smtp_host' => $host,
            'smtp_port' => 587,
            'smtp_timeout' => 10,
            'smtp_user' => $user,
            'smtp_pass' => $pass,
            'mailtype' => "html",
            'charset' => "utf-8",
            'newline' => "\r\n",
            'crlf' => "\r\n",
            'validation' => true
            //'smtp_crypto' => 'ssl'
        );
        
    date_default_timezone_set('America/Costa_Rica');
    $p1 = 'Estimado cliente . ';
	$p2 = 'Usted esta recibiendo un reporte enviado por ORKIN. ';
	$p3 = 'Por favor presione '. " <a href='".$urlLink ;
	$p4 = "'>aqui</a>". ' para visualizarlo.';

	$emailBody    =  $p1. $p2. $p3. $p4. ' <br> '. $commEmai;
    //$email = "villalobosbravobrayan@gmail.com";
    //Obtenemos la instancia
    $this->load->library('email', $config);
    $this->email->set_crlf("\n");
    //Se configura las opciones del email
    $this->email->from($user, $nameUser);
    $this->email->to($email);
    //$this->email->bcc($bcc);
    //Código para reestablecer la contraseña
    $this->email->subject($subj);
    $this->email->message($emailBody);
    //Se envia el email
    
	if(!$this->email->send()) {
    	//echo ' ERROR';
    	echo $this->email->print_debugger();
	    //echo ' Error: ' . $mail->ErrorInfo;
	} else {
    	echo 'OK';
	}
	/*
	echo "<br><br><br>";
	
	echo $this->email->print_debugger();
	
   echo ' email: ' . $email;
   echo '<br><br> url: ' . $urlLink;
   echo '<br><br> comm: ' . $commEmai.'<br><br>';
   echo '<br><br> pass: ' . $pass.'<br><br>';

	$mail = new PHPMailer;

	//$mail->SMTPDebug = 3;                               // Enable verbose debug output

	$mail->isSMTP();                                      // Set mailer to use SMTP
	//$mail->Host = 'mail.route-miner.com';                 // Specify main and backup SMTP servers
	$mail->Host = $host;                 // Specify main and backup SMTP servers
	$mail->SMTPAuth = true;                               // Enable SMTP authentication

	//$mail->Username = 'alonso.villanueva@route-miner.com';                 // SMTP username
	//$mail->Password = 'alonso123'; 
	$mail->Username = $user;                 // SMTP username
	$mail->Password = $pass;   
	$mail->SMTPSecure = 'tsl';                            // Enable TLS encryption, `ssl` also accepted, tls
	$mail->Port = 587;                                    // TCP port to connect to

	$mail->setFrom($user, $nameUser);
	$mail->addAddress($email);               // Name is optional

	//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
	//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
	$mail->isHTML(true);                                    // Set email format to HTML
	$p1 = 'Estimado cliente. ';
	$p2 = 'Usted esta recibiendo un reporte enviado por ORKIN. ';
	$p3 = 'Por favor presione '. ' <a href='.$urlLink ;
	$p4 = '>aqui</a>'. ' para visualizarlo.';

	$mail->Subject = $subj;
	$mail->Body    =  $p1. $p2. $p3. $p4. ' <br> '. $commEmai;
	//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

	if(!$mail->send()) {
    	echo 'ERROR';
	    //echo ' Error: ' . $mail->ErrorInfo;
	} else {
    	echo 'OK';
	}
	*/

 }

   public function sendReportByEmail(){
    
	$email    = "";
	$urlLink  = "";
	$user = "";
	$pass = "";
	$client = "";
	$nameUser = "";


 	  $email    = $this->input->post("email");
	  $urlLink  = $this->input->post("url");
	  $user 	= $this->input->post("user");
	  $pass 	= $this->input->post("pass");
	  $nameUser = $this->input->post("nameUser");
	  $client 	= $this->input->post("client");


	$urlLink =  str_replace("%26","&",$urlLink);
	$urlLink =  str_replace(" ","%20",$urlLink);
	//$urlLink = str_replace("#sc#","-",$urlLink);
    //$urlLink = str_replace("-","%2D",$urlLink);
    $urlLink = str_replace("#","%23",$urlLink);
	$nameUser  =  str_replace("%20"," ",$nameUser);

	//echo $urlLink.'!!!';

	
	$config = Array(
            'protocol' => "smtp",
            'smtp_host' => "mail.route-miner.com",
            'smtp_port' => 587,
            'smtp_timeout' => 15,
            'smtp_user' => $user,
            'smtp_pass' => $pass,
            'mailtype' => "html",
            'charset' => "utf-8",
            'newline' => "\r\n",
            'crlf' => "\r\n ",
            'validation' => true
        );
        
    date_default_timezone_set('America/Costa_Rica');
    $p1 = 'No se pudo encontrar lugar para este reporte.<br>';
	$p2 = 'No se encontro el cliente al cual pertenece '. " <a href='".$urlLink;
	$p3 = "'>este</a>". ' reporte.';

	$emailBody    =  $p1. $p2. $p3. ' <br> ';
    //$email = "villalobosbravobrayan@gmail.com";
    //Obtenemos la instancia
    $this->load->library('email', $config);
    $this->email->set_crlf("\n");
    //Se configura las opciones del email
    $this->email->from($user, $nameUser);
    $this->email->to($email);
    $subject = "Ubicar reporte generado para ".$client." ";
    //echo $subject."<br>";
    $this->email->subject($subject);
    $this->email->message($emailBody);
    //Se envia el email
    $sended = false;
    $count = 0;
    while(!$sended){

    	if(!$this->email->send()) {
    	//echo 'ERROR
    	echo $this->email->print_debugger();
	    //echo ' Error: ' . $mail->ErrorInfo;
	    $count++;
	    sleep(1);

		} else {
	    	echo 'OK';
	    	$sended = true;
		}
		if($count == 3){
			break;
		}
    }

 }
    
    
    public function sendEmailPOST(){
    
	$email =  "";
	$urlLink = "";
	$commEmai = "";

	if ($_SERVER["REQUEST_METHOD"] == "POST") {
 	  $email =   $_POST["email"];
	  $urlLink =  $_POST["url"];
	  $commEmai = $_POST["comm"];
	}
/*
   echo ' email: ' . $email;
   echo '<br><br> url: ' . $urlLink;
   echo '<br><br> comm: ' . $commEmai.'<br><br>';
*/
	$mail = new PHPMailer;

	//$mail->SMTPDebug = 3;                               // Enable verbose debug output

	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'mail.route-miner.com';                 // Specify main and backup SMTP servers
	$mail->SMTPAuth = true;                               // Enable SMTP authentication

	$mail->Username = 'alonso.villanueva@route-miner.com';                 // SMTP username
	$mail->Password = 'alonso123';    
	$mail->SMTPSecure = 'tsl';                            // Enable TLS encryption, `ssl` also accepted, tls
	$mail->Port = 587;                                    // TCP port to connect to

	$mail->setFrom('alonso.villanueva@route-miner.com', 'ORKIN.');
	$mail->addAddress($email);               // Name is optional
	
	//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
	//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
	$mail->isHTML(true);                                    // Set email format to HTML
	$p1 = 'Estimado cliente.';
	$p2 = 'Usted esta recibiendo un reporte enviado por ORKIN.';
	$p3 = 'Por favor presione '. '<br> <a href='.$urlLink ;
	$p4 = '> aqui </a> '. ' para visualizarlo.';

	$mail->Subject = 'Reporteria Orkin ';
	$mail->Body    = $p1. $p2. $p3. $p4. $commEmai;
	//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

	if(!$mail->send()) {
    	echo 'ERROR';
	    //echo ' Error: ' . $mail->ErrorInfo;
	} else {
    	echo 'OK';
	}
 }
    
    
    
    
}



?>
