<?php

/**
 * webservice_envio_correo actions.
 * http://soporte14.sofhouse.net/canon/web/api_dev.php/api/webservice_envio_correo/list.json?recipients=lavila@sofhouse.net;lavila
 *
 * @package    cartera
 * @subpackage webservice_envio_correo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class webservice_envio_correoActions extends sfActions {

    /**
     * Executes list action
     *
     * @param sfRequest $request A request object
     */
    public function executeList(sfWebRequest $request) {

        //Revisar que sea post
        //$this->forward404Unless($request->isMethod('post'));
        //Guardar los parametros del request en el log
        $this->logMessage("---BEGIN Logging request");
        foreach ($request->getPostParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("--------------------------------------------------/  Ip: " . $_SERVER['REMOTE_ADDR']);
        foreach ($request->getGetParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("---END Logging request");

        /*
         * Manejo de errores
         */
        try {

            $this->logMessage("[webservice_envio_correo] Envio de correo INCIO");

            //Variables de configuracion del  servidor de envio de correos (app.yml)
            $ipServidorCorreo = sfConfig::get('app_ipServidorCorreo');
            $smptSecure = sfConfig::get('app_SMTPSecure');
            $email_envio = sfConfig::get('app_email_envio');
            $smtpAuth = sfConfig::get('app_SMTPAuth');
            $port = sfConfig::get('app_Port');
            $usernameCorreo = sfConfig::get('app_Username_correo');
            $passwordCorreo = sfConfig::get('app_Password_correo');

            $user_from = "Servicios";
            if (isset($request['user_from'])) {
                $user_from = $request['user_from'];
            }

            $recipients = array();
            $i = 0;
            if (isset($request["recipients"])) {
                $recipients_datos = explode('/', $request["recipients"]);

                foreach ($recipients_datos as $value) {
                    $datos = explode(';', $value);

                    $recipients[$i]["email"] = $datos[0];
                    $recipients[$i]["name"] = $datos[1];
                    
                    $i++;
                }
            }
            
            $ccRecipients = array();
            $i = 0;
            if (isset($request["ccRecipients"])) {
                $ccrecipients_datos = explode('/', $request["ccRecipients"]);

                foreach ($ccrecipients_datos as $value) {
                    $datos = explode(';', $value);

                    $ccRecipients[$i]["email"] = $datos[0];
                    $ccRecipients[$i]["name"] = $datos[1];
                    
                    $i++;
                }
            }
            
            $bccRecipients = array();
            $i = 0;
            if (isset($request["bccRecipients"])) {
                $bccrecipients_datos = explode('/', $request["bccRecipients"]);

                foreach ($bccrecipients_datos as $value) {
                    $datos = explode(';', $value);

                    $bccRecipients[$i]["email"] = $datos[0];
                    $bccRecipients[$i]["name"] = $datos[1];
                    
                    $i++;
                }
            }

            $subject = "Asunto";
            if (isset($request['asunto'])) {
                $subject = $request['asunto'];
            }

            $attachmentFiles = array();

            /**
             * PHPMailer
             */
            // Instanciar PHPMailer una primera Vez
            $mail = new PHPMailer(); // defaults to using php "mail()"

            /*
             * Parametros PHPMailer
             */
            $this->logMessage("[webservice_envio_correo] Parametros PHPMailer");
            $mail->IsSMTP(); // telling the class to use SMTP
            $mail->SMTPSecure = $smptSecure;
            $mail->Host = $ipServidorCorreo;      // SMTP serverP debug information (for testing)
            //$mail->SMTPDebug = 2; //Alternative to above constant
            // 1 = errors and messages
            // 2 = messages only
            $mail->SMTPAuth = $smtpAuth;                  // enable SMTP authentication
            $mail->Port = $port;                    // set the SMTP port for the GMAIL server
            $mail->Username = $usernameCorreo;              // SMTP account username
            $mail->Password = $passwordCorreo;           // SMTP account password            
            $mail->SetFrom($email_envio, utf8_decode($user_from));
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            $this->logMessage("[webservice_envio_correo] AddAddress: ");
            //Add recipients
            foreach ($recipients as $value) {
                $mail->AddAddress($value['email'], utf8_decode($value['name']));
            }

            //Add ccRecipientes
            foreach ($ccRecipients as $value) {
                $mail->AddCC($value['email'], utf8_decode($value['name']));
            }

            //Add BccRecipientes
            foreach ($bccRecipients as $value) {
                $mail->AddBCC($value['email'], utf8_decode($value['name']));
            }

            $this->logMessage("[webservice_envio_correo] Subject: " . $subject);
            $mail->Subject = utf8_decode($subject);

            /*
             * body
             */
            $body = "<html><body> Envio de Correo.<br/><br/></body></html>";
            if (isset($request['body'])) {
                $body = $request['body'];
            }
            $body = <<<EOD
<br/> 
$body
<br/> 
EOD;

            $this->logMessage("[webservice_envio_correo] body: " . $body);
            $mail->MsgHTML(utf8_decode($body));

            $this->logMessage("[webservice_envio_correo] attachment");
            //Adjuntar archivos        
            foreach ($attachmentFiles as $key => $value) {
                //$mail->AddAttachment("$ruta/$value", $key);                      
            }

            /*
             *  Enviar el correo
             */
            if (!$mail->Send()) {
                $mensaje = "Mailer Error: " . $mail->ErrorInfo;
                $this->logMessage($mensaje . "<br/>");
            } else {
                $mensaje = "Correo enviado";
                $this->logMessage($mensaje);
            }

            /*
             * Limpiar datos del correo
             */
            $this->logMessage("[webservice_envio_correo] Limpiar datos del correo");
            $mail->ClearAllRecipients();
            $mail->ClearAttachments();

            $this->status = 0;
            $this->list_data = array(
                array(
                    'mensaje' => $mensaje,
                    'servicio' => 'webservice_envio_correo',
                    'modulo' => 'CANON'
                )
            );

            $this->logMessage("[webservice_envio_correo] Envio de correo FIN");
        } catch (Exception $e) {
            $mensaje = "[webservice_envio_correo] ERROR!!!";

            $this->status = 1;
            $this->mensajeError = $mensaje;
            $this->list_data = array();
            $this->logMessage($mensaje);
            $this->logMessage($e->getMessage());
        }
    }

}
