<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.maskMoney.js',CClientScript::POS_HEAD); ?>
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js',CClientScript::POS_HEAD); ?>
<link rel="stylesheet" href="css/jquery.dataTables.min.css" >
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.dataTables.min.js', CClientScript::POS_HEAD); ?>

<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
	'id'=>'retiro-parcial-form',
	'enableAjaxValidation'=>false,
)) ?>

	<p class="help-block">Campos con <span class="required">*</span> son requerido.</p>

	<?php echo $form->errorSummary($model); ?>
        <?php Yii::import('application.modules.prestamo.models.DeudaActual') ?>
        <?php echo $this->renderPartial('application.modules.asociado.views.asociado.haberesSocio', array(
            'modelAsociado'=>$modelAsociado,
            'haberes'=>$modelHaberesSocio,
            'porcentaje'=>$porcentaje,
            'etiquetaFecha'=>'Fecha de Inscripci&oacute;n',
            'montoTotaSolicitud'=>$model->monto_total_disponible,
            'fecha'=>$modelAsociado->fechaingreso,
            'disponible' => new Disponibilidad([
                'asociado' => $modelAsociado->idasociado,
                'proceso' => 2,
            ])
        )); ?>
        <?php echo $this->renderPartial('application.modules.asociado.views.asociado.detallesHaberesSocio', array('id'=>$modelAsociado->idasociado)); ?>
    
    <?php if($configuracion->pago_prestamo_retiro_asociado > 0){?>
        <div class="well creditos" >
            <fieldset>
                <legend>Seleccionar pr&eacute;stamo</legend>    
                    <table id="tabla" class="table display items table table-bordered">
                    <thead>
                        <tr>
                        <th style="width: 2%">
                            <?php if($configuracion->metodo_seleccion_prestamo_asociado==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>
                        <?php foreach ($creditosActivos as $key => $value) {?>
                        <tr>
                            <td><?= $value['idcredito'] ?></td>
                            <td><?= $value['categoria'] ?></td>
                            <td><?= $value['plazo_prestamo'] ?></td>
                            <td><?= $value['prestamo'] ?></td>
                            <td><?= $value['monto_aprobado'] ?></td>
                            <td><?= $value['fecha_registro'] ?></td>
                            <td><?= $value['cuotas_pagadas'] ?></td>
                            <td><?= $value['deuda_actual'] ?></td>
                            <td><?= $value['nombre_estatus_credito'] ?></td>
                        </tr>
                        <?php }?>
                    </tbody>
                    </table>
            </fieldset>  
        </div>
    <?php } ?>
    <div class="alert alert-success">
        <h3>Montos permitidos para la solicitud de retiro parcial</h3>
        <hr>
        <div class="row">
            <div class="span3"><b>Monto bloqueo de haberes</b></div>
            <div class="span2 text-right"><?= number_format($montoBloqueado,2,",",".")?> Bs </div>
        </div>
        <div class="row">
            <div class="span3"><b>Monto m&aacute;ximo a solicitar:</b></div>
            <div class="span2 text-right"><?= number_format($montoSolicitud,2,",",".")?> Bs</div>
        </div>
        <?php if($configuracion->pago_prestamo_retiro_asociado > 0){ ?>
            <div class="row">
                <div class="span3"><b><b>Monto pr&eacute;stamos seleccionados:</b></div>
                <div class="span2 text-right" id="tabla-saldo-deudor"><?= number_format($model->saldo_deudor,2,",",".")?> Bs</div>
            </div>
        <?php } ?>
    </div>
	<div class="alert alert-info">
       <div class="row">
            <div class="span6">
                <?php echo $form->labelEx($model,'monto_solicitado'); ?>
                <?php echo  ' Bs.' . $form->textfield($model,'monto_solicitado',array('dir'=>'RTL')) ;?>
                <?php echo $form->error($model,'monto_solicitado'); ?>
            </div>
       </div>
       
       <div class="row">
                <div class="span6">
                <?php echo CHtml::label('<strong>Los haberes solicitados serán abonados a la cuenta:</strong><br>',''); ?>
                <div style='color: #000;'>
                    <?= $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'=>$model->idasociado]]),'id','cuenta_bancaria'),['style'=>"width:100%",'prompt'=>'-- SELECCIONE EL BANCO--']);
                    ?>

                    <?php echo $form->error($model,'cuenta');?>
                <?php //echo $model->cuenta?></div><br />
                <?php
                    //echo $form->textfield($model,'cuenta',array('onkeypress'=>'return validar(event,7)', 'maxlength'=>'20'));
                  
                ?>
                </div>
       </div>
                
   </div>    
        

	<div class="form-actions"  style="text-align: center">
		<?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType'=>'submit',
			'type'=>'primary',
			'label'=>'Solicitar',
		)); ?>
	</div>

<?php $this->endWidget(); ?>

<script>
    let prestamos_seleccionado =<?= json_encode($prestamos_seleccionado)?>;
    
    $(document).ready(function(){

        //$("#<?php /*echo Chtml::activeId($model,'monto_solicitado');*/ ?>").maskMoney();
        $('#<?php echo CHtml::activeId($model,'monto_solicitado'); ?>').mask("#.##0,00", {reverse: true});
        verificarSeleccion();
    });


  $('#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){
              <?php if($configuracion->metodo_seleccion_prestamo_asociado==1){ ?>

                        return '<input type="checkbox" checked = "checked"  readonly  onclick="return false;"   class="checkbox_creditos" name="Credito['+ $('<div/>').text(data).html() +'][id]" value="' + $('<div/>').text(data).html() + '">';

                  <?php  }
                    else{?>
                      

                      let marcar_seleccionado = (prestamos_seleccionado[full.idcredito])?'checked = "checked"': "";

                      return '<input type="checkbox" '+marcar_seleccionado+' class="checkbox_creditos" onChange = "verificarSeleccion()" name="Credito['+ $('<div/>').text(data).html() +'][id]" value="' + $('<div/>').text(data).html() + '">';

                  <?php  }
                  ?>
           }
        },{
          'targets': 7,
          'render': function (data, type, full, meta){
                return '<span id="'+full.idcredito+'">' + $('<div/>').text(data).html() + '</span>';
           }
        }],
        "searching": false,
        "bLengthChange":   false,
     

    } );

     $('#tabla').on('change', '.checkbox_creditos', function(){ 

    verificarSeleccion();
});

  $('#selecionar_todo').on("change",function() {

     let checked = $(this).prop('checked');

     $('#tabla input[type=checkbox]:not("#selecionar_todo")').each(function() {

        $(this).prop("checked",checked);

      });

      verificarSeleccion();

  });


   function verificarSeleccion() {
      
    let monto = 0;


    $('#tabla input[type=checkbox]:not("#selecionar_todo")').each(function() {

      
        if($(this).is(":checked")){

            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-saldo-deudor").html(convertNumberFloatZero(monto)+' Bs');

  }
  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]);
    }
</script>
