<?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
/* @var $this RetiroParcialController */
/* @var $model RetiroParcial */

$this->breadcrumbs=array(
	'Retiro Parcials'=>array('index'),
	'Createadmin',
);

$this->menu=array(
	array('label'=>'List RetiroParcial', 'url'=>array('index')),
	array('label'=>'Manage RetiroParcial', 'url'=>array('admin')),
);
?>

<h3 style="text-align: center">Solicitud de Retiro Parcial </h3>

<?php
/* @var $this RetiroParcialController */
/* @var $model RetiroParcial */
/* @var $form CActiveForm */
?>

<?php 

$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id'=>'retiro-parcial-form',
	'type' => 'horizontal',
        'enableAjaxValidation' => false,
        'enableClientValidation' => true,
        'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => true,
        'validateOnType' => true,
        ),
)); 
$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
    ),
));

?>    
<div class="row">
  <div class="span6">
    <?php echo CHtml::label('Cédula de Identidad del Solicitante:<span class="required">*</span>',''); ?>
    <?php echo  $form->textfield($model, 'cedula');?>
    <input type="button" onclick="return buscar_datos()" value="BUSCAR">
    <br>
     <?php echo  $form->error($model, 'cedula');?>
  </div>
</div><br>
    <div  id="detalleretiro"></div>
    <div id="gifCargando" style="display: none; text-align: center;"><img src="<?php echo Yii:: app() ->baseUrl.'/images/ajax-loader.gif' ?>"></div>
    <?php echo $this->renderPartial('application.modules.asociado.views.asociado.detallesHaberesSocio', array('id'=>NULL,'ocultarDetalle'=>true)); ?>
    
    <?php if($modelConfiguracion->pago_prestamo_retiro_administrador > 0){?>
    <div class="well creditos" style="display: none">
      <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($modelConfiguracion->metodo_seleccion_prestamo_administrador==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>
      </fieldset>  
    </div>
  <?php } ?>
    <div id="montos_permitidos"></div>   

<div class="alert alert-info">
        
       
       <div class="row">
                <div class="span5">
                    <?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 class="span4">
                    <?php echo $form->labelEx($model,'fecha_solicitud') ;?>
                              <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                        'model' => $modelEstatusRetiro,
                                        'attribute' => 'fecha_registro',
                                        'value' => $modelEstatusRetiro->fecha_registro,
                                        'language' => 'es',
                                        'htmlOptions' => array('readonly' => "readonly", 'class' => 'input-xlarge'),
                                        //additional javascript options for the date picker plugin
                                        'options' => array(
                                            'autoSize' => true,
                                            // 'defaultDate'=>$model->fechanacimiento,
                                            //'dateFormat'=>'yy-m-d',
                                            'dateFormat' => 'dd-mm-yy',
                                            'buttonImage' => Yii::app()->baseUrl . '/images/calendar.png',
                                            'buttonImageOnly' => true,
                                            'buttonText' => 'Fecha',
                                            'selectOtherMonths' => true,
                                            'showAnim' => 'slide',
                                            'showButtonPanel' => true,
                                            'showOn' => 'button',
                                            'changeMonth' => 'true',
                                            'changeYear' => 'true',
                                            'maxDate'=> "+0D",
                                        ),
                                    ));
                              ?>
                              <?php echo $form->error($modelEstatusRetiro,'fecha_registro') ;?>
                </div>
       </div>   
       <br>
       <div class="row">
            <div class="span5">
            <?php echo CHtml::label('<strong>Seleccione cuenta bancaria donde se abonaran sus haberes:</strong>',''); ?>
            <?= $form->dropDownList($model,'cuenta',
                    CHtml::listData(AsociadoCuentaBanco::model()->with(['idBanco','idAsociado'])->together(true)->findAll([
                                'select'=>"t.cuenta_bancaria AS id, \"idBanco\".descripcion ||''|| (CASE WHEN cuenta_corriente = true THEN 'Cuenta Corriente' ELSE 'Cuenta de Ahorro' END)||' '|| \"t\".cuenta_bancaria as cuenta_bancaria",
                                'condition'=>'cedula=:cedula AND  id_estatus=1 AND t.blnborrado = false',
                                'params'=>[':cedula'=>$model->cedula]]),'id','cuenta_bancaria'),['style'=>"width:100%",'prompt'=>'-- SELECCIONE EL NUMERO DE CUENTA BANCARIO --']);
                ?>
            </div>
       </div>
       

</div>
     <div class="form-actions"  style="padding-left: 0; text-align: center">
        <?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType' => 'submit',
			'type' => 'success',
			'id' => 'btn_registrar',
                        'icon'=>'icon-ok',
			'label' => 'Solicitar Retiro Parcial',

    ));?>
</div>

<?php $this->endWidget(); ?>
<script>
  let prestamos_seleccionado =<?= json_encode($prestamos_seleccionado)?>;

  $('#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($modelConfiguracion->metodo_seleccion_prestamo_administrador==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);
        }

    });

    html = `<div id = "montos-prestamos-retiro-parcial" class="row">
                <div class="span3"><b>Monto pr&eacute;stamos seleccionados:</b></div>
                <div class="span2 text-right" >${convertNumberFloatZero(monto)} Bs</div>
            </div>`;
    
    $("#montos-prestamos-retiro-parcial").remove();
    $("#montos-retiro-parcial").append(html);

  }

    $(document).ready(function(){

        //$("#<?php /*echo Chtml::activeId($model,'monto_solicitado');*/ ?>").maskMoney();
        $('#<?php echo CHtml::activeId($model,'monto_solicitado'); ?>').mask("#.##0,00", {reverse: 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]);
    }


    function buscar_datos() {
        $("#accordion").hide("slow"); 
        var ruta ="<?php echo Yii::app()->createAbsoluteUrl("/retiro/RetiroParcial/createAdministrador"); ?>";

        if($("#<?php echo Chtml::activeId($model,'cedula'); ?>").val()!="") {    
          
          var cedula=$("#<?php echo Chtml::activeId($model,'cedula'); ?>").val();
          
          $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            url: '<?php echo Yii::app()->createAbsoluteUrl("/asociado/Asociado/haberesSocioRetiroParcial"); ?>',
            data: ({cedulaAsociado:cedula}),

            beforeSend: function(xkr){

                    $("#detalleretiro").html("");

                    $("#montos_permitidos").html("");

                    $("#gifCargando").show("slow"); 

                    <?php if($modelConfiguracion->pago_prestamo_retiro_administrador > 0){ ?>

                        $(".well.creditos").hide("slow"); 

                        $('#tabla').DataTable().clear().draw(); 
                    <?php }?>

                    $("#<?= CHtml::activeId($model,'cuenta'); ?>").empty(); 
                    $("#<?= CHtml::activeId($model,'cuenta'); ?>").append('<option value="">- SELECCIONE EL NUMERO DE CUENTA BANCARIO --</option>'); 
                            

            },

            success:function(data) {
              $("#detalleretiro").html(data.vista);

              $("#gifCargando").hide("slow"); 

              if(data.encontrado ==1){

                  buscarMontosPermitidos(data.idasociado); 

                 <?php if($modelConfiguracion->pago_prestamo_retiro_administrador > 0){ ?>

                      $(".well.creditos").show("fast");

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

                  <?php } ?>
                  
                  $.fn.yiiGridView.update('aporte-ordinario-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 
                  $.fn.yiiGridView.update('aporte-voluntario-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 
                  $.fn.yiiGridView.update('retiro-parcial-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 
                  $.fn.yiiGridView.update('reporte-creditos-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 
                  $.fn.yiiGridView.update('dividendos-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 
                  $.fn.yiiGridView.update('ajuste-haberes-grid',{type:'GET', url:ruta,data:'cedula='+cedula}); 

                  $("#accordion").show("slow");

                  $("#<?= CHtml::activeId($model,'cuenta'); ?>").html(data.datos_bancarios);

              
              }
	  },
	  error: function(data) { // if error occured
	    alert("Ha ocurrido un error , Contacte con el administrador");
	  },
	  // dataType:'html'
	});
    
  } else {
    $("#detalleretiro").html('');
    $("#accordion").hide("slow"); 
  }
}
    

    function buscarMontosPermitidos(idasociado){    
      //var idasociado=$("#<?php //echo Chtml::activeId($model,'cedula'); ?>").val();
      datas="cedula="+idasociado;
        $.ajax({
                type: 'POST',
                url: '<?php echo Yii::app()->createAbsoluteUrl("/Comun/MontosPermitidosRetiroParcial"); ?>',
                data:datas,
                beforeSend: function(xkr){
                    $("#montos_permitidos").html("");
                },
      success:function(data) {
        $("#montos_permitidos").html(data);
         <?php if($modelConfiguracion->pago_prestamo_retiro_administrador > 0){ ?>
                verificarSeleccion();
            <?php } ?>

      },
      error: function(data) { // if error occured
        alert("Ha ocurrido un error , Contacte con el administrador");
      },
      dataType:'html'
    });
    
  

    }

$("#<?php echo Chtml::activeId($model,'cedula'); ?>").change(function(){
    if($(this).val()=="")
        $("#detalleretiro").html('');
        $("#accordion").hide("slow"); 
});

$(document).ready(function() {
  $("form").keypress(function(e) {
    if (e.which == 13) {
      return false;
    }
    
  }); 
  if($("#<?php echo Chtml::activeId($model,'cedula'); ?>").val()!=""){
        buscar_datos();
    }
});
</script>
