<?php

class ActiveFichaDetalle
{
    protected $asociado = null;
    protected $options;
    protected $type = null;

    public function __construct($asociado, $options = [])
    {
        $this->asociado = $asociado;
        $this->options = $options;

        if ($this->asociado === null) {
            throw new Exception('El parametro "asociado" no puede estar vacia.');
        }
    }

    public function get($type = null)
    {
        $this->type = $type;

        if ($this->type === null) {
            throw new Exception('El parametro "type" no puede estar vacia.');
        }

        switch ($type) {
            case 'aporte_asociado':
                return $this->exclude('aporte_patrono', [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AO',
                ]);
            case 'aporte_patrono':
                return $this->exclude('aporte_asociado', [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AO',
                ]);
            case 'aporte_extra_socio':
                return $this->exclude(1, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AE',
                ]);
            case 'aporte_extra_patrono':
                return $this->exclude(2, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AE',
                ]);
            case 'asignacion_monto_asociado':
                return $this->exclude([
                    'id_tipo_ajuste' => 2,
                    'id_tipo_movimiento' => [1, 3],
                ], [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AH',
                ]);
            case 'asignacion_monto_patrono':
                return $this->exclude([
                    'id_tipo_ajuste' => 2,
                    'id_tipo_movimiento' => [2, 3],
                ], [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AH',
                ]);
            case 'dividendos':
                return $this->exclude(null, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'D',
                ]);
            case 'descuento_monto_asociado':
                return $this->exclude([
                    'id_tipo_ajuste' => 1,
                    'id_tipo_movimiento' => [1, 3],
                ], [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AH',
                ]);
            case 'descuento_monto_patrono':
                return $this->exclude([
                    'id_tipo_ajuste' => 1,
                    'id_tipo_movimiento' => [2, 3],
                ], [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'AH',
                ]);
            case 'retiro_parcial':
                return $this->exclude(null, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'RP',
                ]);
            case 'prestamos_no_afectados':
                return $this->exclude($this->options, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'CNAPP',
                ]);
            case 'prestamos_afectados_capital':
                return $this->exclude($this->options, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'CAPP',
                ]);
            case 'prestamos_afectados_interes':
                return $this->exclude($this->options, [
                    'id' => $this->asociado->idasociado,
                    'grid' => 'CAPP',
                ]);
        }
    }

    protected function exclude($type, $options = null)
    {
        switch ($options['grid']) {
            case 'AO':
                list($header, $columns) = $this->aportesOrdinarios($options['id']);

                return [
                    [
                        'title' => 'Aportes ordinarios',
                        'grid' => array_merge($header, [
                            'columns' => (new Warp($columns))->filter(function ($column) use ($type) {
                                return $column['name'] !== $type;
                            }),
                        ]),
                    ],
                ];
            case 'AE':
                return [
                    [
                        'title' => 'Aportes carga individual',
                        'grid' => $this->aportesVoluntarios($options['id'], $type),
                    ],
                    [
                        'title' => 'Aportes carga masiva',
                        'grid' => $this->aportesVoluntariosMasivo($options['id'], $type),
                    ],
                ];
            case 'AH':
                return [
                    [
                        'title' => 'Ajustes de haberes',
                        'grid' => $this->ajustesDeHaberes($options['id'], $type),
                    ],
                ];
            case 'D':
                return [
                    [
                        'title' => 'Dividendos',
                        'grid' => $this->dividendos($options['id']),
                    ],
                ];
            case 'RP':
                return [
                    [
                        'title' => 'Dividendos',
                        'grid' => $this->retirosParciales($options['id']),
                    ],
                ];
            case 'CNAPP':
                return [
                    [
                        'title' => 'Capital de cuotas no afectadas',
                        'grid' => $this->cuotasNoAfectadas($options['id'], $type),
                    ],
                ];
            case 'CAPP':
                return [
                    [
                        'title' => 'Cuotas afectadas por prenomina',
                        'grid' => $this->cuotasAfectadas($options['id'], $type),
                    ],
                ];
        }
    }

    private function aportesOrdinarios($id)
    {
        $model = new AporteOrdinario('search');

        return [
            [
                'id' => 'aporte-ordinario-grid',
                'type' => 'striped bordered condensed',
                'enableSorting' => false,
                'dataProvider' => $model->searchAporteOrdinarioFichaLiquidacion($id, [
                    'cedula' => $this->asociado->cedula,
                    'type' => $this->type
                ]),
            ],
            [
                [
                    'name' => 'nombre_aporte',
                    'value' => '$data->idTxt->nombre_archivo',
                ],
                [
                    'name' => 'fecha_aporte',
                    'value' => '$data->fecha_aporte',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'sueldo_base',
                    'value' => '$data->sueldo_base',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'aporte_patrono',
                    'value' => '$data->aporte_patrono',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'aporte_asociado',
                    'value' => '$data->aporte_asociado',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'total_aporte',
                    'value' => '$data->total_aporte',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'aporte_pagado',
                    'value' => '$data->aporte_pagado',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'aporte_x_pagar',
                    'value' => '$data->aporte_x_pagar',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'tipo_descuento',
                    'name' => 'id_tipo_nomina',
                    'value' => '($data->idTipoNomina)?$data->idTipoNomina->nombre_nomina:""',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'estatus_aporte',
                    'value' => '$data->idTxt ? $data->idTxt->getEstatus() : ""',
                    'type' => 'raw',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
            ],
        ];
    }

    private function aportesVoluntarios($id, $excluir)
    {
        return [
            'id' => 'aporte-voluntario-individual-grid',
            'type' => 'striped bordered condensed',
            'ajaxUrl' => Yii::app()->createUrl('/aportes/AporteOrdinario/admin'),
            'dataProvider' => AporteVoluntario::model()->searchAporteVoluntarioFichaLiquidacion($id, $excluir, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type
            ]),
            'columns' => [
                [
                    'name' => 'codigo',
                    'value' => '(!empty($data->id_txt_integrado)?$data->id_txt_integrado:"Aporte Individual")',
                ],
                [
                    'name' => 'monto',
                    'value' => '$data->monto',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'id_aportante',
                    'value' => '($data->idAportante)?$data->idAportante->nombre:""',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'fecha_pago',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'opcion_retiro',
                    'header' => 'Tipo Operación',
                    'value' => '$data->opcionRetiro ? $data->opcionRetiro->nombre : ""',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'estatus',
                    'value' => '$data->nombre_estatus',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'header' => 'Fecha estatus',
                    'name' => 'fecha_registro',
                    'value' => '! empty($data->fecha_status)
                        ? date("d-m-Y",strtotime($data->fecha_status))
                        :""',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
            ],
        ];
    }

    private function aportesVoluntariosMasivo($id, $excluir)
    {
        $model = new AporteVoluntario();

        return [
            'id' => 'aporte-voluntario-masivo-grid',
            'type' => 'striped bordered condensed',
            'ajaxUrl' => Yii::app()->createUrl('/aportes/AporteOrdinario/admin'),
            'dataProvider' => AporteVoluntario::model()->searchAVMasivoFichaLiquidacion($id, $excluir, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type
            ]),
            'columns' => [
                [
                    'name' => 'id_aportante',
                    'value' => '$data->idAportante->nombre',
                    'htmlOptions' => ['style' => 'text-align: center'],
                    'filter' => CHtml::activeDropDownList($model, 'id_aportante',
                    CHtml::listData(Aportante::model()->findAll('blnborrado=FALSE'), 'id', 'nombre'), ['prompt' => 'SELECCIONE']),
                ],
                [
                    'name' => 'opcion_retiro',
                    'value' => '$data->opcionRetiro ? $data->opcionRetiro->nombre : ""',
                    'htmlOptions' => ['style' => 'text-align: center'],
                    'filter' => CHtml::activeDropDownList(
                        $model,
                        'opcion_retiro',
                        CHtml::listData(TipoOperacion::model()->findAll(), 'id', 'nombre'),
                        ['prompt' => '--Seleccione--']
                    ),
                ],
                [
                    'name' => 'monto_cargado',
                    'value' => '$data->monto_cargado',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                    'type' => 'number',
                ],
                [
                    'name' => 'monto_retirado',
                    'value' => '$data->monto_retirado',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                    'type' => 'number',
                ],
                [
                    'name' => 'monto_comision_retira',
                    'value' => '$data->monto_comision_retira',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                    'type' => 'number',
                ],
                [
                    'name' => 'monto_capitalizado',
                    'value' => '$data->monto_capitalizado',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                    'type' => 'number',
                ],
                [
                    'name' => 'monto_comision_capitaliza',
                    'value' => '$data->monto_comision_capitaliza',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                    'type' => 'number',
                ],
                [
                    'name' => 'fecha_pagos',
                    'value' => 'implode("-",array_reverse(explode("-",$data->fecha_pago)))',
                    'class' => 'SYDateColumn',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'nombre_estatus',
                    'value' => '$data->idTxtIntegrado ? $data->idTxtIntegrado->getEstatus() : ""',
                    'type' => 'raw',
                    'filter' => CHtml::activeDropDownList($model, 'estatus',
                        CHtml::listData(EstatusTxt::model()->findAll('blnborrado=FALSE'), 'id', 'nombre_estatus'),
                        ['prompt' => 'SELECCIONE']
                    ),
                ],
            ],
        ];
    }

    private function ajustesDeHaberes($id, $options)
    {
        return [
            'id' => 'ajuste-haberes-grid',
            'type' => 'striped bordered condensed',
            'dataProvider' => AjusteHaberes::model()->searchAjusteSocioFichaLiquidacion($id, $options, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type
            ]),
            'columns' => [
                'numero_operacion',
                [
                    'name' => 'fecha_operacion',
                    'value' => '$data->fecha_operacion!=""?date("d-m-Y",strtotime($data->fecha_operacion)):""',
                    'class' => 'SYDateColumn',
                ],
                [
                    'name' => 'id_concepto_ajuste',
                    'value' => '$data->idConceptoAjuste->descripcion',
                ],
                [
                    'name' => 'id_tipo_ajuste',
                    'value' => '$data->idTipoAjuste->descripcion',
                ],
                [
                    'name' => 'id_tipo_movimiento',
                    'value' => '$data->idTipoMovimiento->descripcion',
                ],
                [
                    'name' => 'monto_asociado',
                    'value' => '$data->monto_asociado',
                    'type' => 'number',
                ],
                [
                    'name' => 'monto_patrono',
                    'value' => function ($model) {
                        return $model->monto_patrono ? $model->monto_patrono : 0;
                    },
                    'type' => 'number',
                ],
                'observacion',
                [
                    'name' => 'fecha_estatus',
                    'value' => '$data->fecha_estatus',
                ],
                [
                    'name' => 'id_estatus',
                    'value' => '$data->nombre_estatus',
                ],
            ],
        ];
    }

    private function dividendos($id)
    {
        return [
            'id' => 'dividendos-grid',
            'type' => 'striped bordered condensed',
            'dataProvider' => AsociadoDividendos::model()->searchDividendosSocioFichaLiquidacion($id, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type
            ]),
            'columns' => [
                [
                    'name' => 'ano',
                    'value' => '$data->ano',
                ],
                [
                    'name' => 'dividendo',
                    'value' => '$data->dividendo',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                ],
                [
                    'name' => 'fecha_registro',
                    'value' => '! empty($data->fecha_registro) ? $data->fecha_registro : ""',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'activo',
                    'value' => '$data->activo == 1 ? "Aprobado" : "Cargado"',
                ],
            ],
        ];
    }

    private function retirosParciales($id)
    {
        $dataProvider = RetiroParcial::model()->searchRetiroXAsociadoFichaLiquidacion($id, [
            'cedula' => $this->asociado->cedula,
            'type' => $this->type
        ]);
        $datos = $dataProvider->getData();

        return [
            'id' => 'retiro-parcial-grid',
            'ajaxUrl' => 'site/lastPosts',
            'type' => 'striped bordered condensed',
            'dataProvider' => $dataProvider,
            'columns' => [
                [
                    'header' => 'Fecha solicitud',
                    'name' => 'fecha_registro',
                    'value' => '$data->fecha_registro',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center'],
                    'footer' => 'Totales',
                    'footerHtmlOptions' => ['style' => 'font-weight: bold; text-align: center;'],
                ],
                [
                    'name' => 'monto_total_disponible',
                    'value' => '$data->monto_total_disponible',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right'],
                    'footer' => Yii::app()->format->number(Summary::total($datos, 'monto_total_disponible')),
                    'footerHtmlOptions' => ['style' => 'font-weight: bold; text-align: right', 'class' => 'footer_monto_solicitado_rp'],
                ],
                [
                    'name' => 'monto_solicitado',
                    'header' => 'Monto Solicitado',
                    'value' => '$data->monto_solicitado',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right', 'class' => 'td_monto_solicitado_rp'],
                    'footerHtmlOptions' => ['style' => 'font-weight: bold; text-align: right', 'class' => 'footer_monto_solicitado_rp'],
                    'footer' => Yii::app()->format->number(Summary::total($datos, 'monto_solicitado')),
                ],
                [
                    'name' => 'monto_aprobado',
                    'header' => 'Monto Aprobado',
                    'value' => '$data->monto_aprobado',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right', 'class' => 'td_monto_aprobado_rp'],
                    'footerHtmlOptions' => ['style' => 'font-weight: bold; text-align: right', 'class' => 'footer_monto_aprobado_rp'],
                    'footer' => Yii::app()->format->number(Summary::total($datos, 'monto_aprobado')),
                ],
                [
                    'header' => 'Fecha estatus',
                    'name' => 'fecha_estatus',
                    'value' => '$data->fecha_estatus',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
                [
                    'name' => 'idEstatus',
                    'value' => '$data->nombre_estatus',
                    'htmlOptions' => ['style' => 'text-align: center'],
                ],
            ],
        ];
    }

    private function cuotasNoAfectadas($id_asociado, $id_credito)
    {
        return [
            'id' => 'detalle-comprobante-grid',
            'enableSorting' => false,
            'dataProvider' => CreditoTablaAmortizacion::model()->searchCuotasNoafectadasFichaLiquidacion($id_asociado, $id_credito, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type,
                'view' => 'false',
                'options' => $id_credito
            ]),
            'columns' => [
                [
                    'header' => 'Número cuota',
                    'name' => 'numero_cuota',
                    'value' => '$data["numero_cuota"]',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Fecha de vencimiento',
                    'name' => 'fecha_vencimiento',
                    'value' => '! empty($data["fecha_vencimiento"]) ? $data["fecha_vencimiento"] : null',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center;'],
                ],
                [
                    'header' => 'Monto capital',
                    'name' => 'monto_capital',
                    'value' => '$data["monto_capital"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Monto interes',
                    'name' => 'monto_interes',
                    'value' => '$data["monto_interes"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Monto de la cuota',
                    'name' => 'monto_cuota',
                    'value' => '$data["monto_cuota"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Monto pagado',
                    'name' => 'monto_pagado',
                    'value' => '$data["monto_pagado"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
            ],
        ];
    }

    private function cuotasAfectadas($id, $tipo_credito)
    {
        return [
            'id' => 'detalle-comprobante-grid',
            'enableSorting' => false,
            'dataProvider' => CreditoTablaAmortizacion::model()->searchCuotasAfectadasFichaLiquidacion($id, $tipo_credito, [
                'cedula' => $this->asociado->cedula,
                'type' => $this->type,
                'view' => 'false',
                'options' => $tipo_credito
            ]),
            'columns' => [
                [
                    'header' => 'Número',
                    'name' => 'numero_cuota',
                    'value' => '$data["numero_cuota"]',
                    'htmlOptions' => ['style' => 'width: 1%; text-align: right;'],
                ],
                [
                    'header' => 'Nombre de archivo',
                    'name' => 'nombre_archivo',
                    'value' => '$data["nombre_archivo"]',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Fecha de vencimiento',
                    'name' => 'fecha_vencimiento',
                    'value' => '$data["fecha_vencimiento"] ? $data["fecha_vencimiento"] : ""',
                    'type' => 'date',
                    'htmlOptions' => ['style' => 'text-align: center;'],
                ],
                [
                    'header' => 'Capital',
                    'name' => 'monto_capital',
                    'value' => '$data["monto_capital"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Capital pendiente',
                    'name' => 'monto_capital_pendiente',
                    'value' => '$data["monto_capital_pendiente"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Interes',
                    'name' => 'monto_interes',
                    'value' => '$data["monto_interes"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Interes pendiente',
                    'name' => 'monto_interes_pendiente',
                    'value' => '$data["monto_interes_pendiente"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Monto de la cuota',
                    'name' => 'monto_cuota',
                    'value' => '$data["monto_cuota"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Monto pagado',
                    'name' => 'monto_pagado',
                    'value' => '$data["monto_pagado"]',
                    'type' => 'number',
                    'htmlOptions' => ['style' => 'text-align: right;'],
                ],
                [
                    'header' => 'Estatus',
                    'name' => 'nombre_estatus',
                    'value' => '$data["nombre_estatus"]',
                    'htmlOptions' => ['style' => 'text-align: center;'],
                ],
            ],
        ];
    }
}
