<?php

class AnmTask extends sfBaseTask {

    protected function configure() {
        // // add your own arguments here
        // $this->addArguments(array(
        //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
        // ));

        $this->addOptions(array(
            new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'api'),
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
            new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
                // add your own options here
        ));

        $this->namespace = 'tarea';
        $this->name = 'comision';
        $this->briefDescription = '';
        $this->detailedDescription = <<<EOF
The [alerta:comision|INFO] task does things.
Call it with:

  [php symfony alerta:comision|INFO]
EOF;
    }

    protected function execute($arguments = array(), $options = array()) {

        // initialize the database connection
        $databaseManager = new sfDatabaseManager($this->configuration);
        $conn = Doctrine_Manager::connection();
        
        //VALIDAMOS RESOLUCIONES D EPROGRAMACION QUE NO ESTEN FIRMADAS 2 DIAS ANTES DE LA FECHA DE REGRESO DE LA COMISION
        //PARA INACTIVAR RESOLUCION, PROGRAMACION
        $sql = <<<EOD
select 
    tab0.id_plan_comisiones,
    tab0.vigencia,tab0.id_comisiones,
    tab0.vigencia_comisiones,
    tab0.ESTADO_GENERAL,tab0.id_resol_comis,
    tab1.fecha_salida
from 
    com_plan_resol_comis_v tab0
    left join COM_PLAN_COMISIONES_V tab1 on tab0.id_plan_comisiones = tab1.id_plan_comisiones  and tab0.VIGENCIA=tab1.VIGENCIA
where 
    tab0.estado=1 
    and (trunc(tab1.fecha_salida) < trunc(sysdate + INTERVAL '2' DAY))
    and tab0.ESTADO_GENERAL < 5;
EOD;

        $records = $conn->execute($sql)->fetchAll();
        
        if(count($records)>0){
            foreach ($results as $record) {
                //OBTENEMOS VARIABLES
                $id_plan_comisiones = $record['id_plan_comisiones'];
                $id_vigencia = $record['id_vigencia'];
                $id_comisiones = $record['id_comisiones'];
                $vigencia_comisiones = $record['$vigencia_comisiones'];
                $id_resol_comis = $record['id_resol_comis'];
                //INACTIVAMOS LA RESOLUCION EN LA TABLA COM_PLAN_RESOL_COMIS
                $sql = <<<EOD
update com_plan_resol_comis 
set estado = 0,
fecha_estado = SYSDATE,
id_usuario_estado = 'sofhouse',
observaciones_estado = 'RECHAZADO POR VENCIMIENTO DEL PLAZO PARA FIRMAR DIGITALMENTE',
nivel_rechazo = 1
where
id_plan_comisiones = $id_plan_comisiones
and vigencia = $id_vigencia 
and id_comisiones = $id_comisiones
and vigencia_comisiones = $vigencia_comisiones
and id_resol_comis = $id_resol_comis                        
and estado = 1
EOD;
                $conn->execute($sql);
                
            }
        }
    }

    public static function envioCorreo($report_params, $datos_usuario, $subject, $currentUri, $ruta, $adjunto, $progress_key, $array_adjuntos, $body) {

        $ipServidorCorreo = "chiminigagua.colciencias.local";


        /**
         * Clase de log
         */
        /**
         * ipServidorCorreo
         */
        //$ipServidorCorreo = $report_params["ipServidorCorreo"];



        /**
         * Variables
         */
        $i = 0;




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


        /*
         * Sofhouse
         */
         $mail->IsSMTP(); // telling the class to use SMTP
          $mail->SMTPSecure = "ssl";
          $mail->SetFrom($report_params["email_envio"], 'Sofhouse');
          $mail->AddReplyTo($report_params["email_envio"], 'Sofhouse');
          $mail->SMTPAuth = true;
          $ipServidorCorreo = "192.168.2.1";
          $mail->Host = $ipServidorCorreo;      // SMTP server
          $mail->Port = 465;                    // set the SMTP port for the GMAIL server
          $mail->Username = "alexia.velasquez";              // SMTP account username
          $mail->Password = "51s4em@s";           // SMTP account password 
        /*
         * INCI
         */
//        $mail->IsSMTP(); // telling the class to use SMTP
//        $mail->SMTPSecure = "ssl";
//        $mail->Host = $ipServidorCorreo;      // SMTP server
        //$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
        // 1 = errors and messages
        // 2 = messages only
//        $mail->SMTPAuth = true;                  // enable SMTP authentication
//        $mail->Port = 465;                    // set the SMTP port for the GMAIL server
//        $mail->Username = "inci";              // SMTP account username
//        $mail->Password = "Sistemas";           // SMTP account password
//        $mail->SetFrom($report_params["email_envio"], utf8_decode('Contratación Sofhouse'));
//        //$mail->AddReplyTo($report_params["email_envio"], utf8_decode('Nómina INCI'));
//        $mail->AddAddress($report_params["email_envio"], utf8_decode('Contratación Sofhouse'));


        /*
         * ANM
         */
//            $mail->IsSMTP(); // telling the class to use SMTP
//            $mail->SMTPSecure = "tls";
//            $mail->Host = $ipServidorCorreo;      // SMTP server
//            //$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
//            // 1 = errors and messages
//            // 2 = messages only
//            $mail->SMTPAuth = true;                  // enable SMTP authentication
//            $mail->Port = 25;                    // set the SMTP port for the GMAIL server
//            $mail->Username = "nomina";              // SMTP account username
//            $mail->Password = "Nominaanm";           // SMTP account password
//            $mail->SetFrom($report_params["email_envio"], 'Nómina ANM');
//            $mail->AddReplyTo($report_params["email_envio"], 'Nómina ANM');

        /*
         * SGC
         */
        /* $mail->IsSMTP(); // telling the class to use SMTP
          $mail->SMTPSecure = "tls";
          $mail->Host = "172.25.1.3";      // SMTP server
          $mail->SMTPDebug  = false;                     // enables SMTP debug information (for testing)
          // 1 = errors and messages
          // 2 = messages only
          $mail->SMTPAuth = false;                  // enable SMTP authentication
          $mail->Port = 587;                    // set the SMTP port for the GMAIL server
          $mail->Username = "websafi";              // SMTP account username
          $mail->Password = "wsaf0SGC$";           // SMTP account password
          $mail->SetFrom($report_params["email_envio"], utf8_decode('Contratación Websafi'));
         */
        //CORREGIR
        //$mail->AddReplyTo("alexia.velasquez@sofhouse.net", 'Contratación ANM');

        /*
         * COLCIENCIAS
         */
        /*$mail->IsSMTP(); // telling the class to use SMTP
        $mail->SMTPSecure = "";
        $mail->Host = $ipServidorCorreo;      // SMTP server
//            $mail->Host = "chiminigagua.colciencias.local";      // SMTP server
        //$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
        // 1 = errors and messages
        // 2 = messages only
        $mail->SMTPAuth = false;                  // enable SMTP authentication
        $mail->Port = 25;                    // set the SMTP port for the GMAIL server
        $mail->Username = "safiweb";              // SMTP account username
        $mail->Password = "OSI%safi28";           // SMTP account password
        $mail->SetFrom($report_params["email_envio"], utf8_decode('Comisiones COL'));

*/

        $mail->Subject = $subject;

        /**
         * Recorre usuarios para envio de correo
         */
        $i_porcentaje = 1;
        $cantidad_array = count($datos_usuario);

        // Antes de inicar el proceso largo
        $brecha = 1;
        if ($cantidad_array > 100)
            $brecha = $cantidad_array - (0.99 * $cantidad_array);

        foreach ($datos_usuario as $value) {


//            // Guardar un valor en el proceso largo
//            if ($i_porcentaje % $brecha == 0) {
//                MemcacheHandler::getInstance()->set($progress_key, round(($i_porcentaje / $cantidad_array) * 100, 0));
//            }



            $datos = explode(';', $value);

            //Datos del funcionario para el envio del correo
            $report_params["num_doc"] = $datos[0];
            $report_params["id_tipo_doc"] = $datos[1];
            $report_params["email"] = $datos[2];
            //$report_params["email"] = "alexia.velasquez@sofhouse.net";
            $nombre_completo = $report_params["nombre_completo"] = $datos[3];

            //mensaje_extra
            if (isset($report_params["mensaje_extra"])) {
                $report_params["mensaje_extra"] = "<br/><br/>" . $datos[4];
            }

            //arrayadjuntos
            if (isset($report_params["arrayadjuntos"])) {
                $array_adjuntos = array();
                $cant_adjuntos = $report_params["arrayadjuntos"];
                for ($i = 1; $i <= $cant_adjuntos; $i++) {
                    $datos_adj = explode('+', $datos[3 + $i]);
                    $key_datos = $datos_adj[1];
                    $array_adjuntos[$key_datos] = str_replace("+", "/", $datos[3 + $i]);
                }
            }



            /*
             * Operacion con el archivo
             */
            if (true) {

                /*
                 * $mail->AddReplyTo($report_params["email"], $report_params["username"]);
                 */

                // Agregar El correo
                // Agregar el Attachment
                // Cambiar el body
                $address = $report_params["email"];
                //$mail->AddAddress($address, $report_params["num_doc"]);
                //$mail->AddAddress("viaticoscolciencias@colciencias.gov.co", "Seguimiento Comisiones");
                $mail->AddAddress("alexia.velasquez@sofhouse.net", "Seguimiento");
                /**
                 * Reemplazo de caracteres
                 */
                $subject = str_replace("ó", "&oacute;", $subject);
                $report_params["mensaje_extra"] = "";
                $report_params["mensaje_extra"] = str_replace("ó", "&oacute;", $report_params["mensaje_extra"]);
                $report_params["mensaje_extra"] = str_replace(",", "<br/>", $report_params["mensaje_extra"]);
                $report_params["mensaje_extra"] = str_replace("null", " ", $report_params["mensaje_extra"]);


                //$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; // optional, comment out and test

                $body = str_replace("á", "&aacute;", $body);
                $body = str_replace("é", "&eacute;", $body);
                $body = str_replace("í", "&iacute;", $body);
                $body = str_replace("ó", "&oacute;", $body);
                $body = str_replace("ú", "&uacute;", $body);
                $body = str_replace("ñ", "&ntilde;", $body);
                $mail->MsgHTML($body);
                /**
                 * Si el envio es con adjunto de jasper
                 */
                if ($adjunto) {
//                    $mail->AddAttachment("$ruta/nivel/2- Competencias comunes.docx", "ManualNomina.pdf");      // attachment
//                    $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
                    foreach ($array_adjuntos as $key => $value) {
                        $mail->AddAttachment("$ruta/$value", $key);      // attachment                        
                    }
                }

                /*
                 *  Enviar el correo
                 */
                if (!$mail->Send()) {
                    echo "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    echo "Message sent! ";
                }

                /*
                 * Limpiar datos del correo
                 */
                $mail->ClearAllRecipients();
                $mail->ClearAttachments();
            } else {
                header('Content-type: application/pdf');
                header('Content-Disposition: attachment; filename="ManualNomina.pdf"');
                readfile("$ruta/Comprobante$i.pdf");
            }

            //Contadores
            $i = $i + 1;
            $i_porcentaje = $i_porcentaje + 1;
//                echo 'Correo enviado por el usuario ' . $report_params["username"] . ' al funcionario ' .
//                $report_params["nombre_completo"] . ' al correo ' . $report_params["email"];
//                echo '<br/>';
        }

        //Actualizar el Memcache
        //MemcacheHandler::getInstance()->set($progress_key, 99);
    }

    private function htmlClear($string) {

        $string = str_replace('<p>', '<p align="justify">', $string);
        $string = str_replace('<br>', '<br/>', $string);
        $string = str_replace('class=', '', $string);
        $string = str_replace('<img', '', $string);
        $string = str_replace('<td>X</td>', '<td align="center">X</td>', $string);
        //$string = str_replace('<td align="top">', '<td align="justify">', $string);
        //$string = str_replace('<td align="justify">X</td>', '<td align="center">X</td>', $string);
        $string = str_replace('<td rowspan="2">', '<td rowspan="2" align="justify">', $string);

        $string = str_replace('<font size="2">', '<font size="10">', $string);
        $string = str_replace('<font size="3">', '<font size="12">', $string);
        $string = str_replace('<font size="4">', '<font size="14">', $string);
        $string = str_replace('<font size="5">', '<font size="18">', $string);
        $string = str_replace('<font size="6">', '<font size="24">', $string);
        $string = str_replace('<font size="7">', '<font size="36">', $string);
        $string = str_replace('<table ', '<center><table ', $string);
        $string = str_replace('</table> ', '</table></center>', $string);
        $string = str_replace('<table ', '<table border="1"', $string);

        $string = str_replace('size="2"', 'size="10"', $string);
        $string = str_replace('size="3"', 'size="12"', $string);
        $string = str_replace('size="4"', 'size="14"', $string);
        $string = str_replace('size="5"', 'size="18"', $string);
        $string = str_replace('size="6"', 'size="24"', $string);
        $string = str_replace('size="7"', 'size="36"', $string);

        $string = str_replace('border="0"', 'border="1"', $string);


        $string = str_replace('<div>', '<div align="justify">', $string);
        $string = str_replace('&amp;amp;amp;amp;amp;nbsp;', ' ', $string);
        $string = str_replace('&amp;amp;amp;amp;nbsp;', ' ', $string);
        $string = str_replace('&amp;amp;amp;nbsp;', ' ', $string);
        $string = str_replace('&amp;amp;nbsp;', '', $string);
        $string = str_replace('&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;nbsp;', '', $string);
        $string = str_replace('<style type="text/css">P { margin-bottom: 0.08in; direction: ltr; color: rgb(0, 0, 0); line-height: 100%; text-align: justify; widows: 2; orphans: 2; }P.western { font-family: "Tahoma",sans-serif; font-size: 11pt; }P.cjk { font-family: "Times New Roman",serif; font-size: 11pt; }P.ctl { font-family: "Tahoma",sans-serif; font-size: 11pt; }A:link { color: rgb(0, 0, 255); }</style>', ' ', $string);

        $string = str_replace('<td colspan="2">', '<td colspan="2" align="justify">', $string);
        $string = str_replace('<td rowspan="3">', '<td rowspan="3" align="justify">', $string);
        $string = str_replace('<td colspan="3">', '<td colspan="3" align="justify">', $string);
        $string = str_replace('<td rowspan="4">', '<td rowspan="4" align="justify">', $string);
        $string = str_replace('<td colspan="4">', '<td colspan="4" align="justify">', $string);
        $string = str_replace('  ', ' ', $string);
        $string = str_replace('   ', ' ', $string);
        $string = str_replace('    ', ' ', $string);
        $string = str_replace('	    ', ' ', $string);
        $string = str_replace('		    ', ' ', $string);
        //$string = str_replace('<span lang="ES-TRAD">', '<span>', $string);
        $string = str_replace('<span lang="ES-COL">', '<span>', $string);
        $string = str_replace('<!-- @page { size: 21cm 29.7cm; margin: 2cm } P { margin-bottom: 0.21cm } -->', '', $string);
        $string = str_replace('<p lang="es-MX" align="justify">', '', $string);
        //$string = str_replace('<span>', '', $string);
        //$string = str_replace('</span>', '', $string); #Este es el que MAS jode :::::::::::::::::
        $string = str_replace('valign', 'align', $string);
        ;
        $string = str_replace('width=', '', $string);
        //    $string = str_replace('&nbsp;', '', $string);
        //      $string = str_replace('cellspacing=', '', $string);
        //      $string = str_replace('cellpadding=', '', $string);
        $string = str_replace('bordercolor=', '', $string);
        $string = str_replace('<td>', '<td align="justify">', $string);
        $string = str_replace('<li>', '<li align="justify">', $string);
        $string = str_replace('style=', '', $string);
        $string = str_replace('<br clear="all">', '', $string);
        return trim($string);
    }

}
