<?php
/* @var $model Expensesettlement */
/* @var $users array */

$form = $this->beginWidget('CActiveForm', array(
    'id' => 'expensesettlement-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => false,
));
?>

<div class="tab-content">
    <div class="tab-pane active">
        <ul class="clearfix form-ul material">

            <li class="col-sm-6">
                <input type="hidden" name="from" id="from" value="<?php echo $from; ?>">
                <?php echo $form->hiddenField($model, 'id'); ?>

                <?php echo $form->textField($model, 'settlement_date', array(
                    'class' => 'datepicker',
                    'data-label' => 'Settlement Date',
                    'value' => $model->settlement_date
                        ? date('d-m-Y', strtotime($model->settlement_date))
                        : date('d-m-Y')
                )); ?>
            </li>

            <?php
            $loginUserId = Yii::app()->user->id;
            $modeluser  = User::model()->findByPk($loginUserId);

            $users = array();
            $selectedUserId = $model->user_id ?: null;

            if ($modeluser->user_group_id != 1) {
                $users = array($loginUserId => $modeluser->username);
                if (empty($model->user_id)) {
                    $selectedUserId = $loginUserId;
                }
            } else {
                $allUsers = User::model()->findAll(array('order' => 'username ASC'));
                $users = CHtml::listData($allUsers, 'id', 'username');
            }
            ?>

            <li class="col-sm-6">
                <?php echo CHtml::dropDownList(
                    'user_id',
                    $selectedUserId,
                    $users,
                    array(
                        'class' => 'tooltipster',
                        'data-label' => 'Users',
                        'prompt' => 'Select User',
                        'data-search' => 'true'
                    )
                ); ?>
            </li>

            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('Unsettled Expenses', 'Expensesettlement_unsettled_expenses'); ?>
                </div>
                <div class="col-sm-8">
                    <?php echo $form->textField($model, 'unsettled_expenses', array(
                        'id' => 'Expensesettlement_unsettled_expenses',
                        'readonly' => true
                    )); ?>
                </div>
            </li>

            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('Balance', 'balance_field'); ?>
                </div>
                <div class="col-sm-8">
                    <?php echo $form->hiddenField($model, 'expense_details_id', array('id' => 'expense_details_id')); ?>
                    <?php echo $form->textField($model, 'balance', array(
                        'id' => 'balance_field',
                        'readonly' => true
                    )); ?>
                </div>
            </li>

            <!-- ================= ROW 3 ================= -->
            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('Amount Returned', 'Expensesettlement_amount_returned'); ?>
                </div>
                <div class="col-sm-8">
                    <?php echo $form->textField($model, 'amount_returned', array('id' => 'Expensesettlement_amount_returned')); ?>
                </div>
            </li>

            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('Amount Dispersed', 'Expensesettlement_amount_dispersed'); ?>
                </div>
                <div class="col-sm-8">
                    <?php echo $form->textField($model, 'amount_dispersed', array('id' => 'Expensesettlement_amount_dispersed')); ?>
                </div>
            </li>

            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('New Balance', 'Expensesettlement_new_balance'); ?>
                </div>
                <div class="col-sm-8">
                    <?php echo $form->textField($model, 'new_balance', array(
                        'id' => 'Expensesettlement_new_balance',
                        'readonly' => true
                    )); ?>
                </div>
            </li>

            <li class="col-sm-12 form-row">
                <div class="col-sm-4 label-col">
                    <?php echo CHtml::label('Settlement', 'Expensesettlement_is_active'); ?>
                </div>
                <div class="col-sm-8">
                    <?php
                    $isEdit    = !$model->isNewRecord;
                    $isSettled = ($model->isActive === 'Y');

                    echo $form->checkBox($model, 'isActive', array(
                        'id'       => 'Expensesettlement_is_active',
                        'checked'  => ($isEdit && $isSettled),
                        'disabled' => ($isEdit && $isSettled),
                    ));
                    ?>

                    <?php if ($isEdit && $isSettled): ?>
                        <input type="hidden" name="Expensesettlement[isActive]" value="Y">
                    <?php endif; ?>
                </div>
            </li>

        </ul>
    </div>
</div>

<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    <?php
    $url = Yii::app()->createUrl('/expensesettlement/SaveExpenseType');

    echo CHtml::ajaxSubmitButton(
        'Save',
        $url,
        array(
            'type' => 'post',
            'dataType' => 'json',
            'beforeSend' => 'function(){ $("#loader").show(); }',
            'success' => 'function(data){
                $("#loader").hide();
                if(data.status=="success"){
                    t8.success("Expense Settlement Saved Successfully!");
                    $(".x.close").click();
                    reloadTable("#tbl_expense_settlement");
                }else{
                    $.each(data,function(k,v){ t8.error(v); });
                }
            }'
        ),
        array('class' => 'btn btn-theme', 'id' => 'btn-save-expense')
    );
    ?>
</div>

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

<style>
ul.form-ul li { margin-bottom:15px }
.form-row { display:flex; align-items:center }
.label-col label { font-weight:600; margin-top:6px }
input[readonly] { background:#f7f7f7 }
</style>

<script>
$(function(){

    $('#user_id').on('change', function(){
        var userId = $(this).val();
        if(!userId){
            $('#balance_field').val('');
            return;
        }

        $.ajax({
            url: '<?php echo Yii::app()->createUrl("expensesettlement/getUserBalance"); ?>',
            type: 'POST',
            dataType: 'json',
            data: { user_id: userId },
            success: function(res){
                $('#Expensesettlement_unsettled_expenses').val(res.unsettled);
                $('#balance_field').val(res.balance);
                $('#expense_details_id').val(res.expense_details_id);
            }
        });
    });

    function calcBalance(){
        var bal  = parseFloat($('#balance_field').val()) || 0;
        var disp = parseFloat($('#Expensesettlement_amount_dispersed').val()) || 0;
        var r    = parseFloat($('#Expensesettlement_amount_returned').val()) || 0;
        $('#Expensesettlement_new_balance').val(Math.max(bal + disp - r, 0));
    }

    $('#Expensesettlement_amount_dispersed, #Expensesettlement_amount_returned').on('input', calcBalance);

    if ($('#user_id').val() !== '') {
        $('#user_id').trigger('change');
    }

    if ($('#Expensesettlement_is_active').is(':checked')) {
        $('#btn-save-expense').hide();
    }
});
</script>
