<?php

class OrdenPagoController 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', 'excelOrdenPago'),
				'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', [
			'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 OrdenPago('Registrar');
        $model->id_tipo_carga = 2; // individual

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

		if(isset($_POST['OrdenPago']))
		{
			$model->attributes=$_POST['OrdenPago'];

            if($model->validate()){
                $model->save();
                $modelSeguimiento = new OrdenPagoSeguimiento();
                $modelSeguimiento->id_orden_pago = $model->id;
				$modelSeguimiento->id_estatus_orden_pago = 1;
				$modelSeguimiento->save();

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

		if($model->idproveedor !=''){
			if($model->id_tipo_orden==1){
				$sql ="SELECT id, concat_ws(' ',descripcion, case when cuenta_corriente = true then 'Cuenta Corriente' ELSE 'Cuenta de Ahorro' END, cuenta_bancaria) AS cuenta_bancaria
					FROM proveedor_cuenta_banco as t
					JOIN banco as b ON t.idbanco = b.idbanco
					WHERE idproveedor=".$model->idproveedor;
               	$bancos = CHtml::listData( ProveedorCuentaBanco::model()->findAllBySql($sql), 'id', 'cuenta_bancaria');

               

            }
            elseif ($model->id_tipo_orden==2) {
               $sql ="SELECT id, concat_ws(' ',descripcion, case when cuenta_corriente = true then 'Cuenta Corriente' ELSE 'Cuenta de Ahorro' END, cuenta_bancaria) as cuenta_bancaria 
					FROM asociado_cuenta_banco as t
					JOIN banco as b ON t.id_banco = b.idbanco
					WHERE idasociado=".$model->idproveedor;
               	$bancos = CHtml::listData( AsociadoCuentaBanco::model()->findAllBySql($sql), 'id', 'cuenta_bancaria');
            }
		}

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

	/**
	 * 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 actionAprobar($id)
	{
		$model=$this->loadModel($id);
        $model->fecha_comprobante = date('d-m-Y');

		if ($model->id_estatus != 1) {
            Yii::app()->user->setFlash('error', 'Para poder pagar la orden de pago debe estar en estatus REVISIÓN');
            $this->redirect(array('view', 'id' => $model->id));
        }
		$modelSeguimiento = new OrdenPagoSeguimiento();
		// OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$model->id]);
		// $modelSeguimiento->id_orden_pago = $model->id;
		// $modelSeguimiento->id_estatus_orden_pago = 2;
		// $modelSeguimiento->save();
		// Yii::app()->user->setFlash('success', 'La orden de pago se ha aprobado exitosamente');

		if(isset($_POST['OrdenPagoSeguimiento']))
		{
			$modelSeguimiento->attributes=$_POST['OrdenPagoSeguimiento'];

            Yii::import('application.modules.contable.models.*', true);
            if (ParamEscenarios::fechaComprobante(['aprobar_orden_pago' => 7])) {
                $model->fecha_comprobante = $_POST['OrdenPago']['fecha_comprobante'];
            }

			if (isset($_POST['yt0'])) {
                $modelSeguimiento->id_estatus_orden_pago = 2;//($model->refinanciado==0)?2:(($model->refinanciado==1)?7:9);
                $modelSeguimiento->scenario='aprobar';
                $texto='La solicitud 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 solicitud de orden de pago Nº #'.$model->id.' ha sido RECHAZADA.';
            }

			if($modelSeguimiento->validate()){
				$transaction = Yii::app()->db->beginTransaction();
                try {
					OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$model->id]);
					$modelSeguimiento->id_orden_pago = $model->id;
					$modelSeguimiento->save();

                    $model->setFechaRegistro($modelSeguimiento->fecha_registro);
                    //////////////////////////// Contabilización comprobante inicio ////////////////////////////
                    Yii::import('application.modules.contable.models.comprobantes.*', true);
                    Yii::import('application.modules.contable.models.comprobantes.orden_pago.*', true);
                    (new Aprobacion($model))->contabilizar();
                    //////////////////////////// Contabilización comprobante fin ///////////////////////////////

				 	$transaction->commit();
					Yii::app()->user->setFlash('success',$texto);
					$this->redirect(array('view','id'=>$model->id));
                } catch (Exception $e) {
    				$transaction->rollback();
                    Yii::app()->user->setFlash('error', $e->getMessage());
                }
			}
		}

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

	}

	public function actionRechazar($id)
	{
		$model = $this->loadModel($id);
        $model->setScenario('rechazar');
        $model->fecha_comprobante = date('d-m-Y');

        $conceptos = $model->isAutomatico() ? Operacion::getForReverso() : [];

        if ($model->isAutomatico()) {
            $model->setScenario('orden_automatica');
        }

        if (! isset($_POST['OrdenPago'])) {
            return $this->render('reversar', [
                'model' => $model,
                'conceptos' => $conceptos,
            ]);
        }

        $model->setAttributes($_POST['OrdenPago']);

        if (! $model->rechazar()) {
            return $this->render('reversar', [
                'model' => $model,
                'conceptos' => $conceptos,
            ]);
        }

        return $this->redirect(array('admin'));
	}



	public function actionPagar($id)
	{
		$model=$this->loadModel($id);
        $model->fecha_comprobante = date('d-m-Y');
        Yii::import('application.modules.contable.models.*', true);

		if ($model->id_estatus != 2) {
            Yii::app()->user->setFlash('error', 'Para poder pagar la orden de pago 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 (ParamEscenarios::fechaComprobante(['pagar_orden_pago' => 8])) {
                $model->fecha_comprobante = $_POST['OrdenPago']['fecha_comprobante'];
            }

			if($modelProcesoPago->validate()){
				$transaction = Yii::app()->db->beginTransaction();
                try {
					OrdenPagoSeguimiento::model()->updateAll(['actual'=>false],'id_orden_pago=:id_orden_pago',[':id_orden_pago'=>$model->id]);
					$modelSeguimiento = new OrdenPagoSeguimiento();
					$modelSeguimiento->id_orden_pago = $model->id;
					$modelSeguimiento->id_estatus_orden_pago = 5;
					$modelSeguimiento->save();
	                $modelProcesoPago->id_proceso = $model->id;
	                $modelProcesoPago->id_nombre_proceso = 10;
	                $modelProcesoPago->save();

                    $model->setFechaRegistro($modelSeguimiento->fecha_registro);
                    $model->setProcesoPago($modelProcesoPago->id);
                    $model->setBancoPago($modelProcesoPago->id_banco);
                    //////////////////////////// Contabilización comprobante inicio ////////////////////////////
                    Yii::import('application.modules.contable.models.comprobantes.*', true);
                    Yii::import('application.modules.contable.models.comprobantes.orden_pago.*', true);
                    (new PagoIndividual($model))->contabilizar();
                    //////////////////////////// Contabilización comprobante fin ///////////////////////////////

				 	$transaction->commit();
					Yii::app()->user->setFlash('success', 'La orden de pago se ha <strong>pagado</strong> exitosamente');
					$this->redirect(array('admin'));

                }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->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('OrdenPago');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

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

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

    public function actionExcelOrdenPago()
    {
        $datos = $_SESSION['datos_filtrados'];

        if (count($datos) == 0) {
            exit;
        }

        $datos = $datos->getData();

        if (count($datos) == 0) {
            exit;
        }

        $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'));
        $excel = new PHPExcel();

        foreach(range('A', 'N') as $columnID) {
            $excel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }

        $columna = 0;
        foreach ([
            'Tipo de orden', 'Tipo de carga', 'Concepto de operación', 'Tipo de persona', 'Cédula / R.I.F.',
            'Razón social', 'Monto pagado','Banco origen', 'Cuenta origen', 'Banco destino', 'Cuenta destino',
            'Fecha estatus', 'Estatus', 'Descripción'
        ] as $titulo) {
            $excel->getActiveSheet()->getStyleByColumnAndRow($columna, 1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $excel->getActiveSheet()->getStyleByColumnAndRow($columna, 1)->getFont()->setBold(true);
            $excel->getActiveSheet()->getStyleByColumnAndRow($columna, 1)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
            $excel->getActiveSheet()->getStyleByColumnAndRow($columna, 1)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
            $excel->getActiveSheet()->getStyleByColumnAndRow($columna, 1)->getFill()->getStartColor()->setARGB('1C336E');
            $excel->getActiveSheet()->setCellValueByColumnAndRow($columna, 1,  $titulo);
            $columna++;
        }

        $fila = 2;
        foreach ($datos as $campos) {
            $excel->getActiveSheet()->setCellValueByColumnAndRow(0, $fila,  $campos['tipo_orden']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(1, $fila,  $campos['tipo_carga']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(2, $fila,  $campos['nombre_concepto']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(3, $fila,  $campos['nombre_tipo_persona']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(4, $fila,  $campos['rif']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(5, $fila,  $campos['razon_social']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(6, $fila,  $campos['monto_pago']);
            $excel->getActiveSheet()->getStyleByColumnAndRow(6, $fila)->getNumberFormat()->setFormatCode('#,##0.00');
            $excel->getActiveSheet()->getStyleByColumnAndRow(6, $fila)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(7, $fila,  $campos['banco_origen']);
            $excel->getActiveSheet()->setCellValueExplicitByColumnAndRow(8, $fila,  $campos['cuenta_bancaria_origen']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(9, $fila,  $campos['banco_proveedor']);
            $excel->getActiveSheet()->setCellValueExplicitByColumnAndRow(10, $fila,  $campos['cuenta_bancaria_proveedor']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(11, $fila, Yii::app()->format->date($campos['fecha_estatus']));
            $excel->getActiveSheet()->setCellValueByColumnAndRow(12, $fila, $campos['estatus']);
            $excel->getActiveSheet()->setCellValueByColumnAndRow(13, $fila, $campos['descripcion']);
            $fila++;
        }

        // Total
        $excel->getActiveSheet()->setCellValueByColumnAndRow(0, $fila, 'Total');
        $excel->getActiveSheet()->getStyleByColumnAndRow(0, $fila)->getFont()->setBold(true);

        $ultimoDato = $fila - 1;
        $excel->getActiveSheet()->setCellValue("G{$fila}", "=SUM(G2:G{$ultimoDato})");
        $excel->getActiveSheet()->getStyle("G{$fila}")->getNumberFormat()->setFormatCode('#,##0.00');
        $excel->getActiveSheet()->getStyle("G{$fila}")->getFont()->setBold(true);

        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="Ordenes de pago.xlsx"');

        $objWriter = new PHPExcel_Writer_Excel2007($excel);
        $objWriter->setOffice2003Compatibility(true);
        $objWriter->save('php://output');
    }

	/**
	 * 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 OrdenPago the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=OrdenPago::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

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