<?php

class DatosNominaOrdenPagoController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
            array('CrugeAccessControlFilter')
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'aprobar', 'Pagar','Rechazar'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new DatosNominaOrdenPago('RegistroMasivo');
		$postDatos = FALSE;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['DatosNominaOrdenPago']))
		{
            $errorLinea='';
            $totalPago=0;
            $model->attributes=$_POST['DatosNominaOrdenPago'];
            $uploadedFile=CUploadedFile::getInstance($model,'nombre_archivo');
            $model->nombre_archivo=$uploadedFile;
            $ruta=Yii::app()->params['rutaOrdenPago'].$uploadedFile;

            if($model->validate()){
                $archivo =$uploadedFile->saveAs($ruta);
                #Lectura del Excel

                $phpExcelPath = Yii::getPathOfAlias('ext.Excel.PHPExcel.Classes');
                $phpExcelPath2 = Yii::getPathOfAlias('application.extensions.Excel.PHPExcel.Classes.PHPExcel');


                spl_autoload_unregister(array('YiiBase','autoload'));
                include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
                include($phpExcelPath.DIRECTORY_SEPARATOR.'PHPExcel'.DIRECTORY_SEPARATOR.'Reader'.DIRECTORY_SEPARATOR.'Excel2007.php');
                include($phpExcelPath2 . DIRECTORY_SEPARATOR . 'IOFactory.php');
                spl_autoload_register(array('YiiBase','autoload'));
                // Cargando la hoja de calculo
                $extension = $uploadedFile->getExtensionName();

                if($extension=="xls"){ // Si es .xls o xlsx
                    $objReader = new PHPExcel_Reader_Excel5();
                }else{
                    $objReader = new PHPExcel_Reader_Excel2007();
                }


                $objPHPExcel = $objReader->load($ruta); //carga en objphpExcel por medio de objReader,el nombre del archivo
                $objPHPExcel->setActiveSheetIndex(0);
                $numRows = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();

                $col_base = 'A';
                $num_rows_depurado = 0;
                $num_rows_vacia = array('cant'=>0, 'rows_vacias'=>'');

                $filas = $objPHPExcel->getActiveSheet()->getHighestRow($col_base);
                $columna = $objPHPExcel->getActiveSheet()->rangeToArray($col_base.'1:'.$col_base.$filas, "", false, false, true);
                unset($columna['1'],$columna['2'],$columna['3']);

                foreach ($columna as $celda => $data) {

                  if ($data[$col_base] != "" || $data[$col_base] != null) {

                    $num_rows_depurado++;

                  }else{

                    $num_rows_vacia['cant']++;
                    $num_rows_vacia['rows_vacias'] .= $col_base.$celda.", ";
                  }
                }
                ########################################################################################
                ########################################################################################

                $numRows = intval($numRows) - intval($num_rows_vacia['cant']);

                $valido=true;
                if ($numRows>3) {

                    # Valida que los campos de la primera linea cumplan con el formato
                    $model->cant_pago = $objPHPExcel->getActiveSheet()->getCell('A2')->getCalculatedValue();
                    $model->total_pago = $objPHPExcel->getActiveSheet()->getCell('B2')->getCalculatedValue();
                    $model->total_pago=str_replace(',', '.',str_replace('.', ',', $model->total_pago));
                    $model->fecha_pago = $objPHPExcel->getActiveSheet()->getCell('C2')->getCalculatedValue();
					$model->scenario='carga_ajuste';
                    if($model->validate()){
                        $e_rrores=array();
                        # Valida La primera linea del archivo, contra el formato de nombre de archivo
                        if($model->cant_pago!=$numRows-3){
                            $valido=FALSE;
                            $errorLinea.='La cantidad de ('.$model->cant_pago.') ordenes de pagos declarados en la cabecera no coincide con la cantidad de ('.($numRows-3).') presentes en el archivo; ';
                        }

                        # Recorre el archivo en busca de errores
                        $e_rrores[0]=array('Total persona','Total del pago','Fecha del pago',NULL,NULL,'ERRORES');
                        $e_rrores[1]=array($model->cant_pago,$model->total_pago,$model->fecha_pago,NULL,NULL,$errorLinea);
                        $e_rrores[2]=array('Tipo de persona','Cédula/Rif','Monto del pago','Drescripción',NULL,NULL,'ERRRORES');

                        for ($fila=4;$fila<=$model->cant_pago+3;$fila++){
                            $errores='';
                            $valid= TRUE;
                            $modelOrden=new OrdenPago('RegistroIndividualMasivo');
                            $modelOrden->id_tipo_persona=strtoupper(($objPHPExcel->getActiveSheet()->getCell('A'.$fila)->getCalculatedValue()));
                            $modelOrden->rif = $objPHPExcel->getActiveSheet()->getCell('B'.$fila)->getCalculatedValue();
                            $modelOrden->monto_pago = str_replace('.', ',',$objPHPExcel->getActiveSheet()->getCell('C'.$fila)->getCalculatedValue());
                            $modelOrden->descripcion = $objPHPExcel->getActiveSheet()->getCell('D'.$fila)->getCalculatedValue();
                            $modelOrden->id_concepto = $model->id_concepto;
                            if(!$modelOrden->validate()){
                                $valid= FALSE;#Si contiene al menos un error, el archivo es devuelto
                                $errores.=$modelOrden->getError('id_tipo_persona').' ';
                                $errores.=$modelOrden->getError('rif').' ';
                                $errores.=$modelOrden->getError('monto_pago').' ';
                                $errores.=$modelOrden->getError('descripcion').' ';
                                if(!$modelOrden->getError('monto_pago'))
                                    $totalPago+=str_replace(',', '.',$modelOrden->monto_pago);
                            }
                            else{ 
                                $valid = TRUE;
                                $e_rrores[$fila]=array($modelOrden->id_tipo_persona,$modelOrden->rif,$modelOrden->monto_pago,$modelOrden->descripcion);
                                
                                $totalPago+=str_replace(',', '.',$modelOrden->monto_pago);
                            }

                            if(!$valid){
                              $valido= $valido && FALSE;
                              $e_rrores[$fila]=array($modelOrden->id_tipo_persona,$modelOrden->rif,$modelOrden->monto_pago,$modelOrden->descripcion,NULL,NULL,$errores);
                            }
                        }
                        if(round($totalPago,2)!=round(str_replace(',', '.', $model->total_pago),2)){
                            $valido=FALSE; echo $valido;
                            $errorLinea.='El total de pago declarado en el archivo '.$model->total_pago.', no coincide con la sumatoria de los ajustes presentes en el mismo '.$totalPago.';  ';
                            $e_rrores[1]=array($model->cant_pago,$model->total_pago,$model->fecha_pago,NULL,NULL,$errorLinea);
                        }
                        # Si el archivo no contiene errores se procede al guardado
                        if ($valido){
                            $transaction=Yii::app()->db->beginTransaction();
                        	try{
                                #Guarda el encabezado del xls en el modelo
                                if($model->save()){
                                	#Recorre el archivo excel para cargar los apòrtes
                                	for ($fila=4;$fila<=$model->cant_pago+3;$fila++){
                                        $modelOrden=new OrdenPago('RegistroIndividualMasivo');
                                        $modelOrden->id_tipo_persona=strtoupper($objPHPExcel->getActiveSheet()->getCell('A'.$fila)->getCalculatedValue());
                                        $modelOrden->rif = $objPHPExcel->getActiveSheet()->getCell('B'.$fila)->getCalculatedValue();
                                        $modelOrden->monto_pago = str_replace('.', ',',$objPHPExcel->getActiveSheet()->getCell('C'.$fila)->getCalculatedValue());
                                        $modelOrden->descripcion = $objPHPExcel->getActiveSheet()->getCell('D'.$fila)->getCalculatedValue();
                                        $modelOrden->id_datos_nomina_orden_pago = $model->id;
                                        $modelOrden->id_concepto = $model->id_concepto;
                                        $modelOrden->save();

                                        $modelSeguimiento = new OrdenPagoSeguimiento();
                                        $modelSeguimiento->id_orden_pago = $modelOrden->id;
                                        $modelSeguimiento->id_estatus_orden_pago = 1;
                                        $modelSeguimiento->save();
                                    }
                                    $modelEstatusNomina= new DatosNominaOrdenPagoSeguimiento();
                                    $modelEstatusNomina->id_datos_nomina_orden_pago=$model->id;
                                    $modelEstatusNomina->id_estatus_orden_pago = 1;
                                    $modelEstatusNomina->actual=TRUE;
                                    $modelEstatusNomina->save();
                                    $transaction->commit(); #Ejecuta todas las operaciones
                                    $this->redirect(array('view','id'=>$model->id));
                                }
                                else {
                                #No se pudo guargar el archivo
                                    Yii::app()->user->setFlash('error', "No se pudo Guargar el Archivo");
                                }
                            }
                            catch(Exception $e){//echo "<pre>";print_r($e);exit;
                                $transaction->rollback();
                                Yii::app()->user->setFlash('error', "Ocurrio un error durante el guardado, se han revertido todos los cambios");
                                $this->redirect(array('admin'));
                            }
                        }
                        else{ #Si el Archivo contiene errores
							// echo"<pre>";print_r($e_rrores);exit;
                            $objPHPExcel2 = new PHPExcel();
                            $objPHPExcel2->getActiveSheet()->fromArray($e_rrores,NULL,'A1');
                            $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel2);

                            $objWriter->setOffice2003Compatibility(true);

                            $objWriter->save(Yii::app()->params['rutaErroresNominaAportes']."errores_".$model->nombre_archivo.".xlsx");
                            Yii::app()->user->setFlash('error', "El archivo contiene errores, verifique ".CHtml::link('AQUÍ', Yii::app()->params['rutaErroresNominaAportes']."errores_".$model->nombre_archivo.".xlsx",array('target'=>'_blank')));

                        }

                    }# Fin de la validacion de la primera linea

                }# Fin if ($numRows>3), es decir, si el archivo no esta vacio
                else { 
                	$model->addError('cant_pago', 'El Archivo no contiene ningun ajuste');
                }
            }
        }

		$this->render('create',array(
			'model'=>$model,
			'postDatos'=>$postDatos,
		));
	
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['DatosNominaOrdenPago']))
		{
			$model->attributes=$_POST['DatosNominaOrdenPago'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
    public function actionAprobar($id)
    {
        $model=$this->loadModel($id);
        if ($model->id_estatus != 1) {
            Yii::app()->user->setFlash('error', 'Para poder aprobar la nomina de orden de pago debe estar en estatus REVISIÓN');
            $this->redirect(array('view', 'id' => $model->id));
        }
        $modelSeguimiento = new DatosNominaOrdenPagoSeguimiento();
        if(isset($_POST['DatosNominaOrdenPagoSeguimiento']))
        {
            $modelSeguimiento->attributes=$_POST['DatosNominaOrdenPagoSeguimiento'];
            if (isset($_POST['yt0'])) {
                    $modelSeguimiento->id_estatus_orden_pago = 2;//($model->refinanciado==0)?2:(($model->refinanciado==1)?7:9);
                    $modelSeguimiento->scenario='aprobar';
                    $texto='La nómina de orden de pago Nº #'.$model->id.' ha sido APROBADO.';
                }
                if (isset($_POST['yt1'])) {
                    $modelSeguimiento->id_estatus_orden_pago = 4;
                    $modelSeguimiento->scenario='denegar';
                    
                   $texto='La nómina de orden de pago Nº #'.$model->id.' ha sido RECHAZADA.';
                }
            if($modelSeguimiento->validate()){
                $transaction = Yii::app()->db->beginTransaction();
                try {
                    DatosNominaOrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_datos_nomina_orden_pago=:id_datos_nomina_orden_pago',[':id_datos_nomina_orden_pago'=>$model->id]);
                    $modelSeguimiento->id_datos_nomina_orden_pago = $model->id;
                    $modelSeguimiento->save();
                    foreach ($model->idOrdenPago as $key => $value) {
                        OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$value->id]);
                        $modelSeguimientoOP = new OrdenPagoSeguimiento();
                        $modelSeguimientoOP->id_orden_pago = $value->id;
                        $modelSeguimientoOP->id_estatus_orden_pago = $modelSeguimiento->id_estatus_orden_pago;
                        $modelSeguimientoOP->observacion = $modelSeguimiento->observacion;
                        $modelSeguimientoOP->save();
                    }
                    $transaction->commit();
                    Yii::app()->user->setFlash('success',$texto);
                    $this->redirect(array('view','id'=>$model->id));

                }catch (Exception $e){
                    //echo "<pre>";print_r($e);exit;
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', "Ocurrio un error durante el guardado, se han revertido todos los cambios");
                    $this->redirect(array('view','id'=>$model->id));
                }
            }
        }

        $this->render('aprobar',array(
            'model'=>$model,
            'modelSeguimiento'=>$modelSeguimiento,
        ));

    }
    public function actionRechazar($id)
    {
        $model=$this->loadModel($id);
        DatosNominaOrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_datos_nomina_orden_pago=:id_datos_nomina_orden_pago',[':id_datos_nomina_orden_pago'=>$model->id]);
        $modelSeguimiento = new DatosNominaOrdenPagoSeguimiento();
        $modelSeguimiento->id_estatus_orden_pago = 4;
        $modelSeguimiento->id_datos_nomina_orden_pago = $model->id;
        $modelSeguimiento->save();
        foreach ($model->idOrdenPago as $key => $value) {
            OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$value->id]);
            $modelSeguimiento = new OrdenPagoSeguimiento();
            $modelSeguimiento->id_orden_pago = $value->id;
            $modelSeguimiento->id_estatus_orden_pago = 4;
            $modelSeguimiento->save();
        }



        Yii::app()->user->setFlash('success', 'La orden de pago se ha rechazada exitosamente');
        $modelSeguimiento->save();

        $this->redirect(array('view','id'=>$model->id));
    }



    public function actionPagar($id)
    {
        $model=$this->loadModel($id);
        if ($model->id_estatus != 2) {
            Yii::app()->user->setFlash('error', 'Para poder pagar la nómina debe estar en estatus aprobado');
            $this->redirect(array('view', 'id' => $model->id));
        }
        $modelProcesoPago = new ProcesoPago('pagar_orden_pago');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['ProcesoPago']))
        {
            $modelProcesoPago->attributes=$_POST['ProcesoPago'];
            if($modelProcesoPago->validate()){
                $transaction = Yii::app()->db->beginTransaction();
                try {
                    DatosNominaOrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_datos_nomina_orden_pago=:id_datos_nomina_orden_pago',[':id_datos_nomina_orden_pago'=>$model->id]);
                    $modelSeguimiento = new DatosNominaOrdenPagoSeguimiento();
                    $modelSeguimiento->id_estatus_orden_pago = 5;
                    $modelSeguimiento->id_datos_nomina_orden_pago = $model->id;
                    $modelSeguimiento->save();
                    foreach ($model->idOrdenPago as $key => $value) {
                        OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$value->id]);
                        $modelSeguimiento = new OrdenPagoSeguimiento();
                        $modelSeguimiento->id_orden_pago = $value->id;
                        $modelSeguimiento->id_estatus_orden_pago = 5;
                        $modelSeguimiento->save();
                    }
                    $modelProcesoPago->id_proceso = $model->id;
                    $modelProcesoPago->id_nombre_proceso = 11;
                    $modelProcesoPago->save();



                    $transaction->commit();
                    Yii::app()->user->setFlash('success', 'La orden de pago se ha PAGADA exitosamente');
                    $this->redirect(array('view','id'=>$model->id));

                }catch (Exception $e){//echo "<pre>";print_r($e);exit;
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', "Ocurrio un error durante el guardado, se han revertido todos los cambios");
                    $this->redirect(array('view','id'=>$model->id));
                }
            }
        }

        $this->render('pagar',array(
            'model'=>$model,
            'modelProcesoPago'=>$modelProcesoPago,
        ));
    }

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('DatosNominaOrdenPago');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new DatosNominaOrdenPago('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['DatosNominaOrdenPago']))
			$model->attributes=$_GET['DatosNominaOrdenPago'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return DatosNominaOrdenPago the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=DatosNominaOrdenPago::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param DatosNominaOrdenPago $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='datos-nomina-orden-pago-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
