<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js', CClientScript::POS_HEAD); ?>
<?php  Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl.'/js/bootstrap2-toggle.js');
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/bootstrap2-toggle.css');
?>

<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', [
    'id' => 'credito-abono-form',
    'enableAjaxValidation' => false,
]); ?>
<?php
Yii::app()->clientScript->registerScript('tablaAmortizacion2', '
            $(document).ready(function() {
                $(\'.campo_numerico\').mask(\'#.##0,00\', {reverse: true});
                $(\'#prestamos-grid\').selGridView(\'addSelection\', ['.$model->idcredito.']);
                if($("#'.Chtml::activeId($model, 'cedula').'").val()!=""){
                        datosPersonales();
                }
            });
	');
?>
<h3 class="text-center">Abonos a préstamos</h3>
<?php echo $form->errorSummary($model); ?>
<h4>Solicitante</h4>
<p class="help-block">Campos con <span class="required">*</span> son requeridos.</p>
<table class="table table-bordered">
    <tr>
        <td style="width: 25%"><b>
                <?php echo $form->labelEx($model, 'cedula'); ?></b></td>
        <td style="width: 25%">
            <div style="display:table">
                <div style="float:left; width: 85%;">
                    <?php echo $form->textField($model, 'cedula', ['maxlength' => '10']); ?>
                    <?php echo  $form->error($model, 'cedula'); ?>

                </div>
                <div style="float:right;width: 15%;">
                    <?php echo CHtml::htmlButton('<i class="icon-search"></i>', ['type' => 'button', 'id' => 'btn_buscar_datos_personales', 'class' => 'btn btn-success icon button', 'onClick' => 'datosPersonales()']); ?>

                </div>
            </div>

            <div id="mensajesSistema" class="datosPersonales"></div>
        </td>
        <td style="width: 20%"><b>Nombres y apellidos</b></td>
        <td style="width: 30%">
            <div id="nombres_apellidos" class="datosPersonales"></div>
        </td>
    </tr>
    <tr>
        <td><b>Empresa</b></td>
        <td>
            <div id="empresa" class="datosPersonales"></div>
        </td>
        <td><b>Unidad</b></td>
        <td>
            <div id="unidad" class="datosPersonales"></div>
        </td>
    </tr>
    <tr>
        <td><b>&Uacute;ltimo sueldo</b></td>
        <td>
            <div id="sueldo" class="datosPersonales"></div>
        </td>
        <td><b>Porcentaje de aporte</b></td>
        <td>
            <div id="porcentaje" class="datosPersonales"></div>
        </td>
    </tr>
    <tr>
        <td><b>Fecha de inscripci&oacute;n</b></td>
        <td>
            <div id="fecha_inscripcion" class="datosPersonales"></div>
        </td>
        <td><b>Estatus</b></td>
        <td>
            <div id="estatus" class="datosPersonales"></div>
        </td>
    </tr>
    <tr>
        <td colspan="4" id="calculadoraHaberesSocio" class="datosCredito" style="display: none"></td>
    </tr>
</table>

<br>
<h4>Préstamos</h4>
<?php  $this->widget('ext.selgridview.BootSelGridView', [
    'id' => 'prestamos-grid',
    'dataProvider' => $modelReporteCredito->searchAbonoPrestamo(null),
    'selectableRows' => $modelConfGeneralCreditoAbono->abono_multiple_credito_adm ? 100 : 1,
    'columns' => [
        [
            'id' => 'seleccion',
            'class' => 'CCheckBoxColumn',
        ],
        [
            'header' => 'Categoría',
            'name' => 'id_tipo_credito',
            'value' => '( $data->tipoCredito)?$data->tipoCredito->idTituloTipoCredito->nombre_titulo:""',
        ],
        [
            'name' => 'id_tipo_credito',
            'value' => '( $data->tipoCredito)?$data->tipoCredito->descripcion:""',
        ],
        [
            'header' => 'Monto solicitado',
            'value' => 'number_format($data->prestamo,2,",", ".")',
            'htmlOptions' => ['style' => 'text-align: right'],
        ],
        [
            'header' => 'Monto aprobado',
            'value' => '( $data->id_estatus_credito == 2 || $data->id_estatus_credito == 4)?number_format($data->prestamo,2,",", "."):""',
            'htmlOptions' => ['style' => 'text-align: right'],
        ],
        [
            'header' => 'Fecha del préstamo',
            'value' => 'date("d-m-Y",strtotime($data->fecha_registro))',
            'footer' => '',
        ],
        [
            'name' => 'cuotas_pagadas',
            'value' => '( $data->id_estatus_credito != 1 || $data->id_estatus_credito !=3)?$data->cuotas_pagadas:""',
        ],
        [
            'header' => 'Saldo deudor',
            'type' => 'number',
            'htmlOptions' => ['style' => 'text-align: right'],
            'value' => function ($model) {
                return in_array($model->id_estatus_credito, [2, 4])
                    ? $model->saldo_deudor
                    : 0;
            }
        ],
        [
            'header' => 'Saldo para abono',
            'value' => '( $data->id_estatus_credito == 2 || $data->id_estatus_credito == 4)?number_format($data->getMontoDeudaActualConfigurado($data->idcredito),2,",", "."):""',
            'htmlOptions' => ['style' => 'text-align: right', 'class' => 'td_saldo_abono_p'],
            'footerHtmlOptions' => ['style' => 'text-align: right', 'class' => 'footer_saldo_abono_p'],
        ],
        [
            'header' => 'Estaus del préstamo', 'value' => ' $data->nombre_estatus_credito',
        ],
    ],
]); ?>

<h4>Información del abono</h4>
<br>
<div class="row-fluid">
    <?php echo $form->dropDownListRow($model,'idbanco',  CHtml::listData(ParamBancos::model()->findAll(['condition' => 'estatus=true and blnborrado=false']), 'id', 'descripcion'),
                                                    ['prompt' => '-- Seleccione--', 'style' => 'width:50%']); ?>
</div>
<div class="row-fluid">
    <?php echo $form->dropDownListRow($model,'idforma_pago',  CHtml::listData(FormaPago::model()->findAll('id in (1,2)'), 'id', 'descripcion'),
                                                    ['prompt' => '-- Seleccione--']); ?>
</div>
<div class="row-fluid">
    <?php echo $form->textFieldRow($model, 'numero_referencia'); ?>
</div>
<div class="row-fluid">
    <?php echo $form->textFieldRow($model, 'monto_abonar', ['class' => 'campo_numerico', 'style' => 'text-align:right']); ?>
</div>
<div class="row-fluid">
    <?php echo $form->labelEx($model, 'fecha_referencia'); ?>
    <?php if ($model->fecha_referencia != '') {
                                                        $model->fecha_referencia = date('d-m-Y', strtotime($model->fecha_referencia));
                                                    }
                    $this->widget('zii.widgets.jui.CJuiDatePicker', [
                        'model' => $model,
                        'attribute' => 'fecha_referencia',
                        'value' => $model->fecha_referencia,
                        'language' => 'es',
                        'htmlOptions' => ['readonly' => 'readonly', 'style' => 'width:140px'],
                        //additional javascript options for the date picker plugin
                        'options' => [
                            'autoSize' => true,
                            'defaultDate' => $model->fecha_referencia,
                            //'dateFormat'=>'yy-m-d',
                            'dateFormat' => 'dd-mm-yy',
                            'buttonImage' => Yii::app()->baseUrl.'/images/calendar.png',
                            'buttonImageOnly' => true,
                            'buttonText' => 'Fecha de la referencia',
                            'selectOtherMonths' => true,
                            'showAnim' => 'slide',
                            'showButtonPanel' => true,
                            'showOn' => 'button',
                            'maxDate' => '+0D',
                            'showOtherMonths' => true,
                            'changeMonth' => 'true',
                            'changeYear' => 'true',
                        ],
                    ]); ?>
    <?php echo $form->error($model, 'fecha_referencia'); ?>
</div>
<div class="row-fluid">
    <b>¿Desea mantener el monto de la cuota?</b> <br>
    <?php echo $form->checkBox($model, 'mantener_cuota', ['data-toggle' => 'toggle', 'data-on' => 'Sí', 'data-off' => 'No']); ?>
</div>
<hr class="soften">

<div style="text-align: center">
    <?php $this->widget('bootstrap.widgets.TbButton', [
        'buttonType' => 'submit',
        'type' => 'primary',
        'label' => 'Registrar pago',
    ]); ?>
</div>

<?php $this->endWidget(); ?>
<?php
    Yii::app()->clientScript->registerScript('tablaAmortizacion1', '

	var datosPostDatos = '.(($postDatos) ? 1 : 0).';
        var idCreditoSeleccionado = "'.(($model->idcredito != '') ? $model->idcredito : 0).'";
        function datosPersonales(){
            var cedula = $("#'.CHtml::activeId($model, 'cedula').'").val();
            if(!datosPostDatos){
            
                $("#'.CHtml::activeId($model, 'id_titulo_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model, 'id_titulo_tipo_credito').'").append(\'<option value="">...Seleccione...</option>\');
                $("#'.CHtml::activeId($model, 'id_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model, 'id_tipo_credito').'").append(\'<option value="">...Seleccione...</option>\');
            }
            $("#'.CHtml::activeId($model, 'cuenta').'").val("");
            if($.isNumeric(cedula)&& cedula>6){
                var ruta ="'.Yii::app()->createAbsoluteUrl('prestamo/creditoAbono/CreateAdministrador').'";
                $.ajax({
                        url:"'.CController::createUrl('/Comun/DatosPersonalesAbonoPrestamos').'",
                        cache: false,
                        type: "POST",
                        dataType: "json",
                        data: ({cedula:cedula}),
                        beforeSend: function(xkr){
                            $(".datosPersonales").html("");
                            $("#mensajesSistema").html("");
                            if(!datosPostDatos){
                                idCreditoSeleccionado = 0;
                                var cedula= 0;
                                $.fn.yiiGridView.update(\'prestamos-grid\',{type:\'GET\', url:ruta}); 
                            }
                            
                            $("#btn_buscar_datos_personales").prop("disabled", true);
                            $(".datosPersonales").html(`<div style="text-align: center;"><i class="fa fa-spinner fa-spin" style="font-size:29px;"></i></div>`);
                            
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            $(".datosPersonales").html("");
                            $("#btn_buscar_datos_personales").prop("disabled", false);
                        },
                        success: function(data){

                            $("#btn_buscar_datos_personales").prop("disabled", false);
                            $(".datosPersonales").html("");
                                if(data.error==0) {
                                    $("#nombres_apellidos").html(data.nombres_apellidos);
                                    $("#empresa").html(data.empresa);
                                    $("#unidad").html(data.unidad);
                                    $("#sueldo").html("Bs. "+data.sueldo);
                                    $("#porcentaje").html(data.porcentaje);
                                    $("#fecha_inscripcion").html(data.fecha_inscripcion);
                                    $("#estatus").html(data.estatus);  
                                    if(!datosPostDatos){
                                        var cedula= $("#'.Chtml::activeId($model, 'cedula').'").val();
                                        $.fn.yiiGridView.update(\'prestamos-grid\',{type:\'GET\', url:ruta,data:\'cedula=\'+cedula,
                                             async:true,    
                                             complete: function(jqXHR, status) {

                                                if (status==\'success\'){
                                                    totalesTabla();
                                                }
                                            }
                                            }); 
                                        $(\'#prestamos-grid\').selGridView(\'addSelection\', [idCreditoSeleccionado]);

                                     }
                                }
                                else{
                                    $("#mensajesSistema").html(data.mensajeError);
                                    
                                }
                        }
                });
                 datosPostDatos= 0;
        }
        else{
            $(".datosPersonales").html("");
            $("#mensajesSistema").html("");                        
        }

    };

    function totalesTabla(){
        let total =0;
        $(".td_saldo_abono_p").each(
            function(index, value) {     
                var numero = $(this).html();
                numero = numero.replace(/\./g,"").replace(/,/g,".");
                if($.isNumeric(numero)){                        
                    total = total +  eval(numero);
                }   
                else
                    $(this).val(0);
        });
        $(".footer_saldo_abono_p").html("Bs.  "+convertNumberFloatZero(total)) ;
    }

    function convertNumberFloatZero(number){
            if(!$.isNumeric(number)){
                return \'NaN\';
            }
            var numberFloat = number.toFixed(3);
            var splitNumber = numberFloat.split(".");
            var cNumberFloat = number.toFixed(2);
            var cNsplitNumber = cNumberFloat.split(".");
            var lastChar = splitNumber[1].substr(splitNumber[1].length - 1);
            if(lastChar > 0 && lastChar < 5){
                cNsplitNumber[1]--;
            }
            return Number(splitNumber[0]).toLocaleString(\'es\').concat(\',\').concat(cNsplitNumber[1]);
          }

    ', CClientScript::POS_HEAD);
