<?php

/**
 * certif_dian_contra actions.
 *
 * @package    nomina
 * @subpackage certif_dian_contra
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class certif_dian_contraActions extends sfActions {

    /**
     * Executes index 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");

        /*
         * Paginacion
         */
        if (isset($request['_startRow'])) {
            $rowStart = $request['_startRow'];
        } else {
            $rowStart = 0;
        }

        if (isset($request['_endRow'])) {
            $rowEnd = $request['_endRow'];
        } else {
            $rowEnd = 75;
        }

        //ordenar consulta
        if (isset($request['_sortBy'])) {
            $sortBy = " Order by " . $request['_sortBy'];
        } else {
            $sortBy = ' order by ter.num_doc';
        }

        //Contratista
        $id_mae_ter = null;
        $whereTercero = "";
        if (isset($request['id_contratista'])) {
            $id_mae_ter = $request['id_contratista'];
            $whereTercero = " AND tab0.id_contratista = " . $request['id_contratista'];
        }

        if (isset($request['num_doc'])) {
            $whereFuncionarioNumDoc = " AND tab0.num_doc = '" . $request['num_doc'] . "'";
        } else {
            $whereFuncionarioNumDoc = ' ';
        }


        //sentencia sql
        $sql = <<<EOD
ALTER SESSION SET NLS_DATE_FORMAT = "YYYY-MM-DD"
EOD;
        //ejecuta y obtiene el resultado del sql
        CN_TABLE::executeSQL($sql);


        /*
         * Manejo de errores
         */
        try {
            /*
             * Variables obligatorias
             */
            $id_anhos = $request['id_anhos'];


            /*
             * Variables opcionales
             */

            $consulta_sql = <<<EOD
select 
tab0.id_contratista,
tab0.num_doc,
tab0.id_anhos,
ter.razon_social as razon_soc,
ter.correo,
consec.secuencia

from (

        select distinct
        tab1.num_doc as num_doc,
        tab0.id_contratista,
        tab0.id_anhos
        from rvc_formato_pago tab0
        join rvc_contratista_v tab1 on tab0.id_contratista = tab1.id_contratista
            
            
)tab0

left join rvc_contratista_v ter
on ter.id_contratista = tab0.id_contratista

left join rvc_consecutivo_certif consec
on consec.id_contratista = ter.id_contratista
and consec.id_anhos = tab0.id_anhos

where 
tab0.id_anhos = $id_anhos
$whereFuncionarioNumDoc        
EOD;


            /*
             * Sql que trae los resultados
             * por los filtros, para totalizar las filas
             */
            $sql = <<<EOD
select count(*) as count from (
                    
    $consulta_sql    
                    
)
EOD;


            $total_record_count = CN_TABLE::executeSQL($sql);
            $total_record_count = $total_record_count[0]["count"];


            //obtener el listado de recaudos
            $sql = <<<EOD
SELECT * FROM ( SELECT row_.*, ROWNUM rownum_ FROM (

    $consulta_sql

    $sortBy
          
) row_ WHERE ROWNUM <=  $rowEnd   ) where rownum_ >  $rowStart
EOD;
            //ejecuta y obtiene el resultado del sql
            $resultado = CN_TABLE::executeSQL($sql);


            $this->totalRows = $total_record_count;
            $this->startRow = $rowStart;
            $this->endRow = $rowStart + count($resultado);
            $this->list_data = $resultado;
            $this->logMessage("[certif_dian_contra] Consulta exitosa.");
        } catch (Exception $e) {

            $this->status = 1;
            $this->totalRows = 0;
            $this->startRow = 0;
            $this->endRow = 0;
            $this->list_data = array();
            $this->logMessage("ERROR!!!");
            $this->logMessage($e->getMessage());
        }
    }

    /**
     * Generar no formularios Contratistas
     *
     * @param sfRequest $request A request object
     */
    public function executeAdd(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");
        }


        /*
         * Formato de fecha
         */
        //Sql
        $sql = <<<EOD
ALTER SESSION SET NLS_DATE_FORMAT = "YYYY-MM-DD" 
EOD;
        //Ejecutar SQL
        CN_TABLE::executeSQL($sql);

        try {

            /*
             * Variables de filtro
             */
            $id_anhos = $request['id_anhos'];
            $fecha_ini = $request['fecha_ini'];
            $fecha_fin = $request['fecha_fin'];
            $fecha_expe = $request['fecha_expe'];
            $progress_key = $request['progress_key'] . $request['username'];

            //Funcionario num_doc
            $id_mae_ter = null;
            $whereTercero = "";
            if (isset($request['id_contratista'])) {
                $id_mae_ter = $request['id_contratista'];
                $whereTercero = " AND tab0.id_contratista = " . $request['id_contratista'];
            }

            if (isset($request['num_doc'])) {
                $whereFuncionarioNumDoc = " AND tab0.num_doc = '" . $request['num_doc'] . "'";
            } else {
                $whereFuncionarioNumDoc = ' ';
            }

            /*
             * Generar consecutivos por persona y vigencia, ANM/SGR
             */
            //Sql
            $sql = <<<EOD
select 
tab0.id_contratista,
tab0.num_doc,
tab0.id_anhos
from (

        select distinct
        tab1.num_doc as num_doc,
        tab0.id_contratista,
        tab0.id_anhos
        from rvc_formato_pago tab0
        join rvc_contratista_v tab1 on tab0.id_contratista = tab1.id_contratista
            
            
)tab0

left join rvc_contratista_v ter
on ter.id_contratista = tab0.id_contratista

where
tab0.id_anhos = $id_anhos
$whereFuncionarioNumDoc              

order by
ter.num_doc 
EOD;
            //Ejecutar SQL
            $records = CN_TABLE::executeSQL($sql);

            foreach ($records as $value) {

                $id_contratista = $value['id_contratista'];

                try {
                    //insertar 
                    $sql = <<<EOD
insert into rvc_consecutivo_certif (id_consecutivo_certif,id_contratista,id_anhos,secuencia) 
    values ( null, $id_contratista, $id_anhos, (select nvl( max(secuencia) ,0) + 1 from rvc_consecutivo_certif where id_anhos = $id_anhos) ) 
EOD;
                    //ejecuta sql
                    CN_TABLE::executeSQL($sql);
                } catch (Exception $exc) {
//                    echo $exc->getTraceAsString();
                }
            }


            /*
             * COMMIT DE TODAS LAS TRANSACCIONES
             */
            $this->status = 0;
            $this->list_data = array();
            $this->logMessage("[certif_dian_contra] Generació exitosa");
        } catch (Exception $e) {
            MemcacheHandler::getInstance()->set($progress_key, 100);

            $this->status = 1;
            $this->mensajeError = "[certif_dian_contra] Ocurrio un error: " . $e->getMessage();
            $this->list_data = array();
            $this->logMessage("[certif_dian_contra] ERROR!");
            $this->logMessage($e->getMessage());
        }
    }

}
