<?php

use \yii\helpers\Url;

$this->title = 'Update Form';
$base_url = json_encode(Url::base(true));

$this->registerCssFile('@web/css/jquery.rateyo.min.css');
$this->registerCssFile('@web/css/expression-builder.css');
$this->registerCssFile('https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css');
$this->registerCssFile('https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css');

$script =<<< JS

var baseUrl = $base_url;
var fields = $fields;
var matrixFields = $matrix_fields
var allForms = $all_forms;
var lookupFields = $lookup_fields;
var fieldsHaveBeenUsed = $fields_have_been_used;

$(document).ready(function(){
    
    $('body').css('background-color', '#FFF');
    $('body').css('background-image', 'none');

    setTimeout(() => {
        $('.build-wrap').formBuilder('setData', fields);
    }, 2000);
    
    setTimeout(() => {
        for(var matrixName in matrixFields){
            var fieldID = $('input[value="' + matrixName + '"]').closest('.form-field').prop('id');
            for(var i = 0; i < matrixFields[matrixName].length; i++){
                for(var fieldIndex in matrixFields[matrixName][i]){
                    var modalID = fieldID + '-index-' + fieldIndex;
                    var options = JSON.parse(matrixFields[matrixName][i][fieldIndex]);

                    var modal = `<div id="` + modalID + `-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h4 class="modal-title">Fill-out options</h4>
                                </div>
                            <div class="modal-body">
                            <ol class="sortable-options ui-sortable sortable-options" id="` + modalID + `-options" style="list-style: none; padding: 0">`;
                    
                    for(var j = 0; j < options.length; j++){
                        modal += `<li class="ui-sortable-handle" style="margin-bottom: 5px;">
                            <input required value="` + options[j]['value'] + `" type="text" class="form-control modal-option-label modal-input-fields" placeholder="label">
                            <input required value="` + options[j]['label'] + `" type="text" class="form-control modal-option-value modal-input-fields" placeholder="value">` 
                            + (j != 0 && j != 1 ? `<button class="btn icon-cancel delete-option-from-options-modal" style="width: 5%; padding: 0"></button>` : `<div style="width: 10%;"></div>`) + `
                        </li>`;
                    }

                    modal += `</ol>
                        <div style="text-align: end; margin-bottom: 10px;">
                            <button class="add-another-option add-option-to-options-modal-btn">Add Option</button>
                        </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-success save-modal-multiple-options">Save</button>
                        </div></div></div></div>`;
                        
                    $('#modals-container').append(modal);
                }
            }
        }

        var fieldsArray = JSON.parse(JSON.stringify(fields));
        var infoSpanStyle = 'style="margin-left: 10px; color: orange"';
        var omittedAttributeInfo = 'This attribute is omitted';

        for(var f = 0; f < fieldsArray.length; f++){
            var fieldName = fieldsArray[f]['name'];
            var fieldID = $('input[value="' + fieldName + '"]').closest('.form-field').prop('id');

            // Display the deactivation option
            $('#' + fieldID).find('.deactivate-wrap').show();

            // The form rendering doesn't include the fields labels on the top of the fields
            var fieldLabe = $('#' + fieldID).find('.field-label').html();
            $('#' + fieldID).find('.field-label').html($('#' + fieldID).find('.fld-label').html() + fieldLabe);

            // Options status (Active, Inactive)
            if(fieldsArray[f]['type'] == 'select' || fieldsArray[f]['type'] == 'checkbox-group' || fieldsArray[f]['type'] == 'radio-group'){
                var fieldOptions = fieldsArray[f]['values'];
                var listOptionsWrap = $('#' + fieldID).find('.field-options');
                var optionsStatuses = $(listOptionsWrap).find('.option-deactivate');
                for(var i = 0; i < optionsStatuses.length; i++){
                    $(optionsStatuses[i]).val(fieldOptions[i]['status']);
                }
            }

            // Related list
            if(fieldsArray[f]['relatedListCheckbox']){
                var parentListName = fieldsArray[f]['relatedListFieldName'];
                var fieldOptions = fieldsArray[f]['values'];
                
                $('#' + fieldID).find('input[name="related-list-checkbox"]').attr('checked', true);
                $('#' + fieldID).find('.related-list-logic').show();
                var parentListFieldID = $('input[value="' + parentListName + '"]').closest('.form-field').prop('id');
                $('#' + fieldID).find('select[name="related-list-field-name"]').val(parentListFieldID);
                var parentListOptionsWrap = $('#' + parentListFieldID ).find('.field-options');
                var parentListOptionsLabels = $(parentListOptionsWrap).find('.option-label');
                var parentListOptionsValues = $(parentListOptionsWrap).find('.option-value');

                var listOptionsWrap = $('#' + fieldID).find('.field-options');
                var optionsParents = $(listOptionsWrap).find('.option-parent');
                var optionsLabels = $(listOptionsWrap).find('.option-label');
                var optionsValues = $(listOptionsWrap).find('.option-value');
                var options = '';
                for(var i = 0; i < parentListOptionsLabels.length; i++){
                    var value = $(parentListOptionsValues[i]).val();
                    options += '<option value="' + value + '">' + $(parentListOptionsLabels[i]).val() + '</option>';
                }
                for(var i = 0; i < optionsValues.length; i++){
                    $(optionsValues[i]).css('width', 'auto');
                    $(optionsLabels[i]).css('width', 'auto');
                    $(optionsParents[i]).css('display', 'inline-block').css('width', '30%');
                    $(optionsParents[i]).append(options);
                    $(optionsParents[i]).show();
                    if(fieldOptions[i]['value'] == $(optionsValues[i]).val()){
                        $(optionsParents[i]).find('option[value="' + fieldOptions[i]['parent'] + '"]').attr('selected', true);
                    }
                }
                // To adjust the style of elements
                $('#' + fieldID).find('input[name="scoring"]').trigger('change');
                $('#' + fieldID).find('input[name="scoring"]').trigger('change');
            }

            // Show if
            if(fieldsArray[f]['showIfLogicCheckbox']){
                var showIfFieldName = fieldsArray[f]['showIfFieldName'];
                var showIfFieldValue = fieldsArray[f]['showIfFieldValue'];
                
                $('#' + fieldID).find('input[name="show-if-logic-checkbox"]').attr('checked', true);
                $('#' + fieldID).find('.show-if-logic').show();
                var showIfFieldID = $('input[value="' + showIfFieldName + '"]').closest('.form-field').prop('id');
                $('#' + fieldID).find('select[name="show-if-field-name"]').val(showIfFieldID);
                var showIfFieldOptionsWrap = $('#' + showIfFieldID).find('.field-options');
                var showIfFieldOptionsLabels = $(showIfFieldOptionsWrap).find('.option-label');
                var showIfFieldOptionsValues = $(showIfFieldOptionsWrap).find('.option-value'); 
                var options = '<option value="">Select value</option>';
                for(var i = 0; i < showIfFieldOptionsLabels.length; i++){
                    var value = $(showIfFieldOptionsValues[i]).val();
                    options += '<option ' + (value == showIfFieldValue ? 'selected' : '') + ' value="' + value + '">' + $(showIfFieldOptionsLabels[i]).val() + '</option>';
                }
                $('#' + fieldID).find('select[name="show-if-field-value"]').append(options);

                $('#' + fieldID).find('input[name="required"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="required-if-logic-checkbox"]').attr('disabled', true);

                if(fieldsArray[f]['showIfIsRequired']){
                    $('#' + fieldID).find('input[name="show-if-is-required"]').attr('checked', true);
                }
                
                var isHiddenAttribute = $('#' + fieldID).find('input[name="isHidden"]');
                $(isHiddenAttribute).attr('checked', true);
                $(isHiddenAttribute).attr('disabled', true);
                $(isHiddenAttribute).parent().append('<span ' + infoSpanStyle + '>(This attribute is selected automatically)</span>');
            }

            // Required if
            if(fieldsArray[f]['requiredIfLogicCheckbox']){
                var requiredIfFieldName = fieldsArray[f]['requiredIfFieldName'];
                var requiredIfFieldValue = fieldsArray[f]['requiredIfFieldValue'];
                
                $('#' + fieldID).find('input[name="required-if-logic-checkbox"]').attr('checked', true);
                $('#' + fieldID).find('.required-if-logic').show();
                var requiredIfFieldID = $('input[value="' + requiredIfFieldName + '"]').closest('.form-field').prop('id');
                $('#' + fieldID).find('select[name="required-if-field-name"]').val(requiredIfFieldID);
                var requiredIfFieldOptionsWrap = $('#' + requiredIfFieldID).find('.field-options');
                var requiredIfFieldOptionsLabels = $(requiredIfFieldOptionsWrap).find('.option-label');
                var requiredIfFieldOptionsValues = $(requiredIfFieldOptionsWrap).find('.option-value'); 
                var options = '<option value="">Select value</option>';
                for(var i = 0; i < requiredIfFieldOptionsLabels.length; i++){
                    var value = $(requiredIfFieldOptionsValues[i]).val();
                    options += '<option ' + (value == requiredIfFieldValue ? 'selected' : '') + ' value="' + value + '">' + $(requiredIfFieldOptionsLabels[i]).val() + '</option>';
                }
                $('#' + fieldID).find('select[name="required-if-field-value"]').append(options);

                var requiredAttribute = $('#' + fieldID).find('input[name="required"]');
                $(requiredAttribute).attr('disabled', true);
                $(requiredAttribute).parent().append('<span ' + infoSpanStyle + '>(' + omittedAttributeInfo + ')</span>');
                var isReadOnlyAttribute = $('#' + fieldID).find('input[name="isReadOnly"]');
                $(isReadOnlyAttribute).attr('disabled', true);
                $(isReadOnlyAttribute).parent().append('<span ' + infoSpanStyle + '>(' + omittedAttributeInfo + ')</span>');
            }

            if(fieldsArray[f]['scoring']){
                var listOptionsWrap = $('#' + fieldID).find('.field-options');
                var optionsScoring = $(listOptionsWrap).find('.option-scoring');
                var fieldOptions = fieldsArray[f]['values'];
                for(var i = 0; i < optionsScoring.length; i++){
                    $(optionsScoring[i]).val(fieldOptions[i]['score']);
                    $(optionsScoring[i]).show();
                }
                // To adjust the style of elements
                $('#' + fieldID).find('input[name="scoring"]').trigger('change');
                $('#' + fieldID).find('input[name="scoring"]').trigger('change');
            }

            // Required
            if(fieldsArray[f]['required']){
                var isReadOnlyAttribute = $('#' + fieldID).find('input[name="isReadOnly"]');
                $(isReadOnlyAttribute).attr('disabled', true);
                $(isReadOnlyAttribute).parent().append('<span ' + infoSpanStyle + '>(' + omittedAttributeInfo + ')</span>');
                $('#' + fieldID).find('input[name="required-if-logic-checkbox"]').attr('disabled', true);
            }

            // Expressions
            if(fieldsArray[f]['expressionsCheckbox']){
                var operator = fieldsArray[f]['operator'];
                var firstValue = fieldsArray[f]['expressionsValue'];
                var secondValue = operator == 'between' ? fieldsArray[f]['expressionsValue-2'] : '';
                $('#' + fieldID).find('input[name="expressions-checkbox"]').attr('checked', true);
                $('#' + fieldID).find('.available-expressions').show();
                $('#' + fieldID).find('select[name="operator"]').val(operator);
                $('#' + fieldID).find('input[name="expressions-value"]').val(firstValue);
                if(operator == 'between'){
                    $('#' + fieldID).find('input[name="expressions-value-2"]').val(secondValue);
                    $('#' + fieldID).find('.expression-between-second-val').show();
                }
            }

            // Read only
            if(fieldsArray[f]['isReadOnly']){
                $('#' + fieldID).find('input[name="required"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="isHidden"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="related-list-checkbox"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="show-if-logic-checkbox"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="required-if-logic-checkbox"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="expressions-checkbox"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="minlength"]').attr('disabled', true);
                $('#' + fieldID).find('input[name="maxlength"]').attr('disabled', true);
                $('#' + fieldID).find('.defaultValue-wrap').show();
            }

            // Min/Max selection count
            if(fieldsArray[f]['minMaxCheckbox']){
                var minSelection = fieldsArray[f]['checkboxMinValue'];
                var maxSelection = fieldsArray[f]['checkboxMaxValue'];
                $('#' + fieldID).find('input[name="min-max-checkbox"]').attr('checked', true);
                $('#' + fieldID).find('input[name="checkbox-min-value"]').val(minSelection);
                $('#' + fieldID).find('input[name="checkbox-max-value"]').val(maxSelection);
                $('#' + fieldID).find('.minMax-min-selections').show();
                $('#' + fieldID).find('.minMax-max-selections').show();
            }

            if(fieldsArray[f]['type'] == 'calculated'){
                var expression = fieldsArray[f]['labeledArithmeticExpression'];
                $('#' + fieldID).find('input[name="arithmeticExpression"]').val(expression);
                $('#' + fieldID).find('input[name="arithmeticExpression"]').expressionBuilder().isValid();
            }
            else if(fieldsArray[f]['type'] == 'id'){
                $('#' + fieldID).find('input[name="digitsCount"]').val(fieldsArray[f]['digitsCount']);
            }
            else if(fieldsArray[f]['type'] == 'matrix'){
                var fieldOptionsWrap = $('#' + fieldID).find('.field-options').find('li');
                for(var i = 0; i < fieldOptionsWrap.length; i++){
                    $(fieldOptionsWrap[i]).find('.option-field-name').val(fieldsArray[f]['values'][i]['fieldName']);
                }
                var maxRecordsCount = fieldsArray[f]['maxRecordsCount'];
                if(maxRecordsCount){
                    $('#' + fieldID).find('input[name="maxRecordsCount"]').val(maxRecordsCount);
                }
            }
            else if(fieldsArray[f]['type'] == 'lookup'){
                var formSelect = $('#' + fieldID).find('select[name="form"]');
                var referrenceSelect = $('#' + fieldID).find('select[name="referrence"]');
                var helperSelect = $('#' + fieldID).find('select[name="helper"]');
                var readOnlySelect = $('#' + fieldID).find('select[name="readOnly"]');

                var options = '<option value="">Select form</option>';
                for(var i = 0; i < allForms.length; i++){
                    options += '<option value="' + allForms[i]['id'] + '">' + allForms[i]['name'] + '</option>';
                }
                $(formSelect).append(options);
                $(formSelect).val(fieldsArray[f]['form']);

                var selectedFormFields = lookupFields[fieldsArray[f]['name']];
                var referrenceFields = selectedFormFields['reference_fields'];
                var readOnlyFields = selectedFormFields['read_only_fields'];

                var referrenceOptions = '<option value="">Select referrence field</option>';
                for(var i = 0; i < referrenceFields.length; i++){
                    referrenceOptions += '<option value="' + referrenceFields[i]['name'] + '">' + referrenceFields[i]['label'] + '</option>';
                }
                $(referrenceSelect).append(referrenceOptions);
                $(referrenceSelect).val(fieldsArray[f]['referrence']);

                var readOnlyOptions = '';
                for(var i = 0; i < readOnlyFields.length; i++){
                    readOnlyOptions += '<option value="' + readOnlyFields[i]['name'] + '">' + readOnlyFields[i]['label'] + '</option>';
                }
                $(readOnlySelect).append(readOnlyOptions);
                $(readOnlySelect).val(fieldsArray[f]['readOnly']);

                var helperOptions = '<option value="">Select helper field to ease search</option>' + readOnlyOptions;
                $(helperSelect).append(helperOptions);
                $(helperSelect).val(fieldsArray[f]['helper']);
            }

            // Check if field has been used before, then remove delete button
            if(fieldsHaveBeenUsed.includes(fieldsArray[f]['name'])){
                $('#' + fieldID).find('.field-actions a.del-button').remove();
            }
        }

        // Lookup field select2
        $('.select2').select2({
            theme: 'bootstrap4',
        });
        // In order to get selected items in the same line
        $('.select2-selection__rendered').css('display', 'inline-flex');

    }, 3000);
});

$('body').on('beforeSubmit', '#update-form', function(){

    $('#loader').show();

    try{
        // Trigger validation
        var validationResult = $('.save-template').trigger('click').data('validationResult');
        if(! validationResult){
            $('#loader').hide();
            return false;
        }

        var formData = $('.build-wrap').formBuilder('getData', 'json');

        // Check if form contains ID field and another field
        var decodedFields = JSON.parse(formData);
        var formContainsID = false;
        var formContainsAnotherField = false;
        for(var i = 0; i < decodedFields.length; i++){
            if(decodedFields[i]['type'] == 'id'){
                formContainsID = true;
            }
            else if(! ['matrix', 'logo', 'header', 'paragraph', 'file'].includes(decodedFields[i]['type'])){
                formContainsAnotherField = true;
            }

            if(formContainsID && formContainsAnotherField){
                break;
            }
        }

        if(! formContainsAnotherField && ! formContainsAnotherField){
            $('#loader').hide();
            alert('The form must contain an ID field and any other field except matrix, logo, header, paragraph and file');
            return false;
        }
        
        // Processing fields by replacing field-id with field name
        var parsedFormData = JSON.parse(formData);
        for(var i = 0; i < parsedFormData.length; i++){
            if(parsedFormData[i]['type'] == 'calculated'){
                var arithmeticExpression = $('input[value="' + parsedFormData[i]['name'] + '"]').closest('.form-field').find('input[name="arithmeticExpression"]');
                var expression = $(arithmeticExpression).expressionBuilder().getExpression();
                parsedFormData[i]['arithmeticExpression'] = expression;
            }

            if(parsedFormData[i]['relatedListCheckbox']){
                parsedFormData[i]['relatedListFieldName'] = $('li#' + parsedFormData[i]['relatedListFieldName']).find('input[name="name"]').val();
            }
            if(parsedFormData[i]['showIfLogicCheckbox']){
                parsedFormData[i]['showIfFieldName'] = $('li#' + parsedFormData[i]['showIfFieldName']).find('input[name="name"]').val();
            }
            if(parsedFormData[i]['requiredIfLogicCheckbox']){
                parsedFormData[i]['requiredIfFieldName'] = $('li#' + parsedFormData[i]['requiredIfFieldName']).find('input[name="name"]').val();
            }
        }

        $('#form-data').val(JSON.stringify(parsedFormData));

        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: {
                form_name: $('#form_name').val(),
                form_type: $('input[name="form_type"]:checked').val(),
                form_direction: $('input[name="form_direction"]:checked').val(),
                formData: $('#form-data').val(),
            },
            success: function (response) {
                console.log(response);
                var data = JSON.parse(response);
                if(data['status']){
                    window.location.href = baseUrl + '/forms/index';
                }
                else{
                    alert('Could not save the form!');
                }
                $('#loader').hide();
            },
            error: function(error){
                console.log(error);
                $('#loader').hide();
            }
        });
        return false;
    }
    catch(err){
        $('#loader').hide();
        alert(err);
        return false;
    }
});

JS;

$this->registerJs($script);

?>

<div class="content">

    <h1><?= $this->title ?></h1>

    <div id="modals-container"></div>

    <?= $this->render('_form-fields', [
        'form_options' => [
            'options' => [
                'id' => 'update-form'
            ]
        ],
        'form_name' => $model['name'],
        'form_direction' => $model['directionality'],
        'form_type' => $model['type']
    ]) ?>

</div>


<?php 

$this->registerJsFile('@web/js/vendor.js');
$this->registerJsFile('@web/js/form-builder.min.js');
$this->registerJsFile('@web/js/demo.min.js');
$this->registerJsFile('@web/js/jqueryExpressions.js');
$this->registerJsFile('@web/js/jquery.rateyo.min.js');
$this->registerJsFile('@web/js/query-builder.standalone.js');
$this->registerJsFile('https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js');

?>
