<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\bootstrap\Modal;
use app\components\Utilities;
use app\models\Node;

$is_update = json_encode(Yii::$app->controller->action->id == 'update');
$destinationNodeName = null;
$selected_campaign_fields = null;
$selected_data_completion_fields = null;
$original_fields = null;

if($is_update){
    $selected_campaign_fields = Utilities::customJsonEncode($model->campaignFields);
    $selected_data_completion_fields = Utilities::customJsonEncode($model->dataCompletionFields);
    $original_fields = Utilities::customJsonEncode($fields);
    $destinationNode = Node::findOne($model->destinationNodeId);
    $destinationNodeName = $destinationNode ? $destinationNode['name'] : null;
}

$script =<<< JS
    var showIfFields  = $show_if_fields;
    var relatedFields = $related_fields;
    var isUpdate = $is_update;

    var showIfFieldsNames   = Object.keys(showIfFields);
    var showIfFieldsValues  = Object.values(showIfFields);
    var relatedFieldsNames  = Object.keys(relatedFields);
    var relatedFieldsValues = Object.values(relatedFields);

    $(document).ready(function(){

        if(isUpdate){
            var campaginFields = $selected_campaign_fields;
            var dataCompletionFields = $selected_data_completion_fields;
            var originalFields = $original_fields;

            for(var i = 0; i < originalFields.length; i++){
                if(! campaginFields.includes(originalFields[i]['name'])){
                    // Uncheck from campaign fields
                    $('input[name="CampaignFields[' + originalFields[i]['name'] + ']"]').prop('checked', false);

                    // Append to data completion fields
                    var text = originalFields[i]['label'] + ' (' + originalFields[i]['type'] + ')';
                    var isRequired = false;
                    if(originalFields[i]['is_required']){
                        isRequired = true;
                        text += ' REQUIRED FIELD';
                    }

                    var checked = false;
                    if(dataCompletionFields.includes(originalFields[i]['name'])){
                        checked = true;
                    }

                    var inputContainer = '<div class="data-completion-form-field"><label><input type="checkbox" class="completion-field-checkbox" name="DataCompletionFields[' + originalFields[i]['name'] + ']" id="' + originalFields[i]['name'] + '_comp" ' + (checked ? 'checked ' : '') + (isRequired ? 'disabled' : '') + '> ' + text + '</label></div>';
                    $('#data-completion-fields').append(inputContainer);

                    // Check show-if and related-list validation
                    for(var j = 0; j < relatedFieldsNames.length; j++){
                        if(relatedFieldsNames[j] == originalFields[i]['name']){
                            var childrenFields = relatedFieldsValues[j];
                            for(var k = 0; k < childrenFields.length; k++){
                                $('input[name="CampaignFields[' + childrenFields[k] + ']"]').prop('disabled', true);
                            }
                        }
                    }

                    for(var j = 0; j < showIfFieldsNames.length; j++){
                        if(showIfFieldsNames[j] == originalFields[i]['name']){
                            var childrenFields = showIfFieldsValues[j];
                            for(var k = 0; k < childrenFields.length; k++){
                                $('input[name="CampaignFields[' + childrenFields[k] + ']"]').prop('disabled', true);
                            }
                        }
                    }
                }
                else{
                    // Enable only the first child
                    for(var j = 0; j < relatedFieldsNames.length; j++){
                        if(relatedFieldsNames[j] == originalFields[i]['name']){
                            var firstChildField = relatedFieldsValues[j][0];
                            $('input[name="CampaignFields[' + firstChildField + ']"]').prop('disabled', false);
                        }
                    }

                    for(var j = 0; j < showIfFieldsNames.length; j++){
                        if(showIfFieldsNames[j] == originalFields[i]['name']){
                            var firstChildField = showIfFieldsValues[j][0];
                            $('input[name="CampaignFields[' + firstChildField + ']"]').prop('disabled', false);
                        }
                    }
                }
            }
        }

        $('.campaign-field-checkbox').change(function(){
            var isChecked = $(this).prop('checked');
            var text = $(this).parent().text();
            var name = $(this).prop('name');
            name = name.replace('CampaignFields[', '').replace(']', '');
            var id = $(this).prop('id');
            var isRequired = $(this).hasClass('required-field');

            // The field will be appear in the data completion section
            // If the field is required, it will appear as disabled because it must be a field in data completion, otherwisw there is capability to uncheck it
            if(! isChecked){
                $('#data-completion-fields').append('<div class="data-completion-form-field"><label><input type="checkbox" class="completion-field-checkbox" name="DataCompletionFields[' + name + ']" id="' + id + '_comp" checked ' + (isRequired ? 'disabled' : '') + '>' + text + '</label></div>');
                
                for(var i = 0; i < relatedFieldsNames.length; i++){
                    if(relatedFieldsNames[i] == name){
                        var childrenLists = relatedFieldsValues[i];
                        for(var j = 0; j < childrenLists.length; j++){
                            var childField = $('input[id="' + childrenLists[j] + '"]');
                            $(childField).prop('checked', false);
                            $(childField).prop('disabled', true);
                            if(! $('#data-completion-fields').find('input[id="' + childrenLists[j] + '_comp"]').length){
                                $('#data-completion-fields').append('<div class="data-completion-form-field"><label><input type="checkbox" class="completion-field-checkbox" name="DataCompletionFields[' + childrenLists[j] + ']" id="' + childrenLists[j] + '_comp" checked ' + ($(childField).hasClass('required-field') ? 'disabled' : '') + '>' + $(childField).parent().text() + '</label></div>');
                            }
                        }
                    }
                }

                for(var i = 0; i < showIfFieldsNames.length; i++){
                    if(showIfFieldsNames[i] == name){
                        var childrenFields = showIfFieldsValues[i];
                        for(var j = 0; j < childrenFields.length; j++){
                            var childField = $('input[id="' + childrenFields[j] + '"]');
                            $(childField).prop('checked', false);
                            $(childField).prop('disabled', true);
                            if(! $('#data-completion-fields').find('input[id="' + childrenFields[j] + '_comp"]').length){
                                $('#data-completion-fields').append('<div class="data-completion-form-field"><label><input type="checkbox" class="completion-field-checkbox" name="DataCompletionFields[' + childrenFields[j] + ']" id="' + childrenFields[j] + '_comp" checked ' + ($(childField).hasClass('required-field') ? 'disabled' : '') + '>' + $(childField).parent().text() + '</label></div>');
                            }
                        }
                    }
                }
            }
            else{
                $('#data-completion-fields').find('input[id="' + name + '_comp"]').closest('div').remove();

                for(var i = 0; i < relatedFieldsNames.length; i++){
                    if(relatedFieldsNames[i] == name){
                        var childrenLists = relatedFieldsValues[i];
                        // Only first child must be enabled
                        var firstChild = childrenLists[0];
                        var childField = $('input[id="' + firstChild + '"]');
                        $(childField).prop('disabled', false);
                        if($('#data-completion-fields').find('input[id="' + firstChild + '_comp"]').length){
                            $(childField).prop('checked', false);
                        }
                        else{
                            $(childField).prop('checked', true);
                        }
                    }
                }

                for(var i = 0; i < showIfFieldsNames.length; i++){
                    if(showIfFieldsNames[i] == name){
                        var childrenFields = showIfFieldsValues[i];
                        // Only first child must be enabled
                        var firstChild = childrenFields[0];
                        var childField = $('input[id="' + firstChild + '"]');
                        $(childField).prop('disabled', false);
                        if($('#data-completion-fields').find('input[id="' + firstChild + '_comp"]').length){
                            $(childField).prop('checked', false);
                        }
                        else{
                            $(childField).prop('checked', true);
                        }
                    }
                }
            }

            // Check if there is no fields checked, the submit button must be disabled
            var checkedFieldsCount = $('.campaign-field-checkbox:checked').length;
            if(checkedFieldsCount == 0){
                $('#submit-button').prop('disabled', true);
            }
            else{
                $('#submit-button').prop('disabled', false);
            }
        });

        $('#search-icon').click(function(){
            $('#search-input').val('');
            $('.form-field').show();
        });

        $('#search-data-completion-icon').click(function(){
            $('#search-data-completion-input').val('');
            $('.data-completion-form-field').show();
        });

        $('#search-input').keyup(function(){
            var value = $(this).val();
            $('.form-field').show();
            if(value != ''){
                $('.form-field').show();
                var fields = $('.form-field');
                for(var i = 0; i < fields.length; i++){
                    var text = $(fields[i]).text();
                    var splittedText = text.split('(')[0];  // Get ride of field type and required text indicator
                    splittedText = splittedText.trim();
                    if(! splittedText.toUpperCase().includes(value.toUpperCase())){
                        $(fields[i]).hide();
                    }
                }   
            }
        });

        $('#search-data-completion-input').keyup(function(){
            var value = $(this).val();
            $('.data-completion-form-field').show();
            if(value != ''){
                $('.data-completion-form-field').show();
                var fields = $('.data-completion-form-field');
                for(var i = 0; i < fields.length; i++){
                    var text = $(fields[i]).text();
                    var splittedText = text.split('(')[0];  // Get ride of field type and required text indicator
                    splittedText = splittedText.trim();
                    if(! splittedText.toUpperCase().includes(value.toUpperCase())){
                        $(fields[i]).hide();
                    }
                }   
            }
        });

        // The disabled fields don't appear in submitted data, so we have to remove disabled attribute firstly
        // And we have to check if the user selected destination node
        $('form').on('beforeSubmit', function(){
            if($('input[name="Campaign[destinationNodeId]"]').val() == ''){
                alert('The owner node of the submitted data must be selected!');
                return false;
            }
            $('input[name*="DataCompletionFields"]:disabled').removeAttr('disabled');
            return true;
        });
    });

JS;

$this->registerJs($script);

?>

<div class="group-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    
    <?= $form->field($model, 'description')->textarea(['rows' => 6, 'style' => 'resize: none;']) ?>

    <div class="row">
        <div class="col-md-6">
            <?= $form->field($model, 'startDate', ['enableAjaxValidation' => true])->textInput(['type' => 'date']) ?>
        </div>

        <div class="col-md-6">
            <?= $form->field($model, 'endDate', ['enableAjaxValidation' => true])->textInput(['type' => 'date']) ?>
        </div>
    </div>

    <hr>

    <div class="form-group">
        <h3><?= 'Owner Node' ?></h3>
        <?= Html::label('Select the owner node of the submitted data', 'node') ?>

        <p>
            <?= Html::a('Display Nodes', [''],
                    [
                        'class' => 'tree-modal-button btn btn-primary btn-expanded',
                        'value' => Url::base(true) . '/nodes/show-tree-modal-for-campaign'
                    ])
            ?>
        </p>
        
        <?= Html::hiddenInput('Campaign[destinationNodeId]', $destinationNodeName, ['id' => 'selected-node-input']) ?>

        <h5 id='selected-node-section' style='display: <?= ($is_update ? 'block' : 'none') ?>; padding-top: 5px;'>
            <?= 'Selected node: ' ?><span class='text-warning' id='selected-node-span'><?= $destinationNodeName ?></span>
        </h5>

        <hr>

        <div class="form-group">
            <div style='margin-bottom: 10px;'>
                <label for=""><?= 'Campaign Form Fields' ?></label>
                <div class="input-group" style="display: inline-flex;">
                    <?= Html::textInput('search', '', ['id' => 'search-input', 'class' => 'form-control', 'aria-describedby' => 'search-icon', 'placeholder' => 'search..']) ?>
                    <span class="input-group-addon" id="search-icon" style="width: auto;"><span class="glyphicon glyphicon-remove" style="vertical-align: middle;"></span></span>
                </div>
            </div>
            
            <?php 
                foreach($fields as $field){
                    if($field['type'] != 'lookup'){
                        $label = $field['label'] . ' (' . $field['type'] . ')';
                        $is_required = $field['is_required'];
                        if($is_required){
                            $label .= ' <span class="text-danger">REQUIRED FIELD</span>';
                        }
                        echo '<div class="form-field">';
                        echo Html::checkbox('CampaignFields[' . $field['name'] . ']', true, ['label' => $label, 'id' => $field['name'], 'class' => ($is_required ? 'campaign-field-checkbox required-field' : 'campaign-field-checkbox')]);
                        echo '</div>';
                    }
                }
            ?>
        </div>

        <div class="form-group" style="border-top: 1px solid lightgrey; padding-top: 10px;">
            <div style='margin-bottom: 10px;'>
                <label for=""><?= 'Data Completion Fields' ?></label>
                <div class="input-group" style="display: inline-flex;">
                    <?= Html::textInput('search', '', ['id' => 'search-data-completion-input', 'class' => 'form-control', 'aria-describedby' => 'search-data-completion-icon', 'placeholder' => 'search..']) ?>
                    <span class="input-group-addon" id="search-data-completion-icon" style="width: auto;"><span class="glyphicon glyphicon-remove" style="vertical-align: middle;"></span></span>
                </div>
            </div>

            <div id="data-completion-fields">
                <?php 
                    foreach($fields as $field){
                        if($field['type'] == 'lookup'){
                            $label = $field['label'] . ' (' . $field['type'] . ')';
                            $is_required = $field['is_required'];
                            if($is_required){
                                $label .= ' <span class="text-danger">REQUIRED FIELD</span>';
                            }
                            echo '<div class="data-completion-form-field">';
                            echo Html::checkbox('DataCompletionFields[' . $field['name'] . ']', true, ['label' => $label, 'id' => $field['name'] . '_comp', 'class' => ($is_required ? 'completion-field-checkbox required-field' : 'completion-field-checkbox'), 'disabled' => $is_required]);
                            echo '</div>';
                        }
                    }
                ?>
            </div>
        </div>

    </div>

    <div class="center-elements">
        <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success btn-expanded', 'id' => 'submit-button']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

<?php 
    Modal::begin([
        'header' => '<h3>' . 'System Tree' . '</h3>',
        'id' => 'tree-modal',
        'size' => 'modal-lg',
        'closeButton' => false
    ]);

    echo '<div id="tree-modal-content"></div>';

    Modal::end();
?>