
<div class="modal fade" id="add-edit-checklist-modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('add_checklist'); ?></h5>
                <h5 class="edit-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('edit_checklist'); ?></h5>
            </div>
            <div class="modal-body">
                <form id="checklist_form" method="POST" onsubmit="return false">
                    <div id='aa'>
                    </div>
                    <input type='hidden' name='checklist_id' id='checklist_id'/>
                    <div class="row">
                        <?php echo Forms::AlertDiv('checklist_alert'); ?>
                    </div>
                    <div class="row  m-t-10">
                        <div class="col-md-4 form-group">
                            <label><?php print CommonLanguage::getMessage('checklist_name'); ?></label>
                            <span class="red-star">*</span>
                            <input class="form-control" id="checklist_name" name="checklist_name" type="text" required />
                        </div>
                        <div class="col-md-6 form-group">
                            <label><?php print CommonLanguage::getMessage('checklist_description'); ?></label>
                            <span class="red-star">*</span>
                            <input class="form-control" id="checklist_description" name="checklist_description"  type="text" required />
                        </div>
                    </div> 
                    <div class="row m-t-10">
                        <h3 class="semi-bold"><?php print CommonLanguage::getMessage('questions'); ?></h3>
                        <div class="col-md-12 questions_div">
                            <div class="col-md-12">
                                <div class="col-md-4">
                                    <label><?php echo CommonLanguage::getMessage('question_title') ?></label>
                                </div>
                                <div class="col-md-3">
                                    <label><?php echo CommonLanguage::getMessage('question_type') ?></label>
                                </div>
                                <div class="col-md-4">
                                    <label><?php echo CommonLanguage::getMessage('question_value') ?></label>
                                </div>
                            </div>
                            <div class="row add-row m-t-10" data-index="0">
                                <div class="col-md-12">
                                    <div class="col-md-4">
                                        <input type="text" name="question_name"  class="full-width form-control question_name" >
                                    </div>
                                    <div class="col-md-3">
                                        <input type="hidden" name="question_type"  class="full-width" >
                                    </div>
                                    <div class="col-md-4 question_value_div">
                                    </div>
                                    <div class="col-md-1 buttons">
                                        <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px;cursor:pointer;"></span>
                                        <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;cursor:pointer;"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button style="color:white !important;"  class="btn bg-success-dark text-white" id="submit_checklist"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('checklistLoader'); ?>
        </div>
    </div>
</div>
<script>
    var is_pop_modal = '<?php echo !empty($_GET['open_modal']) ? true :false;?>';
    $(function(){
      
        $('#submit_checklist').on('click',function(){
            if (!$("#checklist_form").valid())
                return;
            var Data = new FormData(document.getElementById("checklist_form")),
                checklist_questions =[],
                is_question_empty = false,is_question_type=false,
                is_range_empty = false,is_from_greater_to=false,
                is_option_empty = false,
                is_default_empty = false,
                is_default_range = false;
            $('.add-row').each(function(){
                var parent = $(this),question_type= $('input[name=question_type]',$(this)).val(),
                    question_value='',default_answer='';
                if(!$('input[name=question_name]',$(this)).val())
                    is_question_empty = true;
                if(!question_type)
                    is_question_type = true;
                if(question_type <= 2 || question_type == 4){
                    if(question_type == 1 ){
                        if($('input.yes_no:checked',parent).length == 0)
                            is_default_empty = true;
                        else
                            default_answer = $('input.yes_no:checked',parent).val(); 
                    }else if(question_type == 2){
                        if(!$('input[name="question_number"]',parent).val())
                            is_default_empty = true;
                        else
                            default_answer = $('input[name="question_number"]',parent).val(); 
                    }else{
                        if(!$('input[name="question_text"]',parent).val())
                            is_default_empty = true;
                        else
                            default_answer = $('input[name="question_text"]',parent).val(); 
                    }
                    question_value = '';
                }else if(question_type  == 3){
                    var from =$('input[name=range_from]',parent).val() ,to=$('input[name=range_to]',parent).val(),
                        default_value =  $('input[name="default_range_value"]',parent).val();
                    if(!from || !to)
                        is_range_empty = true;
                    if(parseFloat(from) > parseFloat(to))
                        is_from_greater_to = true;
                    question_value = from+','+to;
                    if(!default_value)
                        is_default_empty = true;
                    if(parseFloat(default_value) > parseFloat(to) || parseFloat(default_value) < parseFloat(from)) 
                        is_default_range = true;
                    default_answer = default_value;
                }else{
                    question_value = $('input[name=question_options]',$(this)).val();
                    if(!$('input[name=question_options]',$(this)).val())
                        is_option_empty = true;
                    if(!$('select[name=question_default_select]',$(this)).val())
                        is_default_empty = true;
                    default_answer = $('select[name=question_default_select]',$(this)).val();
                }
                checklist_questions.push({
                    question_name:$('input[name=question_name]',$(this)).val(),
                    question_type:question_type,
                    question_value:question_value,
                    default_answer: default_answer
                });
            });
            if(is_question_empty){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_question_title');?>', 'danger');
                return;
            }
            if(is_question_type){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_question_type');?>', 'danger');
                return;
            }
            if(is_range_empty){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_range');?>', 'danger');
                return;
            }
            if(is_from_greater_to){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_from_greater_to');?>', 'danger');
                return;
            }
            if(is_option_empty){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_option');?>', 'danger');
                return;
            }
            if(is_default_empty){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_default_answer');?>', 'danger');
                return;
            }
            if(is_default_range){
                AddAlert("#checklist_alert",'<?php echo CommonLanguage::getMessage('alert_default_range');?>', 'danger');
                return;
            }
            Data.append('checklist_questions',JSON.stringify(checklist_questions));
            $("#checklistLoader").removeClass('hidden');
            $.ajax({
                url: "MaintenanceAjax/submitChecklist",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            hideModalAlert('add-edit-checklist-modal', 'checklist_alert');
                            RebuildDataTable($('.panel-heading .panel-title').html(), [0,1], 'MaintenanceAjax/getChecklist');
                        }
                        AddAlert("#checklist_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#checklistLoader").addClass('hidden');
                }
            });
        });
        build_select2($("input[name=question_type]"),"xhr/CommonSearch?col_name=type_name&col_id=type_id&table=tbl_question_types");
        $("#new_checklist").on("click", function () {
            $("#checklist_id").val(0);
            $("#add-edit-checklist-modal .add-label").removeClass('hidden');
        });
        if(is_pop_modal)
            $('#new_checklist').trigger('click');
        $("#tableWithSearch").on("click", ".edit_checklist",function () {
            var checklist_id = $(this).parents('div.Action').attr('data-id');
            $("#checklist_id").val(checklist_id);
            $("#add-edit-checklist-modal .edit-label").removeClass('hidden');
            CommonViewById('MaintenanceAjax/getChecklistData', {checklist_id: checklist_id},
                           '#checklistLoader', function (response) {
                var main = response['main'],details = response['details'],
                    current_row = $(".questions_div .add-row:eq(0)").clone()

                $('#checklist_name').val(main.checklist_name)
                $('#checklist_description').val(main.checklist_description);
                $(".questions_div .add-row").remove();
                $.each(details,function(index,value){
                    current_row = current_row == null ? $(".questions_div .add-row:eq(0)").clone() : current_row;
                    $('input[name=question_name]',current_row).val(details[index].question_name);
                     var content = getQuestionValueHtml(details[index].answer_type_id,details[index].answer_type_value,index,details[index].default_answer)
                    $('.question_value_div',current_row).html($(content))
                    $(".questions_div").append(current_row);
                    $(".select2-container",current_row).remove();
                    $("input[name=question_type]",current_row).val(details[index].answer_type_id);
                    $("input[name=question_type]",current_row).attr("data-select-name", details[index].type_name);
                    build_select2($("input[name=question_type]"),"xhr/CommonSearch?col_name=type_name&col_id=type_id&table=tbl_question_types");
                   
                    if(details[index].answer_type_id >= 5){
                        $('.tagsinput',current_row).tagsinput()
                        $('select[name=question_default_select]',current_row).select2();
                        enableTagEventAdd($('.tagsinput',current_row),current_row,details[index].answer_type_id,details[index].default_answer)
                    }
                    if(details[index].answer_type_id == "1"){
                        $('input[name=yes_no'+index+'][value='+details[index].default_answer+']',current_row).prop('checked',true)

                    }
                    $(".select2-container",current_row).show();
                    current_row = null
                    $(".add-row").each(function () {
                        $(" .fa-minus-circle", $(this).parents('.questions_div')).css({"display": $(".add-row", $(this).parents('.questions_div')).length <= 1 ? "none" : "inline-block"})
                    });
                }); 
            });
        });
        $(".questions_div").on("click", " .fa-plus-circle", function (e) {
            $(".add-row  .fa-minus-circle").css("display", "inline-block");
            var Parent = $(this).parents(".add-row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find(".question_name").val('');
            NewItem.find(".select2-container").remove();
            NewItem.find(".question_value_div").empty();
            NewItem.find("input[name=question_type]").val('').attr("data-select-name", "");
            build_select2($("input[name=question_type]",NewItem),"xhr/CommonSearch?col_name=type_name&col_id=type_id&table=tbl_question_types");
            $(".select2-container", NewItem).show();
        });
        $('.questions_div').on("change","input[name=question_type]",function(){
            var parent = $(this).parents(".add-row"),question_type= $(this).val();
            if($(this).val()){
                var content = getQuestionValueHtml(question_type,'',parent.index());
                parent.find('.question_value_div').html($(content))
                if(question_type >= 5){
                    $('.tagsinput',parent).tagsinput() 
                    $('select[name=question_default_select]',parent).select2();
                    enableTagEventAdd($('.tagsinput',parent),parent,question_type,'')
                }
            }else{
                parent.find('.question_value_div').empty() 
            }
        });
        $(".questions_div").on("click", ".fa-minus-circle", function (e) {
            if ($(".add-row").length != 1) 
                $(this).closest(".add-row").empty().remove();
        });

    });
    function enableTagEventAdd(input,parent,question_type,default_value){
        input.on('itemAdded', function(event) {
            var select_options = input.tagsinput('items'),options='';
            $('select[name=question_default_select]',parent).empty()
            $.each(select_options,function(i){
                options += '<option value="'+select_options[i]+'">'+select_options[i]+'</option>';
            });
            $('select[name=question_default_select]',parent).append($(options))
        });
        input.on('itemRemoved', function(event) {
            var select_options = input.tagsinput('items'),options='';
            $('select[name=question_default_select]',parent).empty()
            $('select[name=question_default_select]',parent).val('').select2()
            $.each(select_options,function(i){
                options += '<option value="'+select_options[i]+'">'+select_options[i]+'</option>';
            });
            $('select[name=question_default_select]',parent).append($(options))
        });
        var select_options = input.tagsinput('items'),options='';
        $('select[name=question_default_select]',parent).empty()
        $.each(select_options,function(i){
            options += '<option value="'+select_options[i]+'">'+select_options[i]+'</option>';
        });
        $('select[name=question_default_select]',parent).append($(options));
        default_value ? $('select[name=question_default_select]',parent).val(question_type == 5 ? default_value : default_value.split(',')).select2() : '';
    }
    function getQuestionValueHtml(question_type,value,index,default_value){
        var content = '';
        if(question_type ==  1){
            content = '<div class="radio radio-success-dark "><input type="radio" class="yes_no" value="1"  id="yes'+index+'"  name="yes_no'+index+'" ><label for="yes'+index+'">Yes</label><input type="radio"  class="yes_no" value="2" name="yes_no'+index+'" id="no'+index+'" ><label for="no'+index+'">No</label></div>'
        }else if(question_type == 2){
            content = '<input type="number" placeholder="Number" name="question_number" value="'+(default_value ? default_value : '' )+'"   class="form-control">'
        }else if(question_type == 3){
            var range_from_to = value.split(",");
            content = '<div class="display-flex"><input type="number" value="'+(value != '' ? range_from_to[0] : '')+'" placeholder="From"  name="range_from"   class="form-control"><input type="number" placeholder="Range To" value="'+(value != '' ? range_from_to[1] : '')+'" name="range_to"   class="form-control"><input type="number" placeholder="Default Value"  name="default_range_value" value="'+(default_value ? default_value : '' )+'" class="form-control"></div>'
        }else if(question_type == 4){
            content = '<input type="text" placeholder="Text" name="question_text" value="'+(default_value ? default_value : '' )+'" class="form-control">'
        }else{
            content = '<div class="display-flex"><input  type="hidden"  name="question_options"  value="'+(value != '' ? value : '')+'"   class="form-control tagsinput" /><select name="question_default_select" class="full-width  criteria_type" data-init-plugin="select2" '+(question_type == 5 ? '' : 'multiple')+'></select></div>'
        }
        return content;
    }
</script>