<?php

$this->widget('ext.PlNavbar', array(
        'brand'=> $model->isNewRecord ? __('ROUTING_IVR_CREATE_NEW_VOICE_MENU') : __('ROUTING_IVR_UPDATE_VOICE_MENU') . ': ' . CHtml::encode($model->title),
        'collapse'=>false, // requires bootstrap-responsive.css
        'items'=>array(
            array(
                'class'=>'bootstrap.widgets.TbMenu',
                'items'=>array(),
            ),

        ),
        'htmlOptions' => array(
            'data-translation-target'=>'ROUTING_IVR_MANAGE_HEADER'
        ),
    ));


$form = $this->beginWidget('ext.PlGrid.PlActiveForm', array(
    'id' => 'ivr-form',
    'loadCoreScripts' => true,
    'type' => 'horizontal',
    'htmlOptions' => array('class' => 'well'),
    'action' => $model->isNewRecord ? array('create') : array(),
    'enableAjaxValidation' => true,
    'renderContextHelp' => true
        )
);

echo $form->textFieldRow($model, 'title', array(
		'class'=>'span3',
		'data-translation-id'=>'IVR_MODEL_TITLE',
));

if (cfg('DP_BRANCH_PREFIX')) {
    echo $form->textFieldRow($model, 'extension', array(
            'class'=>'span3',
            'prepend'=>cfg('DP_BRANCH_PREFIX'),
            'style'=>'width: 179px;',
            'data-translation-id'=>'IVR_MODEL_EXTENSION',
        ));
} else {
    echo $form->textFieldRow($model, 'extension', array(
            'class'=>'span3',
            'data-translation-id'=>'IVR_MODEL_EXTENSION',
        ));
}

echo $form->dropDownListRow($model, 'announce_file', $model->getAudioFileList(),
    array(
        'class'=>'span3',
        //             'data-translation-id'=>'IVR_MODEL_ANNOUNCE_FILE',
        'data-translation-target'=>'IVR_MODEL_ANNOUNCE_FILE_TARGET',
        'options' => array(
            ''=>array('label'=>'---')
        )
    ));
    
echo $form->textAreaRow($model, 'description', array(
        'class'=>'span3',
        'data-translation-id'=>'IVR_MODEL_DESCRIPTION',
    ));


if($model->isNewRecord){
    $model->answer_time = 10;
    $model->answer_retry = 2;
}
echo $form->textFieldRow($model, 'answer_time', array(
        'class'=>'span1',
        'data-translation-target'=>'IVR_MODEL_ANSWER_TIME',
        'append'=>__('IVR_MODEL_ANSWER_TIME_SECONDS')
    ));



echo $form->textFieldRow($model, 'answer_retry', array(
        'class'=>'span1',
        'data-translation-id'=>'IVR_MODEL_ANSWER_RETRY',
    ));


$action_keys = $model->getActionKeysData();
$translatedActions = $model->getTranslatedActionKeys();


// Select target user
$availableTragets = $model->getAvailableRoutingTargets();
$availableTragets[__('RENDER_TARGET_MANUAL')] = array(TargetType::Manual=>__('RENDER_TARGET_TYPE_MANUAL'));
$availableTragetUsers = $model->getAvailableUserTargets();
$audiofileList = $model->renderAnnounceFile();

$availableKeys = $model->getAvailableKeys();
echo $form->errorSummary($model);
foreach( $availableKeys as $keyName){

    $formPrefix = "IVR[keys]";

    $keyActionName = $formPrefix."[".$keyName."][action]";
    $keyTargetName = $formPrefix."[".$keyName."][target]";
    $keyMetaName = $formPrefix."[".$keyName."][meta]";

    $targetExtensionModelAttribute = 'key_'.$keyName.'_targetExtension';
    $targetTypeModelAttribute = 'key_'.$keyName.'_targetType';
    $targetModelAttribute = 'key_'.$keyName.'_target';
    $actionModelAttribute = 'key_'.$keyName.'_action';
    $metaModelAttribute = 'key_'.$keyName.'_meta';

    $translatedActionsTemp = $translatedActions;
    if($keyName == 'noInput' || $keyName == 'invalid'){
        if($model->$actionModelAttribute == null) {
            $model->$actionModelAttribute = 1;
        }
        unset ($translatedActionsTemp[0]);
    }

    echo '<div class="actionKeys">';

    // Select action
    echo $form->dropDownListRow(
        $model,
        'key_'.$keyName.'_action',
        $translatedActionsTemp,
        array(
            'name' => $keyActionName,
            'class'=>'span2',
            'onChange'=>'check(this);',
            'data-translation-id'=> 'IVR_MODEL_ACTION_KEY_'. strtoupper($keyName),
            'data-translation-target'=>'RENDER_TARGET_TYPES'. strtoupper($keyName),

        ));


    // Select target voicemail

    $visbleStyle = '';
    if($model->$actionModelAttribute == KeyType::hangUp) {
        $visbleStyle = 'style="display:inline-block;"';
    }

    $selectedTargetNumber = TargetType::Manual;
    if($model->$targetTypeModelAttribute != TargetType::Manual) {
        $selectedTargetNumber = $model->$targetTypeModelAttribute . '_';
        $selectedTargetNumber .= base64_encode($model->$targetExtensionModelAttribute) . '_';
        $selectedTargetNumber .= $model->$targetModelAttribute;
    }

    $visbleStyle = '';
    if($model->$actionModelAttribute == KeyType::targetNumber &&
        $model->$targetTypeModelAttribute != TargetType::Manual
    ){
        $visbleStyle = 'style="display:inline-block;"';
    }
    $targetErrorClass ="";
    if(isset($model->errors[$targetModelAttribute])) {
        $targetErrorClass = "error";
    }
    
    echo '<div class="targetNumber keyOptions"'. $visbleStyle .'>';
    
    echo CHtml::dropDownList(
        $keyTargetName . '['.KeyType::targetNumber.']',
        $selectedTargetNumber,
        $availableTragets,
        array(
            'class'=>'span2 '.$targetErrorClass,
            'data-translation-target'=>'RENDER_TARGET_NUMBER_TYPES',
            'onChange'=>'checkManualNumber(this);',
        )
    );
    echo '</div>';


    // Select custom number

    $visbleStyle = '';
    if($model->$actionModelAttribute == KeyType::targetNumber && $model->$targetTypeModelAttribute == TargetType::Manual){
        $visbleStyle = 'style="display:inline-block;"';
    }

    echo '<div class="targetCustomNumber keyOptions"'. $visbleStyle .'>';
    echo CHtml::textField(
        $keyTargetName . '[customNumber]',
        $model->$targetTypeModelAttribute == TargetType::Manual ? $model->$targetModelAttribute : null,
        array(
            'class' => 'hideableInput span2 '.$targetErrorClass,
        )
    );
    echo '</div>';


    // Select voicemail target user //base64_encode($model->$targetExtensionModelAttribute)
    $selectedTargetNumber = TargetType::Manual;
    if($model->$targetTypeModelAttribute != TargetType::Manual){
        $selectedTargetNumber = $model->$targetTypeModelAttribute . '_';
        $selectedTargetNumber .= base64_encode($model->$targetExtensionModelAttribute) . '_';
        $selectedTargetNumber .= $model->$targetModelAttribute;
    }

    $visbleStyle = '';
    if($model->$actionModelAttribute == KeyType::voiceMail){
        $visbleStyle = 'style="display:inline-block;"';
    }

    echo '<div class="targetVoicemail keyOptions"'. $visbleStyle .'>';
    echo CHtml::dropDownList(
        $keyTargetName . '['.KeyType::voiceMail.']',
        $selectedTargetNumber,
        $availableTragetUsers,
        array(
            'class'=>'span2 '.$targetErrorClass,
            'onChange'=>'checkManualNumber(this);',
        )
    );
    echo '</div>';


    // Select target voicemail
    $visbleStyle = '';
    if($model->$actionModelAttribute != KeyType::noneSelected){
        $visbleStyle = 'style="display:inline-block;"';
    }

    echo '<div class="voiceMail keyOptions"'. $visbleStyle .'>';
//     echo '<span class="required" '. $visbleStyle .'>*</span>';
    
    $metaErrorClass = "";
    if (isset($model->errors[$metaModelAttribute])) {
        $metaErrorClass = 'error';
    }
    
    echo CHtml::dropDownList(
        $keyMetaName,
        $model->$metaModelAttribute,
        $audiofileList,
        array(
            'class'=>'span2 '.$metaErrorClass
        )
    );
    echo '</div>';

    echo '</div>';

}

if (PhonalisaLicenseManager::routingScriptExtensionMax() !== 0) {
    echo $form->dropDownListRow($model, 'scriptExtension', ScriptExtension::model()->listData, array(
        'class' => 'span3',
        'data-translation-id' => 'USER_MODEL_SCRIPT_EXTENSION',
            )
    );
}



echo "<br>";

$this->widget('bootstrap.widgets.TbButton', array(
        'buttonType'=>'submit',
        'type'=>'primary',
        'label'=>__('GLOBAL_SAVE_BUTTON'),
        'loadingText'=>'loading...',
        'htmlOptions'=>array(
            'id'=>'savePhonesettingsNotificationsButton',
            'data-translation-id'=>'GLOBAL_SAVE_BUTTON',
        ),

    ));


$this->endWidget();



if (Yii::app()->user->translateMode) {

    echo '<i data-translation-target="IVR_MODEL_ANNOUNCE_FILE_TARGET" data-translation-id="ROUTING_IVR_SELECT_VOICEMESSAGE"></i>';
    echo '<i data-translation-target="IVR_MODEL_ANNOUNCE_FILE_TARGET" data-translation-id="IVR_MODEL_ANNOUNCE_FILE"></i>';


    echo '<i data-translation-target="IVR_MODEL_ANSWER_TIME" data-translation-id="IVR_MODEL_ANSWER_TIME_SECONDS"></i>';
    echo '<i data-translation-target="IVR_MODEL_ANSWER_TIME" data-translation-id="IVR_MODEL_ANSWER_TIME"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="ROUTING_IVR_SELECT_TARGET"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_USER"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_GROUP"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_IVR"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_QUEUE"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_CONFERENCE"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_MANUAL"></i>';
    echo '<i data-translation-target="RENDER_TARGET_NUMBER_TYPES" data-translation-id="RENDER_TARGET_TYPE_MANUAL"></i>';
    echo '<i data-translation-target="ROUTING_IVR_MANAGE_HEADER" data-translation-id="ROUTING_IVR_ADD_NEW_VOICE_MENU"></i>';
    echo '<i data-translation-target="ROUTING_IVR_MANAGE_HEADER" data-translation-id="ROUTING_IVR_UPDATE_VOICE_MENU"></i>';
    echo '<i data-translation-target="ROUTING_IVR_MANAGE_HEADER" data-translation-id="ROUTING_IVR_CREATE_NEW_VOICE_MENU"></i>';

    $actionKeys = $model->getActionKeys();
    $actionKeys[] = 'IVR_KEY_TARGET_NOT_DEFINED_ERROR';
    $actionKeys[] = 'IVR_KEY_META_NOT_DEFINED_ERROR';
    foreach($actionKeys as $translationKey) {
        foreach($availableKeys as $keyName) {

            echo '<i data-translation-target="RENDER_TARGET_TYPES'.strtoupper($keyName).'" data-translation-id="'.$translationKey.'"></i>';
        }


    }
}
?>

<style>
.hideableClose{
    cursor: pointer;
    background-color: #fff; /*FIXME */

}
.hideableClose:after{
    color: #999;
    content: "\f00d";
    font-family: FontAwesome;
    margin-left: -20px;
    vertical-align: middle;
    font-style: normal;
}

.hideableClose:hover:after{
    color: #666;
}
</style>
<script>
$('<i class="hideableClose" ></i>').insertAfter($('.hideableInput'));
$(".hideableInput").parent().on('click', '.hideableClose' , function(el){
    $parent = $(this).parent();

    $parent.hide();
    $parent.prev().css("display","inline-block");
    $parent.prev().find('select').val('');
});

function check(elem) {
	   if(elem.options[elem.selectedIndex].value == '1'){
	       $(elem).parents().eq(2).find('.keyOptions').hide();
	       $(elem).parents().eq(2).find('.voiceMail').css("display","inline-block");
	       $(elem).parents().eq(2).find('.recordedMessage').css("display","inline-block");
	   }
	   else if(elem.options[elem.selectedIndex].value == '2'){
	       $(elem).parents().eq(2).find('.keyOptions').hide();
	       $(elem).parents().eq(2).find('.voiceMail').css("display","inline-block");
	       $(elem).parents().eq(2).find('.targetNumber select').val('');
    	   $(elem).parents().eq(2).find('.targetNumber').css("display","inline-block");
	   }
	   else if(elem.options[elem.selectedIndex].value == '3'){
	       $(elem).parents().eq(2).find('.keyOptions').hide();
	       $(elem).parents().eq(2).find('.targetVoicemail').css("display","inline-block");
	       $(elem).parents().eq(2).find('.voiceMail').css("display","inline-block");
	   }
	   else if(elem.options[elem.selectedIndex].value == '4'){
            $(elem).parents().eq(2).find('.keyOptions').hide();
    	   $(elem).parents().eq(2).find('.voiceMail').css("display","inline-block");
	   }
	   else {
	       $(elem).parents().eq(2).find('.keyOptions').hide();
       }

	}

function checkManualNumber(elem){
    if(elem.options[elem.selectedIndex].value == 2){
        $(elem).parent().hide();
        $(elem).parents().eq(1).find('.targetCustomNumber').css("display","inline-block");
    }
    else{
        $(elem).parents().eq(1).find('.targetCustomNumber').hide();
    }
}
</script> 