<?php
Yii::app()->clientScript->registerCoreScript('jquery.ui');
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/plDialog/plDialog.js', CClientScript::POS_HEAD);

$phoneList = $model->renderPhoneNamesDropdown();

$phone = null;
if (isset($_GET['phone'])) {
    $phone = $_GET['phone'];

    // Set current phone as active
    if (array_key_exists($phone, $phoneList)) {
        $phoneList[$phone]['active'] = true;
    }
}

$phonesDropdown = array(
    'label' => $model->name,
    'url' => '#',
    'items' => $phoneList
);

$this->widget('ext.PlNavbar', array(
    'brand' => __('PHONEKEYS_NAVBAR_TITLE'),
    'items' => array(
        array(
            'class' => 'bootstrap.widgets.TbMenu',
            'items' => array(
                '---',
                $phonesDropdown,
            ),
        ),
    ),
    'htmlOptions' => array(
        'data-translation-id' => 'PHONEKEYS_NAVBAR_TITLE',
    ),
));

$this->widget('bootstrap.widgets.TbAlert', array(
    'block' => true, // display a larger alert block?
    'fade' => true, // use transitions?
    'closeText' => '&times;', // close link text - if set to false, no close link is displayed
));

Yii::app()->clientScript->registerScript(
        'autoHideAlert', 'setTimeout(function(){$(".alert").alert("close")}, 3000);', CClientScript::POS_READY
);

$this->beginWidget('CActiveForm', array(
    'id' => 'routing-outbound-form',
    'enableAjaxValidation' => false,
));


if (isset($alert)) {
    foreach ($alert as $note) {
        echo $note . "<br>";
    }
}

if ($user && $model->getPhoneKeysDataProvider($user, "") != null) {
    echo CHtml::dropDownList('Dummy[queue_list]', '', $this->getUserQueues(), array('style' => 'display:none'));
    echo CHtml::textField('Dummy[text_field]', '', array('style' => 'display:none'));
    echo CHtml::dropDownList('Dummy[forward_list]', '', $this->getForwardList(), array('style' => 'display:none'));
    echo CHtml::dropDownList('Dummy[callgroup_list]', '', $this->getUserCallGroup(), array('style' => 'display:none'));
    $keyLevels = $model->getAvailableKeyLevels();

    if (count($keyLevels) == 0) {
        $keyLevels[] = array();
    }

    foreach ($keyLevels as $keyLevel) {

        if (!array_key_exists('level', $keyLevel)) {
            continue;
        }

        echo "<h4 data-translation-id=" . @$keyLevel["name"] . ">" . __(@$keyLevel["name"]) . "</h4>";

        $this->widget('bootstrap.widgets.TbGridView', array(
            'id' => 'phone-key-grid',
            'dataProvider' => $model->getPhoneKeysDataProvider($user, $keyLevel["level"]),
            'type' => 'striped bordered condensed', //change color from columns in 'white' and 'grey' responsively
            'itemsCssClass' => 'plTable',
            'summaryText' => false, //change design of the table, removed search bar
            'columns' => array(
                array(
                    'name' => 'name',
                    'type' => 'raw',
                    'value' => array($this, 'renderKeyName'),
                    'header' => __('PHONEKEYS_MODEL_KEY'),
                    'headerHtmlOptions' => array('data-translation-id' => 'PHONEKEYS_MODEL_KEY')
                ),
                array(
                    'name' => 'function',
                    'type' => 'raw',
                    'value' => array($this, 'renderLocked'),
                    'header' => __('PHONEKEYS_MODEL_FUNCTION'),
                    'headerHtmlOptions' => array('data-translation-id' => 'PHONEKEYS_MODEL_FUNCTION')
                ),
                array(
                    'name' => 'number_data',
                    'type' => 'raw',
                    'value' => array($this, 'renderLocked'),
                    'header' => __('PHONEKEYS_MODEL_NUMBER_DATA'),
                    'headerHtmlOptions' => array('data-translation-id' => 'PHONEKEYS_MODEL_NUMBER_DATA')
                ),
                array(
                    'name' => 'label',
                    'type' => 'raw',
                    'value' => array($this, 'renderLocked'),
                    'header' => __('PHONEKEYS_MODEL_LABEL_DATA'),
                    'headerHtmlOptions' => array('data-translation-id' => 'PHONEKEYS_MODEL_LABEL_DATA')
                ),
                array(
                    'name' => 'locked',
                    'type' => 'raw',
                    'value' => array($this, 'renderLocked'),
                    'header' => __('PHONEKEYS_MODEL_LOCKED'),
                    'headerHtmlOptions' => array('data-translation-id' => 'PHONEKEYS_MODEL_LOCKED'),
                ),
                array(
                    'class' => 'ext.PlGrid.PlCButtonColumn',
                    'template' => '{restore}',
                    'header' => __('GLOBAL_RESTORE_BUTTON'),
                    'buttons' => array(
                        'restore' => array(
                            'label' => __('GLOBAL_RESTORE_BUTTON'),
                            'icon' => 'icon-level-up',
                            'url' => '$data->id',
                            'visible' => array($this, 'restoreButtonVisibility'),
                            'options' => array(
                                'class' => 'restoreBtn',
                                'data-translation-id' => __('GLOBAL_RESTORE_BUTTON'),
                                'onclick' => 'showRestoreConfirmDialog(this); return false;',
                            )
                        ),
                    ),
                ),
            ),
                )
        );
    }
}

echo CHtml::submitButton('save', array('id' => 'savePhoneKeyAction', 'style' => 'display:none'));

$this->widget('bootstrap.widgets.TbButton', array(
    'buttonType' => 'button',
    'type' => 'primary',
    'label' => __('GLOBAL_SAVE_AND_RESTART_BUTTON'),
    'loadingText' => 'loading...',
    'htmlOptions' => array(
        'id' => 'savePhoneKeyButton',
        'data-translation-id' => 'GLOBAL_SAVE_AND_RESTART_BUTTON',
    ),
));

$this->endWidget();
if (Yii::app()->user->translateMode) {
    $options = $model->getOptions(false);
    foreach ($options as $id => $value) {
        echo '<i data-translation-id="' . $value['label'] . '" data-translation-target="TEST"></i>';
    }
    $modalTranslationKeys = array(
        'PHONEKEYS_RESTORE_DEFAULT_KEY_MESSAGE',
        'PHONEKEYS_RESTORE_DEFAULT_KEY_HEADER',
        'PHONEKEYS_RESTORE_DEFAULT_KEY_CONFIRM',
        'PHONEKEYS_RESTORE_DEFAULT_KEY_STAY'
    );
    foreach ($modalTranslationKeys as $modalTranslationKey) {
        echo "<i data-translation-target='$modalTranslationKey' data-translation-id='$modalTranslationKey' >";
        echo "$modalTranslationKey => " . __("$modalTranslationKey");
        echo '</i></br>';
    }
}
?>
<script>
    $('#savePhoneKeyButton').click(function () {
        var btn = $(this);
        btn.button('loading'); // call the loading function
        $("#savePhoneKeyAction").click();
    });

    function toggleKeySelection(field) {

        var dummyQueueList = $("#Dummy_queue_list");
        var dummyTextField = $("#Dummy_text_field");
        var dummyForwardList = $("#Dummy_forward_list");
        var dummyCallGroupList = $("#Dummy_callgroup_list");
        var id = $(field).attr('id').split('_function')[0];

        var value = $(field)[0].options[$(field)[0].selectedIndex].text;

        var currentField = $('#' + id + '_number_data');

        var valueNoOverwrite = "<?php echo __('PHONE_TIPTEL_FUNCTION_NOT_OVERRIDE'); ?>";
        var valueEmpty = "<?php echo __('PHONE_TIPTEL_FUNCTION_EMPTY'); ?>";
        var login_logout_queues = "<?php echo __('PHONE_TIPTEL_FUNCTION_QUEUE_LOGIN'); ?>";
        var valueForward = "<?php echo __('PHONE_TIPTEL_FUNCTION_FORWARD'); ?>";
        var login_logout_callgroup = "<?php echo __('PHONE_TIPTEL_FUNCTION_CALLGROUP_LOGIN'); ?>";

        var disableDataFieldList = [
            valueNoOverwrite,
            valueEmpty,
            "<?php echo __('PHONE_TIPTEL_FUNCTION_VOICEMAIL'); ?>",
            "<?php echo __('PHONE_TIPTEL_FUNCTION_DND'); ?>",
            "<?php echo __('PHONE_TIPTEL_FUNCTION_ALL_QUEUES_LOGOUT'); ?>",
            "<?php echo __('PHONE_TIPTEL_FUNCTION_ALL_QUEUES_LOGIN'); ?>"
        ];

        $('#' + id + '_label').removeAttr('disabled');

        if (value === login_logout_queues) {
            var newField = dummyQueueList.clone();
            changeReplaceCurrentFieldWithNew(id, currentField, newField);
        } else if (value === valueForward) {
            var newField = dummyForwardList.clone();
            changeReplaceCurrentFieldWithNew(id, currentField, newField);
        } else if (value === login_logout_callgroup) {
            var newField = dummyCallGroupList.clone();
            changeReplaceCurrentFieldWithNew(id, currentField, newField);
        } else {
            var newField = dummyTextField.clone();
            changeReplaceCurrentFieldWithNew(id, currentField, newField);
            if ($.inArray(value, disableDataFieldList) !== -1) {
                newField.attr('disabled', 'disabled');
            }
        }
        if (value === valueNoOverwrite || value === valueEmpty) {
            $('#' + id + '_label').val('');
            $('#' + id + '_label').attr('disabled', 'disabled');
        }
    }

    function changeReplaceCurrentFieldWithNew(id, currentField, newField) {
        newField.attr("id", id + '_number_data');
        newField.attr("name", currentField.attr('name'));
        currentField.replaceWith(newField);
        newField.show();
    }

    function showRestoreConfirmDialog(restoreBtn) {
        var restoreBtnID = $(restoreBtn).attr("href");
        var options = {
            confirmMessage: "<?php echo __('PHONEKEYS_RESTORE_DEFAULT_KEY_MESSAGE'); ?>",
            dialogHeader: "<?php echo __('PHONEKEYS_RESTORE_DEFAULT_KEY_HEADER'); ?>",
            confirmText: "<?php echo __('PHONEKEYS_RESTORE_DEFAULT_KEY_CONFIRM'); ?>",
            cancelText: "<?php echo __('GLOBAL_CANCEL_BUTTON'); ?>",
            confirmCmd: function () {
                restoreKey(restoreBtnID, true);
            },
            addButton: {
                "stay": {
                    text: "<?php echo __('PHONEKEYS_RESTORE_DEFAULT_KEY_STAY'); ?>",
                    id: 'dialog-confirm_stay',
                    class: 'modalSaveBtn btn btn-info',
                    click: function () {
                        restoreKey(restoreBtnID);
                    }
                }
            }
        };

        var plDialog = new $.plDialog(options);
        plDialog.showConfirmDialog();
    }


    function restoreKey(id, triggerSaveBtn = false) {
        $.ajax({
            url: "<?php echo url('phonesettingsPhoneKey/default/restoreKey'); ?>",
            type: "POST",
            dataType: "json",
            data: {
                id: id
            },
            success: function (result) {
                $.each(result, function (index, button) {
                    $('#' + index).val(button);
                });
                $('.restoreBtn[href$="' + id + '"]').hide();
                $('#dialog-confirm.modal-body').dialog("close");
                if (triggerSaveBtn === true) {
                    $('#savePhoneKeyButton').click();
                }
            }
        });
    }

</script>