<link rel="stylesheet" href="css/jquery.dataTables.min.css" >
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js',CClientScript::POS_HEAD); ?>
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/fileinput.js',CClientScript::POS_END);
        Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/fileinput.css');
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl.'/js/bootstrap2-toggle.js');
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/bootstrap2-toggle.css'); 
        Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.dataTables.min.js', CClientScript::POS_HEAD); ?>
<?php
$this->breadcrumbs=array(
	'Creditos'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List Credito','url'=>array('index')),
	array('label'=>'Manage Credito','url'=>array('admin')),
);
?>
<h2 style="text-align: center">Refinanciamiento de pr&eacute;stamo</h2>
<?php 

$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id'=>'credito-form',
	'type' => 'horizontal',
        'enableAjaxValidation' => false,
        'enableClientValidation' => true,
        'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => true,
        'validateOnType' => true,
        ),
        'htmlOptions'=>array('enctype'=>'multipart/form-data', 'onsubmit'=>'return comparaMontos()'),
)); 
$this->widget('bootstrap.widgets.TbAlert', array(
    'block' => true, // display a larger alert block?
    'fade' => true, // use transitions?
    'closeText' => '×', // close link text - if set to false, no close link is displayed
    'alerts' => array(// configurations per alert type
        'error' => array('block' => true, 'fade' => true, 'closeText' => '×'), // success, info, warning, error or danger
        'info' => array('block' => true, 'fade' => true, 'closeText' => '×'), // success, info, warning, error or danger
    ),
));

?>
<br>
<fieldset><legend style=" font-size: 17px;"><b>Datos del solicitante</b></legend>            
<table class="table table-bordered">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'cedula'); ?></b></td>
            <td style="width: 25%"> <?php echo $modelAsociado->cedula; ?><br>
                                    <div id="mensajesSistema"  class="datosPersonales"></div>
                                    <?php echo $form->error($model, "cedula"); ?></td>
            <td style="width: 20%"><b>Nombres y apellidos</b></td>
            <td style="width: 30%"><?php echo  $modelAsociado->nombre.' '.$modelAsociado->apellidos ?></td>
        </tr>
        <tr>
            <td><b>Empresa</b></td>
            <td><?php echo  ($modelAsociado->lugartrabajo0)?$modelAsociado->lugartrabajo0->descripcion:"";?> </td>
            <td><b>Unidad</b></td>
            <td><?php echo ($modelAsociado->unidad)?$modelAsociado->unidad->descripcion:"";?></td>
        </tr>
        <tr>
            <td><b>&Uacute;ltimo sueldo</b></td>
            <td>Bs. <?php echo  number_format($sueldo,2,',','.');?></td>
            <td><b>Porcentaje de aporte</b></td>
            <td><?php echo $porcentaje?>%</td>
        </tr>
        <tr>
            <td><b>Fecha de inscripci&oacute;n</b></td>
            <td><?php echo date('d-m-Y',  strtotime($modelAsociado->fechaingreso ))?></td>
            <td><b>Estatus</b></td>
            <td><?php echo ($model->blnborrado=="1")?"Inacivo":"Activo" ?></div></td>
        </tr>
        <tr>
            <td colspan="4" id="calculadoraHaberesSocio" class="datosCredito" style="display: none"></td>
        </tr>
        
    </table>
</fieldset>
<fieldset>
    <legend style=" font-size: 17px;"><b>Seleccionar pr&eacute;stamo</b></legend> 
    <table class="table table-bordered" >
        <tr>
            <td style="width: 25%"><b>Tipo de operaci&oacute;n</b></td>
            <td style="width: 25%"><b><?php echo $form->dropDownList($model,'refinanciado', array(1=>'REFINANCIAMIENTO',2=>'REESTRUCTURACIÓN DE DEUDA'),
                                                                    array('prompt' => '...SELECCIONE... ',
                                                                        'onChange' => 'busquedaTiposCreditosRefinanciamiento();'
                                                                            )); ?></b></td>
            <td style="width: 20%"><b><?php echo $form->labelEx($model,'id_tipo_credito');?></b></td>
            <td style="width: 30%"><?php echo $form->dropDownList($model,'id_tipo_credito',  CHtml::listData(TipoCredito::model()->findAll(array('condition'=>'id =:id','order'=>'descripcion asc',
                                                                                                                                                'params'=>array(':id'=>(int)$model->id_tipo_credito))), 'id', 'descripcion'),
                                                                    array('onchange'=>'tipoCreditoCaracteristica()','prompt' => 'SELECCIONE ')); ?><br>
                                        <?php echo $form->error($model,'id_tipo_credito'); ?></td>
        </tr>
    </table>

    <table id="tabla" class="table display items table table-bordered">
            <thead>
                <tr>
                  <th style="width: 2%" id="campo-seleccionar-todo">
                    <?php if(($modelConfiguracionPrestamos->refinanciamiento_multiple_asc ==1 && $model->refinanciado ==1) ||
                                ($modelConfiguracionPrestamos->reestructuracion_multiple_asc ==1 && $model->refinanciado ==2)
                            ){ ?>
                        <input type="checkbox" id="selecionar_todo" data-to-table="tasks">
                    <?php } ?>

                </th>
                    <th style="width: 18%">Categor&iacute;a</th>
                    <th style="width: 18%">Plazo del pr&eacute;stamo</th>
                    <th style="width: 12%">Monto solicitado</th>
                    <th style="width: 12%">Monto aprobado</th>
                    <th style="width: 10%">Fecha del pr&eacute;stamo</th>
                    <th style="width: 8%">Cuotas pagadas</th>
                    <th style="width: 14%">Saldo deudor</th>
                    <th style="width: 8%">Estaus</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    <div id="prestamos-seleccionados"></div>   
    <table class="table table-bordered" id="datos_prestamos_calculadora"></table>
</fieldset>  
<fieldset><legend style=" font-size: 17px;"><b>Informaci&oacute;n de su &uacute;ltimo recibo de pago</b></legend>            
    <table class="table table-bordered" id="datos_prestamos_calculadora">
        <tr>
            <td colspan="4" id="calculadoraHaberes" class="datosCredito" style="display: none"></td>
        </tr>
        <tr>
            <td><b>Monto m&aacute;ximo permitido</b></td>
            <td><div id="monto_sugerido" class="datosPersonales datosCredito"></div></td>
            <td></td>
            <td></td>
        </tr>
        <?php if($post ==  true && count($modelCapacidadPago)>0){ ?>
                <tr class="detalle_capacidad_pago">
                    <td colspan="2"><b>Descripci&oacute;n</b></td>
                    <td><b>Asignaci&oacute;n</b></td>
                    <td><b>Deducciones</b></td>
                </tr>
                <?php   foreach ($modelCapacidadPago as $key => $value) {?>
                            <tr class="detalle_capacidad_pago">
                                <td colspan="2"><b><?php echo $value->nombre_concepto; ?></b></td>
                                <td><?php echo ($value->asignacion)?' Bs.' .$form->textField($value,"[$key]monto",array('maxlength'=>'10','style'=>'text-align:right','onChange'=>'calcularCapacidadPago();' ,'class'=>'span2 campo_asignacion')):""; ?><br>
                                     <?php echo ($value->asignacion)?$form->error($value,"[$key]monto"):""; ?></td>
                                <td><?php echo (!$value->asignacion)?' Bs.' .$form->textField($value,"[$key]monto",array('maxlength'=>'10','style'=>'text-align:right','onChange'=>'calcularCapacidadPago();','class'=>'span2 campo_deduccion')):""; ?><br>
                                     <?php echo (!$value->asignacion)?$form->error($value,"[$key]monto"):""; ?></td>
                            </tr>
                <?php }
           
                if(count($modelCapacidadPago)>0){?>
                    <tr class="detalle_capacidad_pago">
                        <td colspan="2"><b>Totales</b></td>
                        <td style="text-align: left"><div id="total_asignacion" class="campo_asignacion"></div></td>
                        <td style="text-align: left"><div id="total_deducciones" class="campo_deduccion"></div></td>
                    </tr>
                   <?php }?>

                   <?php  foreach (Credito::model()->findAll('idasociado=:idasociado',array(':idasociado'=>$model->idasociado)) as $key => $value) {?>            
                        <tr class="detalle_capacidad_pago">
                            <td colspan="2">Cuota mensual del prestamos "<b><?php echo $value->idTipoCredito->descripcion; ?></b>"</td>
                            <td></td>
                            <td style="text-align: left" class="monto_haberes_comprometido">Bs. <?php echo trim(Yii::app()->numberFormatter->formatCurrency($value->cuota_pagar,'')) ; ?></td>

                        </tr>
                    <?php } ?>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Sueldo integral</b></td>
                        <td><div id="sueldo_integral"></div></td>
                        <td><b>33% del descunto integral</b></td>
                        <td><div id="porcentaje_sueldo"></div></td>
                    </tr>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Monto total comprometido mensual</b></td>
                        <td><div id="total_prestamos"></div></td>
                        <td><b>% en pr&eacute;stamos mensual</b></td>
                        <td><div id="porcentaje_total_prestamos"></div></td>
                    </tr>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Monto disponible para comprometer hasta el 33%</b></td>
                        <td><div id="total_disponible"></div></td>
                        <td><b>% del monto disponible</b></td>
                        <td><div id="porcentaje_total_disponible"></div></td>
                    </tr>
                <?php }?>
        
    </table>
</fieldset>
<fieldset><legend style=" font-size: 17px;"><b>Datos del prestamos</b></legend>            
<table class="table table-bordered" id="datos_prestamos">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'cuenta'); ?> </b></td>
            <td style="width: 25%"> 
                <?= $form->dropDownList($model,'cuenta',
                        CHtml::listData(AsociadoCuentaBanco::model()->with('idBanco')->together(true)->findAll([
                                    'select'=>"cuenta_bancaria AS id, \"idBanco\".descripcion ||''|| (CASE WHEN cuenta_corriente = true THEN 'Cuenta Corriente' ELSE 'Cuenta de Ahorro' END)||' '|| cuenta_bancaria as cuenta_bancaria",
                                    'condition'=>'idasociado=:idasociado AND t.blnborrado = false',
                                    'params'=>[':idasociado'=>$modelAsociado->idasociado]]),'id','cuenta_bancaria'),['style'=>"width:100%",'prompt'=>'-- SELECCIONE EL BANCO--']);
                    ?><br>
                <?php /*echo CHtml::label($model->cuenta,'');*/ ?>                 
                <?php echo $form->error($model,'cuenta');?>
            </td>
            <td style="width: 30%"><b></b></td>
            <td style="width: 20%"> </td>
        </tr>
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'monto_credito'); ?></b></td>
            <td style="width: 25%"> 
                <div style="display:table">
                    <div style="float:left; width: 85%;" class="input-append">
                        <?php echo  $form->textfield($model,'monto_credito',array('style'=>'text-align:right','readOnly'=>((!$model->isNewRecord)?'readOnly':NULL))) ;?>

                        <?php echo CHtml::htmlButton('<i class="icon-search"></i>', array('type'=>"button",'id'=>'btn_tabla_amortizacion','class' => 'btn btn-success icon button','onClick'=>"buscarTablaAmortizacion();"));   ?>
                        
                    </div>
                    <div style="width: 100%;" >
                        <?php echo  $form->error($model,'monto_credito') ;?>
                        
                    </div>
                </div>


            </td>
            <td style="width: 30%"><div class="desicionCuotasEspeciales" style="display:<?php echo ($modelPermitirCuotasEspeciales!=0)?"block":"none"?>">Calcular con cuotas especiales</div></td>
            <td style="width: 20%"><div class="desicionCuotasEspeciales" style="display:<?php echo ($modelPermitirCuotasEspeciales!=0)?"block":"none"?>"> <?php echo $form->radioButtonList($model, 'generar_tabla_cuotas_especiales', array(
                                                        '1'=>'SI',
                                                        '0'=>'NO', 
                                                       )); ?></div></td>
        </tr>
        
        
    </table>
</fieldset>
<div id="error_submit"></div>


    <div id='detalle_tsabla_amortizacion'></div>
     <div class="form-actions"  style="text-align: center">
        <?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType' => 'submit',
			'type' => 'success',
			'id' => 'btn_registrar',
                        'icon'=>'icon-ok',
                        'htmlOptions'=>array(/*'class'=>'disabled'*/'id'=>'btn_registrar'),
			'label' => 'Solicitar préstamo',

    ));?>
</div>

<?php $this->endWidget(); ?>
   
<?php 
    Yii::app()->clientScript->registerScript('tablaAmortizacion1', '
        var monto_haberes_socio = 0;
        var datosPost = '.(($post)?1:0).';
        var idcreditoSeleccionado=0;
        var total_monto_deuda=0;
        var datosPostDatos = '.(($postDatos)?1:0).';
        var idasociado = '.$model->idasociado.';
        
        var refinanciamiento_multiple = '.(($modelConfiguracionPrestamos->refinanciamiento_multiple_asc)?1:0).';
        var reestructuracion_multiple = '.(($modelConfiguracionPrestamos->reestructuracion_multiple_asc)?1:0).';
        let prestamos_seleccionado ='.json_encode($prestamos_seleccionado).';

        let datosPostRegistrado = '.(($model->id_tipo_credito!='')?1:0).';


        function consultarTablaAmortizacionPost(){
            calcularCapacidadPago();
            setTimeout(function(){$("#btn_tabla_amortizacion").click() },250);
        }
       

        function busquedaTiposPrestamos(id){
            n = $.fn.yiiGridView.getSelection(id);
            $("#calculadoraHaberes").hide();
            if(!datosPostDatos){
                $("#'.CHtml::activeId($model,'refinanciado').'").empty();
                $("#'.CHtml::activeId($model,'refinanciado').'").append(\'<option value="">...SELECCIONE...</option>\');
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...SELECCIONE...</option>\');
            }
            if (n>0){
                idcreditoSeleccionado = n;
               $.ajax({
                        url: "'.Yii::app()->urlManager->createUrl('/Comun/ListarOpcionesRoR').'",
                        cache:false,
                        type: "POST",
                        dataType: "json",
                        data: ({"id_credito": parseInt(n)}),
                        beforeSend: function(xkr){
                            $("#'.CHtml::activeId($model,'refinanciado').'").empty();
                            $("#'.CHtml::activeId($model,'refinanciado').'").append(\'<option value="">...SELECCIONE...</option>\');        
                            $("#calculadoraHaberes").html("");
                            $("#error_submit").html("");

                        },
                        success:function(data){
                            if(data.error==0){
                                $("#'.CHtml::activeId($model, 'refinanciado').'").html(data.tipo_credito);
                            }
                            else{
                                $("#calculadoraHaberes").show();
                                $("#calculadoraHaberes").html(data.mensaje);
                            }
                        }
                    });
            }
            else{
                $(".datosCredito").html("");
                $(".detalle_capacidad_pago").remove();
                $(".detalle_tabla_amortizacion").remove();
                $(".desicionCuotasEspeciales").hide();
            }
              
        };
        
    function busquedaTiposCreditosRefinanciamiento2(){
            var tipoOpcion = $("#'.CHtml::activeId($model,"refinanciado").'").val();
            // var idcredito = $("#prestamos-grid").selGridView("getAllSelection");
            $("#calculadoraHaberes").hide();
            if(!datosPostRegistrado){
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...SELECCIONE...</option>\');
            }
            if (tipoOpcion>0){
               $.ajax({
                        url: "'.Yii::app()->urlManager->createUrl('/Comun/ListarTipoCreditosRefinanciamiento').'",
                        cache:false,
                        type: "POST",
                        dataType: "json",
                        data: ({"tipoOpcion": tipoOpcion, idcredito:idcredito}),
                        beforeSend: function(xkr){
                            if(!datosPostRegistrado){
                                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...SELECCIONE...</option>\');
                            }  
                            $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true);
                            $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", true);

                            $("#calculadoraHaberes").hide(); $("#calculadoraHaberes").html("");
                            $(".datosCredito").html("");
                            $(".detalle_capacidad_pago").remove();
                            $(".detalle_tabla_amortizacion").remove();
                            $(".desicionCuotasEspeciales").hide();
                            $("#error_submit").html("");

                            $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true); 
                        },
                        success:function(data){

                            $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false); 
                            if(data.error==0){
                                 if(!datosPostRegistrado){
                                    $("#'.CHtml::activeId($model, 'id_tipo_credito').'").html(data.tipo_credito);
                                    total_monto_deuda = data.monto_deuda;
                                } 
                            }
                            else{
                                if(data.mensaje!=""){
                                    $("#calculadoraHaberes").show();
                                    $("#calculadoraHaberes").html(data.mensaje);  
                                 }
                            }
                             datosPostRegistrado = 0;
                        }
                    });
                   
            }
            else{
                $(".datosCredito").html("");
                $(".detalle_capacidad_pago").remove();
                $(".detalle_tabla_amortizacion").remove();
                $(".desicionCuotasEspeciales").hide();
            }
              
    };
    function busquedaTiposCreditosRefinanciamiento(){
            var tipoOpcion = $("#'.CHtml::activeId($model,"refinanciado").'").val();
            // var idcredito = $("#prestamos-grid").selGridView("getAllSelection");
            $("#calculadoraHaberes").hide();
            if(!datosPostRegistrado){
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...SELECCIONE...</option>\');
            }
            
            ListadoPrestamosRoR(idasociado);

            if (tipoOpcion>0){

               $.ajax({
                        url: "'.Yii::app()->urlManager->createUrl('/Comun/ListarTipoCreditosRefinanciamiento').'",
                        cache:false,
                        type: "POST",
                        dataType: "json",
                        data: ({"tipoOpcion": tipoOpcion, idasociado:idasociado}),
                        beforeSend: function(xkr){
                            if(!datosPostRegistrado){
                                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...SELECCIONE...</option>\');
                            }  

                            

                            $("#calculadoraHaberes").hide(); $("#calculadoraHaberes").html("");
                            $(".datosCredito").html("");
                            $(".detalle_capacidad_pago").remove();
                            $(".detalle_tabla_amortizacion").remove();
                            $(".desicionCuotasEspeciales").hide();
                            $("#error_submit").html("");

                            $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true); 
                            $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", true);

                        },
                        success:function(data){
                            $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false); 
                            $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", false); 
                            if(data.error==0){

                                 if(!datosPostRegistrado){

                                    $("#'.CHtml::activeId($model, 'id_tipo_credito').'").html(data.tipo_credito);

                                    // total_monto_deuda = data.monto_deuda;

                                    
                                }
                                
                            }
                            else{
                                if(data.mensaje!=""){
                                    $("#calculadoraHaberes").show();
                                    $("#calculadoraHaberes").html(data.mensaje);  
                                 }
                            }
                             datosPostRegistrado = 0;
                        }
                    });
                   
            }
            else{
                $(".datosCredito").html("");
                $(".detalle_capacidad_pago").remove();
                $(".detalle_tabla_amortizacion").remove();
                $(".desicionCuotasEspeciales").hide();
            }
              
    };
    function ListadoPrestamosRoR(){

            let idTipoCredito  = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();
            let refinanciamiento  = $("#'.CHtml::activeId($model,'refinanciado').'").val();
            $("#prestamos-seleccionados").html("");
            
            $.ajax({
                url: "'.Yii::app()->urlManager->createUrl('/Comun/ListadoPrestamosRoR').'",
                cache:false,
                type: "POST",
                dataType: "json",
                data: ({"idasociado": parseInt(idasociado),"refinanciamiento": parseInt(refinanciamiento),"idtipocredito": parseInt(idTipoCredito), }),
                beforeSend: function(xkr){
                    
                    $("#tabla").DataTable().clear().draw(); 

                    $("#campo-seleccionar-todo").html("");

                },
                success:function(data){

                    $("#tabla").DataTable().rows.add(data.creditos).draw(false);

                    if((refinanciamiento_multiple == 1 || reestructuracion_multiple == 1) && idTipoCredito > 0)

                        $("#campo-seleccionar-todo").append("<input type=\"checkbox\" id=\"selecionar_todo\" data-to-table=\"tasks\">");
                        
                }
            });
              
    };

        function tipoCreditoCaracteristica(){
               var idTipoCredito  = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();
               var refinanciamiento  = $("#'.CHtml::activeId($model,'refinanciado').'").val();
               $("#calculadoraHaberes").hide();
               if(refinanciamiento !="") { 
				if(idTipoCredito!=""){
					$.ajax({
                                                url:"'.CController::createUrl('TipoCreditoCaracteristica').'",
                                                cache: false,
                                                type: "POST",
                                                dataType: "json",
                                                data: ({idTipoCredito:idTipoCredito,refinanciamiento:refinanciamiento}),
                                                beforeSend: function(xkr){
                                                        $(".datosCredito").html("");
                                                        if(!datosPost){
                                                            $(".detalle_capacidad_pago").remove();
                                                        }
                                                        monto_haberes_socio = 0;

                                                        $(".detalle_tabla_amortizacion").remove();
                                                        $("#mensajesSistema").html("");
                                                        $("#recibo_pago").hide(); 
                                                        $(".desicionCuotasEspeciales").hide();
                                                        $("#error_submit").html("");

                                                        $("#calculadoraHaberes").show();
                                                        $("#calculadoraHaberes").html(`<div style="text-align: center;"><i class="fa fa-spinner fa-spin" style="font-size:29px;"></i></div>`);
                                                        $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true); 
                                                        $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", true); 
                                                        $("#tabla").DataTable().clear().draw(); 

                                                        $("#campo-seleccionar-todo").html("");

                                                },
                                                error: function (xhr, ajaxOptions, thrownError) {
                                                    
                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false);
                                                    $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", false);
                                                    $("#calculadoraHaberes").hide();
                                                    $("#calculadoraHaberes").html("");

                                                },
                                                success: function(data){
                                                    $("#calculadoraHaberes").hide();
                                                    $("#calculadoraHaberes").html("");
                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false);
                                                    $("#'.CHtml::activeId($model,'refinanciado').'").prop("disabled", false);
                                                    ListadoPrestamosRoR(idasociado);


                                                            if(data.error==0) {
                                                                $("#monto_sugerido").html(data.monto_sugerido);
                                                                $("#datos_prestamos_calculadora").append(data.detalle_capacidad_pago); 
                                                                if(data.mostrar_recibo_pago==1){
                                                                    $("#recibo_pago").show();                                                                 
                                                                }
                                                                $("#calculadoraHaberes").show();
                                                                $("#calculadoraHaberes").html(data.calculadoraHaberes);   
                                                                
                                                                datosPost=0;
                                                                porcentaje_capacidad_pago = data.porcentajeCapacidadPago;
                                                                
                                                               
                                                                    var montoDisponible =  data.monto_sugerido;
                                                                    montoDisponible = montoDisponible.trim();
                                                                    montoDisponible = montoDisponible.replace("Bs. ", "");
                                                                    montoDisponible = montoDisponible.replace("</b>", "");
                                                                    montoDisponible = montoDisponible.replace("&nbsp;", "");
                                                                    montoDisponible = montoDisponible.replace(".", "");
                                                                    montoDisponible = montoDisponible.replace(",", ".");
                                                                    monto_haberes_socio = montoDisponible;

                                                                if(data.permitirDesicionCuotasEspeciales == 1)
                                                                    $(".desicionCuotasEspeciales").show();
                                                            }
                                                            else{
                                                                $("#calculadoraHaberes").show();
                                                                $("#calculadoraHaberes").html(data.mensajeError);  
                                                            }
                                                }
					});
				}
				else{
                                    $(".datosCredito").html("");
                                    $(".detalle_capacidad_pago").remove();
                                    $(".detalle_tabla_amortizacion").remove();
                                    $(".desicionCuotasEspeciales").hide();
				}

        }
        else{
                $(".datosCredito").html("");
                $(".detalle_capacidad_pago").remove();
                $(".detalle_tabla_amortizacion").remove();
                $("#mensajesSistema").html("");
        }

    };

function verificarSeleccion(id) {
        let monto = 0;

        let idTipoCredito = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();

        let tipoOpcion = $("#'.CHtml::activeId($model,'refinanciado').'").val();

        input_check = $(`#checkbox-${id}`);

        if(input_check.is(":checked") ){

            $.ajax({
                url: "'.Yii::app()->urlManager->createUrl('/Comun/ValidarCreditoRefinanciamiento').'",
                cache:false,
                type: "POST",
                dataType: "json",
                data: ({"idcredito": parseInt(id),"tipoOpcion": parseInt(tipoOpcion),"idtipocredito": parseInt(idTipoCredito)}),
                beforeSend: function(xkr){

                    $("#prestamos-seleccionados").html("");

                },
                success:function(data){
                    if(data.error==1){
                           $("#prestamos-seleccionados").html(data.mensajeError);  
                           input_check.remove();
                    }
                }
            });

        }


        idcreditoSeleccionado = "";

        $(`#tabla input[type=checkbox]:not("#selecionar_todo")`).each(function() {

          
            if($(this).is(":checked")){

                idcreditoSeleccionado = idcreditoSeleccionado +$(this).val() + ",";
                var monto_prestamos = $(`#${$(this).val()}`).html();
                monto_prestamos = monto_prestamos.trim();
                monto_prestamos = monto_prestamos.replace("Bs", "");
                monto_prestamos = monto_prestamos.trim();
                monto_prestamos = monto_prestamos.replace("&nbsp;", "");
                monto_prestamos = monto_prestamos.replace(/\./g,"").replace(/,/g,".");

                monto +=eval(monto_prestamos);
            }

        });

        $(`#tabla input[type=radio]`).each(function() {

          
            if($(this).is(":checked")){

                idcreditoSeleccionado = idcreditoSeleccionado +$(this).val() + ",";
                var monto_prestamos = $(`#${$(this).val()}`).html();
                monto_prestamos = monto_prestamos.trim();
                monto_prestamos = monto_prestamos.replace("Bs", "");
                monto_prestamos = monto_prestamos.trim();
                monto_prestamos = monto_prestamos.replace("&nbsp;", "");
                monto_prestamos = monto_prestamos.replace(/\./g,"").replace(/,/g,".");

                monto +=eval(monto_prestamos);
            }

        });
        
        total_monto_deuda = monto;

        // $("#prestamos-seleccionados").html("a");
        // $("#prestamos-seleccionados").html(`a`);

    }

 function buscarTablaAmortizacion(){
        var idTipoCredito  = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();
        var montoCredito  = $("#'.CHtml::activeId($model,'monto_credito').'").val();
        var opcionRefinanciamiento  = $("#'.CHtml::activeId($model,'refinanciado').'").val();
        var generar_cuotas_especiales  = $(\'input:radio[name="Credito[generar_tabla_cuotas_especiales]"]:checked\').val();
        var capacidad_pago = 0;
        if ( $("#total_disponible").length ) {
            var capacidad_pago = $("#total_disponible").html()
                                    .trim()
                                    .replace("Bs. ", "")
                                    .replace("&nbsp;", "")
                                    .replace(/\./g,"")
                                    .replace(/,/g,".");
        }
        
        
        $(".detalle_tabla_amortizacion").remove();   
         //$("#btn_registrar").prop("disabled", true);

        if (capacidad_pago != "") {

            if(idcreditoSeleccionado == ""){

                alert("Debe de seleecionar el o los créditos a refinanaciar o a reestructurar");

                return false;

            }
            if($.isNumeric(capacidad_pago) && capacidad_pago>0){
                    if(idTipoCredito!=""){
                        $.ajax({
                                url:"'.CController::createUrl('tablaAmoritzacionAdministrador').'",
                                cache: false,
                                type: "POST",
                                dataType: "json",
                                data: ({idTipoCredito:idTipoCredito,montoCredito:montoCredito,capacidad_pago:capacidad_pago,generar_cuotas_especiales:generar_cuotas_especiales,monto_haberes_socio:monto_haberes_socio,opcionRefinanciamiento:opcionRefinanciamiento,idcredito:idcreditoSeleccionado}),

                                beforeSend: function(xkr){
                                    $(".detalle_tabla_amortizacion").remove();
                                    $("#error_submit").html("");

                                    $("#datos_prestamos").append(
                                            `<tr id = "cargando-tabla-amortizacion">
                                                <td colspan="4">
                                                    <div style="text-align: center;">
                                                        <i class="fa fa-spinner fa-spin" style="font-size:29px;"></i>
                                                    </div>
                                                </td>
                                            </tr>`
                                     ); 
                                    $("#btn_tabla_amortizacion").prop("disabled", true);

                                },

                                error: function (xhr, ajaxOptions, thrownError) {
                                    $("#btn_tabla_amortizacion").prop("disabled", false);
                                     $("#cargando-tabla-amortizacion").remove();
                                },
                                success: function(data){
                                    $("#cargando-tabla-amortizacion").remove();

                                        if(data.error==0) {                                
                                            $("#datos_prestamos").append(data.encabezado_tabla_amoritzacion);      
                                            //$("#btn_registrar").removeAttr("disabled");
                                            //$("#btn_registrar").removeClass("disabled");
                                            $("#btn_registrar").prop("disabled", false);

                                        }
                                        else{
                                            var html = "<tr class=\"detalle_tabla_amortizacion\">\
                                                            <td colspan=\"4\">"+data.mensajeError+"</td>\
                                                        </tr>";
                                            if(data.mensajeError!="")
                                                $("#datos_prestamos").append(html); 
                                        }
                                }
                        });
                    }
                    else{                                            
                        $(".datosCredito").html("");
                        $(".detalle_capacidad_pago").remove();
                        $(".detalle_tabla_amortizacion").remove();
                    }
            }
            else{
                var html = "<tr class=\"detalle_tabla_amortizacion\">\
                            <td colspan=\"4\"><div class=\"alert alert-warning\"><i class=\"icon-info-sign\"></i>El asociado no posee capacidad de pago para solictar préstamo</div></td>\
                            </tr>";
                $("#datos_prestamos").append(html); 
            }
        }
    };
	var globalDeducciones = 0;
	var globalAsignaciones = 0;
	var porcentaje_sueldo = 0;
	var porcentaje_capacidad_pago = 0.33;
    function calcularCapacidadPago(){
        globalAsignaciones =0;
        $(".campo_asignacion").each(
            function(index, value) {
                var numero = $(this).val();
                numero = numero.replace(/\./g,"").replace(/,/g,".")						
                if($.isNumeric(numero)){						
                    globalAsignaciones = globalAsignaciones +  eval(numero);
                }	
                else
                    $(this).val(0);
        });

        $("#total_asignacion").html("Bs. "+convertNumberFloatZero(globalAsignaciones)) ;
        $("#sueldo_integral").html("Bs. "+convertNumberFloatZero(globalAsignaciones)) ;
        porcentaje_sueldo = globalAsignaciones.toFixed(2)*porcentaje_capacidad_pago;
        $("#porcentaje_sueldo").html("Bs. "+convertNumberFloatZero(porcentaje_sueldo)) ;       
    
        globalDeducciones =0;
        $(".campo_deduccion").each(
            function(index, value) {
                var numero = $(this).val();
                numero = numero.replace(".", "");
                numero = numero.replace(",", ".");							
                if($.isNumeric(numero)){						
                    globalDeducciones = globalDeducciones +  eval(numero);						
                }
                else
                    $(this).val(0);
            });
        
        $("#total_deducciones").html("Bs. "+globalDeducciones.toFixed(2)) ;		
            $(".monto_haberes_comprometido").each(function(){
                var numero = $(this).html();
                numero = numero.trim();
                numero = numero.replace("Bs. ", "");
                numero = numero.replace("&nbsp;", "");
                numero = numero.replace(".", "");
                numero = numero.replace(",", ".");
                globalDeducciones = globalDeducciones +  eval(numero);	
            });
            $("#total_deducciones").html("Bs.  "+convertNumberFloatZero(globalDeducciones)) ;
            $("#total_prestamos").html("Bs.  "+convertNumberFloatZero(globalDeducciones)) ;

            calculadorHaberes();		
        }
	
	function calculadorHaberes(){
            if(globalAsignaciones>0){
                var porcentaje_total_prestamos = (globalDeducciones.toFixed(2) *100/eval(globalAsignaciones));
                $("#porcentaje_total_prestamos").html(convertNumberFloatZero(porcentaje_total_prestamos)+"%") ;

                var monto_total_disponible = eval(porcentaje_sueldo)-globalDeducciones.toFixed(2);
                $("#total_disponible").html("Bs. "+convertNumberFloatZero(monto_total_disponible)) ;

                var porcentaje_total_disponible = (porcentaje_capacidad_pago*100)-porcentaje_total_prestamos.toFixed(2);
                $("#porcentaje_total_disponible").html(convertNumberFloatZero(porcentaje_total_disponible)+"%") ;
            }
	}
        
     function comparaMontos(){
        
        var reest = $("#'.CHtml::activeId($model,'refinanciado').'").val();
        var m_credito = $("#'.CHtml::activeId($model,'monto_credito').'").val();
        m_credito = m_credito.replace(/\./g,"").replace(/,/g,".");
        m_credito = parseFloat(m_credito);

        var m_financiar = $("#monto_financiar").html()
                                .trim()
                                .replace(" Bs.", "")
                                .replace(/\./g,"")
                                .replace(/,/g,".");
        m_financiar = parseFloat(m_financiar);

        var m_reest = $("#monto_reest").html();
        m_reest = m_reest.trim();
        m_reest = m_reest.replace(" Bs.", "");
        m_reest = m_reest.replace(/\./g,"").replace(/,/g,".");
        m_reest = parseFloat(m_reest);

        var suma = m_credito + m_reest;
        suma = parseFloat(suma);
        suma = suma.toFixed(2);

        if (reest == 1) {
            if (m_credito != m_financiar) {
                //alert("error " + (m_credito + m_reest) + " " + m_financiar);
                $("#error_submit").html("<span class=\"help-inline error\">Debe dar click en el boton <b>Calcular</b>, para generar la nueva tabla!</span>");
                return false;
            }else{
                //alert("success " + (m_credito + m_reest) + " " + m_financiar);
                $("#error_submit").html("");
                return true;
            }
            
        }else if (reest == 2) {
            if (suma != m_financiar) {
                //alert("error " + suma + " " + m_financiar);
                $("#error_submit").html("<span class=\"help-inline error\">Debe dar click en el boton <b>Calcular</b>, para generar la nueva tabla!</span>");
                return false;

            }else{
                //alert("success " + suma + " " + m_financiar);
                $("#error_submit").html("");
                return true;
            }
        }
        //return false;
    }



  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]);
  }
        
        $(\'.campo_asignacion\').mask(\'#.##0,00\', {reverse: true});
        $(\'.campo_deduccion\').mask(\'#.##0,00\', {reverse: true});
        $(\'#'.CHtml::activeId($model,'monto_credito').'\').mask(\'#.##0,00\', {reverse: true});

	',CClientScript::POS_HEAD);

        
	Yii::app()->clientScript->registerScript('tablaAmortizacion2','
			$(document).ready(function() {
                            $(\'.campo_asignacion\').mask(\'#.##0,00\', {reverse: true});
                            $(\'.campo_deduccion\').mask(\'#.##0,00\', {reverse: true});
                            // $(\'#prestamos-grid\').selGridView(\'addSelection\', ['.$model->id_credito_padre.']);
                            $("form").keypress(function(e) {
                                if (e.which == 13) {
                                    return false;
                                }
                            });
                            tipoCreditoCaracteristica();

                            $("#error_submit").html("");
                            $("#btn_registrar").prop("disabled", true);
			});
                        
	');

?>
<script type="text/javascript">
      $('#tabla').DataTable( {
          "language": {
              "url": "js/jquery.dataTables.Spanish.json",
          },
          "aoColumns": [
              { mData: 'idcredito' } ,
              { mData: 'categoria' },
              { mData: 'plazo_prestamo' },
              { mData: 'prestamo',
                className: 'dt-body-right'  },
              { mData: 'monto_aprobado',
                className: 'dt-body-right'  },
              { mData: 'fecha_registro',
                className: 'dt-body-center'  },
              { mData: 'cuotas_pagadas' ,
                className: 'dt-body-center' },
              { mData: 'deuda_actual' ,
                className: 'dt-body-right' },
              { mData: 'nombre_estatus_credito',
                className: 'dt-body-center' }
          ],
        'columnDefs': [
        {
           'targets': 0,
           'searchable':false,
           'orderable':false,
           'className': 'dt-body-center',
           'render': function (data, type, full, meta){

                let tipoOpcion  = $("#<?= CHtml::activeId($model,'refinanciado')?>").val();

                let idTipoCredito  = $("#<?= CHtml::activeId($model,'id_tipo_credito')?>").val();

                 let marcar_seleccionado = (prestamos_seleccionado[full.idcredito])?'checked = "checked"': "";

                if(idTipoCredito > 0){

                    if(tipoOpcion == 1){

                        if(refinanciamiento_multiple == 1)

                            return '<input type="checkbox" '+marcar_seleccionado+' id="checkbox-'+ $('<div/>').text(data).html() +'" class="checkbox_creditos" onChange = "verificarSeleccion('+ $('<div/>').text(data).html() +')" name="Credito[id_creditos][]" value="' + $('<div/>').text(data).html() + '">';
                    }
                    else{

                        if(reestructuracion_multiple == 1)

                                    return '<input type="checkbox" '+marcar_seleccionado+' id="checkbox-'+ $('<div/>').text(data).html() +'" class="checkbox_creditos" onChange = "verificarSeleccion('+ $('<div/>').text(data).html() +')" name="Credito[id_creditos][]" value="' + $('<div/>').text(data).html() + '">';
                        

                    }
                    
                    return '<input type="radio" id="checkbox-'+ $('<div/>').text(data).html() +'" onChange = "verificarSeleccion('+ $('<div/>').text(data).html() +')" name="Credito[id_creditos][]" value="' + $('<div/>').text(data).html() + '">';
                }
                
                    

                return '';
           }
        },
        {
          'targets': 7,
          'render': function (data, type, full, meta){

                return '<span id="'+full.idcredito+'">' + $('<div/>').text(data).html() + '</span>';
           }
        }],
        "searching": false,
        "bLengthChange":   false,
     

    } );
    </script>
