
<div class="row mb-3">
    <div class="col-sm-12">
        <div id="questions-container"></div>
        <button type="button" class="btn btn-sm btn-primary text-white mt-3" id="btn-add-section">
            <i class="fa fa-plus"></i> Add Section
        </button>
    </div>
</div>


<script>
    let accordions = [];
    let empty_question = {
        "question_id" : "",
        "question_type" : "",
        "question_family" : "",
        "question_level" : "",
        "validation_rules" : [],
        "tags" : [],
        "content" : "",
        "note" : "",
        "possible_score" : "",
        "active" : "",
        "allow_null" : "",
        "readonly" : "",
        "true_label" : "",
        "false_label" : "",
        "null_label" : "",
        "removed" : false,
    };

    let empty_category = {
        "category_id" : "",
        "category_name" : "Default Category",
        "removed" : false,
        "questions" : [
            JSON.parse(JSON.stringify(empty_question))
        ],
        "accordion_state" : "open",
    }

    var questions_data = JSON.parse('{{str_replace('\"', '',json_encode($questionData))}}'.replace(/&quot;/g,'"'));

    function buildQuestionsView(){
        let innerContent = '';
        for (let i=0; i<questions_data.length; i++){
            let e = questions_data [i];
            if (!e['removed']) {
                innerContent += '<div  class="question-accordion mb-3">' +
                    '<div class="mb-3 '+e['accordion_state']+'">' +
                    '<h3 data-index="'+i+'" class="acc-header"><span class="title-text">'+e['section_name']+'</span><i class="indicator float-right la"></i> <span data-index="'+i+'" class="float-right btn-delete-item text-black btn-danger  btn btn-sm mr-2">Remove</span></h3>' +
                    '<div class="acc-body">' +
                    '<label>Section name</label> <input required class="form-control section-name mb-2" value="'+e['section_name']+'" placeholder="Section name" data-section="'+i+'" type="text" >';

                for (let j=0; j<e['categories'].length; j++){
                    let c  = e['categories'][j];
                    if (!c['removed']) {
                        innerContent += '<div  class="question-accordion mb-3">'+
                            '<div class="mb-3 '+c['accordion_state']+'">' +
                            '<h3 data-index="'+i+'_'+j+'" class="acc-header"><span class="title-text">'+c['category_name']+'</span><i class="indicator float-right la"></i> <span data-index="'+i+'_'+j+'" class="float-right btn-delete-item text-black btn-danger btn btn-sm mr-2">Remove</span></h3>' +
                            '<div class="acc-body">' +
                            '<label>Category name</label> <input required class="form-control category-name mb-2" value="'+c['category_name']+'" placeholder="Category name" data-category="'+i+'_'+j+'" type="text" >';


                        for (let k=0; k<c['questions'].length; k++){
                            let q = c['questions'][k];
                            if (!q['removed']) {
                                innerContent += '<div class="question-form">'+questionFrom(q, i, j, k)+'</div>';
                            }
                        }

                        innerContent += '<button data-category="'+i+'_'+j+'" type="button" class="btn btn-sm btn-info text-white mt-3 btn-add-question">' +
                            '<i class="fa fa-plus"></i> Add Question' +
                            '</button>'+
                            '</div>' +
                            '</div>' +
                            '</div>'
                    }
                }

                innerContent += '<button data-section="'+i+'" type="button" class="btn btn-sm btn-purple text-white mt-3 btn-add-category">' +
                    '<i class="fa fa-plus"></i> Add Category' +
                    '</button>'+
                    '</div>' +
                    '</div>' +
                    '</div>'
            }
        }

        $('#questions-container').html(innerContent);

        accordions = [];
        $('.question-accordion').each(function () {
            var acc = new Accordion(this, {
                open : true,
                onToggle: function(fold, isOpen){
                    //console.log(fold);   // -> Reference to a `Fold` instance
                    //console.log(isOpen); // -> true / false
                    if(isOpen){
                        //$(this).find('i').attr('class', 'la la-chevron-circle-down')
                    }
                }
            });
            accordions.push(acc);
        });

        $('.select2').each(function () {
            $(this).select2({
                dropdownParent: $(this).parent(),
            });
        });

        $('.question-type').change();
    }

    $(document).on('click','#btn-add-section',function (e) {
        let section = {
            "section_id" : "",
            "section_name" : "Default section",
            "removed" : false,
            "categories" : [
                JSON.parse(JSON.stringify(empty_category))
            ],
            "accordion_state" : "open",
        };
        questions_data.push(section)
        buildQuestionsView();
    });

    $(document).on('click','.btn-add-category',function (e) {
        let section_index = $(this).data('section')
        questions_data[section_index]['categories'].push( { ...empty_category });
        buildQuestionsView();
    });

    $(document).on('click','.btn-add-question',function (e) {
        let indexes = $(this).data('category').split('_');
        let section_index = indexes[0];
        let category_index = indexes[1];
        questions_data[section_index]['categories'][category_index]['questions'].push({ ...empty_question });
        buildQuestionsView();
    });

    $(document).on('keyup','.section-name',function (e) {
        let section_index = $(this).data('section')
        questions_data[section_index]['section_name'] = $(this).val();
        $('.acc-header[data-index='+section_index+'] .title-text').html($(this).val())
    });

    $(document).on('keyup','.category-name',function (e) {
        let indexes = $(this).data('category').split('_');
        let section_index = indexes[0];
        let category_index = indexes[1];
        questions_data[section_index]['categories'][category_index]['category_name'] = $(this).val();
        $('.acc-header[data-index='+section_index+'_'+category_index+'] .title-text').html($(this).val())
    });

    $(document).on('click','.acc-header',function (e) {
        let indexes = $(this).data('index').toString().split('_');
        if(indexes[1] !== undefined) {
            if( questions_data[indexes[0]]['categories'][indexes[1]]['accordion_state'] === 'open' ){
                questions_data[indexes[0]]['categories'][indexes[1]]['accordion_state'] = 'closed';
            } else {
                questions_data[indexes[0]]['categories'][indexes[1]]['accordion_state'] = 'open';
            }
        } else {
            //$(this).parent().removeClass('open');
            //$(this).parent().removeClass('closed');
            if(questions_data[indexes[0]]['accordion_state'] === 'open' ){
                questions_data[indexes[0]]['accordion_state'] = 'closed';
            } else  {
                questions_data[indexes[0]]['accordion_state'] = 'open';
            }
        }
    });

    $(document).on('click','.btn-delete-item',function (e) {
        let indexes = $(this).data('index').toString().split('_');
        if(indexes[2] !== undefined) {
            questions_data[indexes[0]]['categories'][indexes[1]]['questions'][indexes[2]]['removed'] = true;
        } else {
            if(indexes[1] !== undefined) {
                questions_data[indexes[0]]['categories'][indexes[1]]['removed'] = true;
            } else {
                questions_data[indexes[0]]['removed'] =  true;
            }
        }
        buildQuestionsView();
    });

    $(document).on('change','.question-type',function (e) {
        let question_index = $(this).data('question');
        let indexes = question_index.toString().split('_');
        let ruleInput = $('.question-rules[data-question='+question_index+']');
        ruleInput.find('option').remove();
        let question = questions_data[indexes[0]]['categories'][indexes[1]]['questions'][indexes[2]];
        @foreach($validation_rules as $v)
            if({{$v->question_type_id}} == $(this).val()){
                var selected = question['validation_rules'].map(String).includes('{{$v->id}}')? 'selected' : '';
                ruleInput.append('<option '+selected+' class="question-rules-options" data-question_type="{{$v->question_type_id}}" value="{{$v->id}}">{{$v->name}}</option>');
            }
        @endforeach

        if(['radio'].includes($(this).find(':selected').data('name'))){
            $('.question-true_label[data-question='+question_index+']').parent().show();
            $('.question-false_label[data-question='+question_index+']').parent().show();
            $('.question-null_label[data-question='+question_index+']').parent().show();
        } else {
            $('.question-true_label[data-question='+question_index+']').parent().hide();
            $('.question-false_label[data-question='+question_index+']').parent().hide();
            $('.question-null_label[data-question='+question_index+']').parent().hide();
        }
    });

    //mouseout
    $(document).on('change','.question-form .form-control',function (e) {
        let indexes = $(this).data('question').toString().split('_');
        let target = $(this).data('target');
        questions_data[indexes[0]]['categories'][indexes[1]]['questions'][indexes[2]][target] = $(this).val();
    })

    function getYesOrNoInput(name, target, value, question_index){
        let input = '<select class="form-control mb-2 '+name+'" data-target="'+target+'" data-question="'+question_index+'" ><option value="">*Choose</option>';
        @foreach($yesOrNo as $e)
            var selected = value == '{{$e}}' ? 'selected' : '';
            input +='<option '+selected+' value="{{$e}}">{{$e}}</option>';
        @endforeach
        input += '</select>';

        return input;
    }

    function questionFrom(question, s, c, q){
        let question_type_input = '<select required class="form-control mb-2 question-type" data-target="question_type" data-question="'+s+'_'+c+'_'+q+'" ><option value="">*Choose</option>';
            @foreach($questionTypes as $t)
                var selected = question['question_type'] == {{$t->id}}? 'selected' : '';
                question_type_input +='<option '+selected+' data-name="{{$t->name}}" value="{{$t->id}}">{{$t->label}}</option>';
            @endforeach
        question_type_input += '</select>';

        let tag_input = '<select data-placeholder="Choose..." class="question-tags form-control  select2" multiple="multiple" data-target="tags" data-question="'+s+'_'+c+'_'+q+'" >';
            @foreach($tags as $k => $v)
                var selected = question['tags'].map(String).includes('{{$k}}')? 'selected' : '';
                tag_input +='<option '+selected+' value="{{$k}}">{{$v}}</option>';
            @endforeach
        tag_input += '</select>';

        let question_family_input = '<select required class="form-control mb-2 question-family" data-target="question_family" data-question="'+s+'_'+c+'_'+q+'" ><option value="">*Choose</option>';
            @foreach($questionFamilies as $t)
                var selected = question['question_family'] == {{$t->id}}? 'selected' : '';
                question_family_input +='<option '+selected+' data-name="{{$t->code}}" value="{{$t->id}}">{{$t->label}}</option>';
            @endforeach
        question_family_input += '</select>';

        let question_level_input = '<select class="form-control mb-2 question-level" data-target="question_level" data-question="'+s+'_'+c+'_'+q+'" ><option value="">*Choose</option>';
            @foreach($questionLevels as $t)
                var selected = question['question_level'] == {{$t->id}}? 'selected' : '';
                question_level_input +='<option '+selected+' data-name="{{$t->sequence}}" value="{{$t->id}}">{{$t->name}}</option>';
            @endforeach
        question_level_input += '</select>';

        let rules_input = '<select  data-placeholder="Choose..." class="question-rules form-control select2" multiple="multiple" data-target="validation_rules" data-question="'+s+'_'+c+'_'+q+'" ></select>';

        let html = '<div class="row">';
        html += '<div class="col-sm-12"><button data-index="'+s+'_'+c+'_'+q+'" class="float-right btn-delete-item text-black btn-danger btn btn-sm mr-2" style="">Remove</button></div>';
        html += '<div class="col-sm-12"><label>Question type</label> '+question_type_input+'</div>';
        html += '<div class="col-sm-12"><div class="row">'
        html += '<div class="col-sm-12"><label>Question content</label> <input data-target="content" required class="form-control question-content mb-2" value="'+question['content']+'" placeholder="Question content" data-question="'+s+'_'+c+'_'+q+'" type="text" ></div>';
        html += '<div class="col-sm-4"><label>Possible score</label> <input data-target="possible_score" required class="form-control question-score mb-2" value="'+question['possible_score']+'" placeholder="Possible score" data-question="'+s+'_'+c+'_'+q+'" type="number" ></div>';
        html += '<div class="col-sm-4"><label>Family</label> '+question_family_input+'</div>';
        html += '<div class="col-sm-4"><label>Level</label> '+question_level_input+'</div>';

        html += '<div class="col-sm-12 mb-2"><label>Validations rules</label> '+rules_input+'</div>';

        html += '<div class="col-sm-2"><label>Active</label> '+getYesOrNoInput('active', 'active', question['active'], s+'_'+c+'_'+q)+'</div>';
        html += '<div class="col-sm-2"><label>Allow empty</label> '+getYesOrNoInput('allow_null', 'allow_null', question['allow_null'], s+'_'+c+'_'+q)+'</div>';
        html += '<div class="col-sm-2"><label>Read only</label> '+getYesOrNoInput('readonly', 'readonly' , question['readonly'], s+'_'+c+'_'+q)+'</div>';

        html += '<div class="col-sm-2" style="display: none"><label>True label</label> <input data-target="true_label"  class="form-control question-true_label mb-2" value="'+question['true_label']+'" placeholder="Yes" data-question="'+s+'_'+c+'_'+q+'" type="text" ></div>';
        html += '<div class="col-sm-2" style="display: none"><label>False label</label> <input data-target="false_label"  class="form-control question-false_label mb-2" value="'+question['false_label']+'" placeholder="No" data-question="'+s+'_'+c+'_'+q+'" type="text" ></div>';
        html += '<div class="col-sm-2" style="display: none"><label>Null label</label> <input data-target="null_label"  class="form-control question-null_label mb-2" value="'+question['null_label']+'" placeholder="N/A" data-question="'+s+'_'+c+'_'+q+'" type="text" ></div>';

        html += '</div></div></div>';

        return html;
    }

    buildQuestionsView();
</script>
