<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js', CClientScript::POS_HEAD); ?>

<h2 style="text-align: center;">Retiro de aporte voluntario</h2>
<br>
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', [
    'id' => 'aporte-voluntario-admin-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
    'clientOptions' => [
        'validateOnSubmit' => true,
    ],
]); ?>

<p class="help-block">Los campos con <span class="required">*</span> son obligatorios.</p>

<?php echo $form->errorSummary($model); ?>

<fieldset>
    <!--Datos del asociado-->
    <legend style=" font-size: 17px;"><b>Datos del asociado</b></legend>
    <table class="table table-bordered">
        <tr>
            <td style="width: 25%"><b>
                    <?= $form->labelEx($model, 'acedula'); ?></b></td>
            <td style="width: 25%" id="cedula">
                <?= $modelAsociado->cedula; ?>
            </td>
            <td style="width: 20%"><b>Nombres y apellidos</b></td>
            <td style="width: 30%">
                <?= $modelAsociado->nombre.' '.$modelAsociado->apellidos; ?>
            </td>
        </tr>
        <tr>
            <td><b>Empresa</b></td>
            <td>
                <?= ($modelAsociado->lugartrabajo0) ? $modelAsociado->lugartrabajo0->descripcion : ''; ?>
            </td>
            <td><b>Unidad</b></td>
            <td>
                <?= ($modelAsociado->unidad) ? $modelAsociado->unidad->descripcion : ''; ?>
            </td>
        </tr>
        <tr>
            <td><b>&Uacute;ltimo sueldo</b></td>
            <td>
                <?= number_format($sueldo, 2, ',', '.'); ?> Bs.S</td>
            <td><b>Porcentaje de aporte</b></td>
            <td>
                <?= $porcentaje; ?>%</td>
        </tr>
        <tr>
            <td><b>Fecha de inscripci&oacute;n</b></td>
            <td>
                <?= date('d-m-Y', strtotime($modelAsociado->fechaingreso)); ?>
            </td>
            <td><b>Estatus</b></td>
            <td>
                <?= strtoupper($modelAsociado->idEstatus->nombre_estatus); ?>
            </td>
        </tr>
    </table>
</fieldset>
<!--fin datos del asociado-->
<br>
<div id="mensajes" class="datosPersonales"></div>
<div id="datos_aporte">
        <legend style=" font-size: 17px;"><b>Datos del retiro</b></legend>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th style="width: 45%;">Concepto</th>
                    <th style="width: 45%;">Monto</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tr>
                <td>Total aporte voluntario</td>
                <td>
                    <div id="aporte-voluntario-disponible" class="datosPersonales numero text-right">0,00</div>
                </td>
                <td></td>
            </tr>
            <tr>
                <td>Aporte voluntario capitalizado</td>
                <td>
                    <div id="aporte-voluntario-capitalizado" class="datosPersonales numero text-right">0,00</div>
                </td>
                <td style="text-align: center;">
                    <i class="icon icon-eye-open" style="cursor: pointer;" onclick="show('capitalizado')"></i>
                </td>
            </tr>
            <tr id="detalle_capitalizado_tr" class="well" style="display: none;" is-open="false">
                <td colspan="3" id="detalle_capitalizado"></td>
            </tr>
            <tr>
                <td>Aporte voluntario retirados</td>
                <td>
                    <div id="aporte-voluntario-retirados" class="datosPersonales numero text-right text-error">0,00</div>
                </td>
                <td style="text-align: center;">
                    <i class="icon icon-eye-open" style="cursor: pointer;" onclick="show('retirado')"></i>
                </td>
            </tr>
            <tr id="detalle_retirado_tr" class="well" style="display: none;" is-open="false">
                <td colspan="3" id="detalle_retirado"></td>
            </tr>
            <tr>
                <td>Total disponible</td>
                <td>
                    <div id="total-disponible" class="datosPersonales numero text-right">0,00</div>
                </td>
                <td></td>
            </tr>
        </table>
        <?= $form->textFieldRow($model, 'monto'); ?>
        <?= $form->dropDownListRow($model,'id_banco_asociado',
            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->acedula], ]), 'id', 'cuenta_bancaria'), ['class' => 'input-xxlarge', 'prompt' => 'Seleccione']);
        ?>
    </div>
<div class="form-actions" style="text-align: center;">
    <?php $this->widget('bootstrap.widgets.TbButton', [
        'buttonType' => 'submit',
        'type' => 'primary',
        'label' => 'Guardar',
        'htmlOptions' => ['id' => 'btn_registrar'],
    ]); ?>
</div>

<?php $this->endWidget(); ?>

<?php Yii::app()->clientScript->registerScript('datosAporteVoluntario', '
	monto_permitido = 0;

	$(document).ready(function(){

		$("#'.CHtml::activeId($model, 'monto').'").mask("#.##0,00", {reverse: true});

        $("#btn_registrar").prop("disabled", true);

        datosAporteVoluntario();

	});

    function show(tipo) {
        const url = "'.Yii::app()->urlManager->createUrl('/aportes/aporteVoluntario/conceptoDetalle').'";
        const data = {
            tipo,
            cedula: $("#cedula").html().trim()
        }

        const el = $(`#detalle_${tipo}_tr`)
        
        if (el.attr("is-open") == "true") {
            el.slideUp(120);
            el.attr("is-open", "false")
        } else {
            $.get(url, data, function (res) {
                if (! res.success) {
                    return alert(res.mensaje);
                }

                $(`#detalle_${tipo}`).html("")
                $(`#detalle_${tipo}`).html(res.content)

                el.slideDown(120);
                el.attr("is-open", "true")
            }, "json")
        }
    }

	function datosAporteVoluntario(){
                           
		$.ajax({
			url:"'.Yii::app()->urlManager->createUrl('/Comun/DatosRetiroAporteVoluntario').'",
			cache: false,
			type: "POST",
			dataType: "json",
			data: ({id:'.$modelAsociado->idasociado.',asc:1}),
			beforeSend: function(xkr){

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

				$("#'.CHtml::activeId($model, 'id_banco_asociado').'").empty();
            	$("#'.CHtml::activeId($model, 'id_banco_asociado').'").append(\'<option value="">- SELECCIONE EL NUMERO DE CUENTA BANCARIO --</option>\'); 
		        $("#btn-datos").prop("disabled", true);
		        
		        $(".datosPersonales.numero").html(`<div style="text-align: center;"><i class="fa fa-spinner fa-spin" style="font-size:29px;"></i></div>`);

		        monto_permitido = 0;
			},
			success: function(data){
                    // alert(new Intl.NumberFormat().format(data.total_aporte));
		        $(".datosPersonales.numero").html("");
		        $("#btn-datos").prop("disabled", false);
                $("#'.CHtml::activeId($model, 'id_banco_asociado').'").html(data.cuenta_banco);

                $("#aporte-voluntario-disponible").html(convertNumberFloatZero(eval(data.total_aporte)) + " Bs.S");
                $("#aporte-voluntario-capitalizado").html(convertNumberFloatZero(eval(data.monto_capitalizado)) + " Bs.S");
                $("#aporte-voluntario-retirados").html(convertNumberFloatZero(eval(data.monto_retiro)) + " Bs.S");
                $("#total-disponible").html(convertNumberFloatZero(eval(data.monto_disponible)) + " Bs.S");
                // $("#total-disponible").html(new Intl.NumberFormat().format(data.monto_disponible) + " Bs.S");

                monto_permitido = Number(data.monto_disponible).toFixed(2);

				$("#mensajes").html(data.mensaje);

				verificarMontoSolicitud();
                    
            }

		});
    }

    function verificarMontoSolicitud(){

    	monto = $("#'.CHtml::activeId($model, 'monto').'").val()
	            .replace(/\./g,"")
	            .replace(/,/g,".");

	    if( monto == "")

	    	monto = 0;

	    $("#btn_registrar").prop("disabled", true);

	    if (parseFloat(monto) > 0 && parseFloat(monto) <= parseFloat(monto_permitido)) {

	    	$("#btn_registrar").prop("disabled", 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]);
    }
', CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScript('datosAportdeVoluntario', '
	 $("#'.CHtml::activeId($model, 'monto').'").change(function(){

    	verificarMontoSolicitud();

    });

    ');
