@extends('template')

@section('page-title') {{$questionSet->title}} @endsection

@section('tag-title') Process @endsection

@section('page-sub-title')

@endsection

@section('main-content')

    <?php
        $user_locationIds = Auth::user()->locations->pluck('id')->toArray();
        $locations = DB::table('locations')->whereIn('id', $user_locationIds)->where('department_id', $questionSet->department_id)->get();

        $currentLocationId = null;
        $responsable_person = ' ';
        if(!empty($questionSetJob)){
            $currentLocationId = $questionSetJob->location_id;
            //$responsable_person = $questionSetJob->responsable_person;
        }
    ?>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="mg-b-20 row">
                        <div class="col-sm-12">
                            <div class="form-group">
                                <!--label for="responsable_person" class="control-label">Enter the name of responble  person<span style="color: red">*</span></label>
                                <input id="responsable_person" type="text" required name="responsable_person" value="{{$responsable_person}}" class="form-control mb-5"-->
                                <label for="location_id" class="control-label">Choose the location to complete checklist<span style="color: red">*</span></label>
                                <select required id="location_id" name="location_id" class="form-control select2">
                                    <option value="">*Choose</option>
                                    @foreach($locations as $item)
                                        <option  @if($item->id == $currentLocationId) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                    </div>
                   
                    <div id="questions-containers">

                    </div>
                    
                </div>
            </div>
        </div>
    </div>

@endsection

@section('page-style')

    <style>
        #question-wizard ul .title{
            width: 100%;
        }

        label{
            font-weight: bold;
            margin-bottom: 3px;
        }

        .card-header{
            padding: 7px 10px;
            border-top-left-radius: 3px !important;
            border-top-right-radius: 3px !important;
            background-color: #f0f6ff;
            color: #0a0a0a;
        }

        .card-body{
            padding: 7px 10px;
            border-bottom-left-radius: 3px !important;
            border-bottom-right-radius: 3px !important;
        }

        .wizard.vertical > .content{
            padding: 7px;
        }

        .wizard.vertical > .steps{
            padding: 10px;
        }
        .wizard > .content > .title{
            margin-bottom: 10px;
        }

        .question-content{
            font-size: 13px;
            font-weight: bold;
        }

        .question-note{
            font-style: italic;
            color: #8e8e8e;
        }

        .question-footer{

        }

        .select2-container--default.select2-container--focus .select2-selection--multiple, .select2-container--default .select2-selection--single,
        .select2-container--default .select2-selection--multiple{
            min-height: 35px;
            border-radius: 3px;
            height: 35px;
        }

        .radiobtns .btn-group > .btn:not(:disabled):not(.disabled){
            padding: 5px 15px !important;
        }
    </style>
@endsection

@section('page-script')
    <script src="{{url('assets/plugins/jquery-steps/jquery.steps.min.js')}}"></script>
    <script src="{{url('assets/plugins/parsleyjs/parsley.min.js')}}"></script>

    <script>

        function refreshQuestionData(){
            $('#global-loader').show();
            var req = $.ajax({
                url: '{{url(config('app.admin_prefix').'/refresh-question-data-to-process')}}',
                type: "GET",
                data: {question_set_id: '{{$questionSet->id}}', location_id : $('#location_id').val()},
                dataType: "html"
            });
            req.done(function (response, textStatus, jqXHR) {
                $('#questions-containers').html(response);
                $('#global-loader').hide();
            });
            req.fail(function (jqXHR, textStatus) {
                $('#global-loader').hide();
                swal("Erreur!", "Error during get data. Please refresh page", "warning");
            });
        }
        
         $(document).on('change', '#location_id', function () {
            refreshQuestionData();
        });

        /*$(document).on('change', '#location_id', function () {
            if ($(this).val().trim() !== '') {
                if ($('#responsable_person').val().trim() === '') {
                    swal("Erreur!", "Please enter the name of the responsible person!", "warning");
                    return;
                }
                refreshQuestionData();
            }
        });*/

        $('#location_id').change();


        $(document).on('submit','.form-step-section',function (e) {
            e.preventDefault();
        });

        function submitSectionForm(index){
            let currentForm = $('#section_'+index);
            let result = true
            let req = $.ajax({
                url: currentForm.attr('action'),
                type: currentForm.attr('method'),
                data: new FormData(document.getElementById('section_'+index)),
                dataType: "json",
                async : false,
                contentType: false,
                processData: false,
            });
            req.done(function (response, textStatus, jqXHR) {
                result = response.success;
                printMessage(response.message, response.success? 'success' : 'warning', 'center');
                if(currentForm.data('last') == 1){
                   setTimeout(() => {
                        window.location = response.redirectTo;
                   }, 2000)
                }
            });
            req.fail(function (jqXHR, textStatus) {
                let response = JSON.parse(jqXHR.responseText)
                result = false;
                swal("Error!", response.message, "warning");
            });
            return result;
        }

        $(document).on('change','.question-answerer',function (e) {
            let value = $(this).val();
            let question_id = $(this).data('id');
            let category_id = $(this).data('category');
            let section_id = $(this).data('section');
            let possibleScore = $(this).data('score');

            let strategies = JSON.parse(JSON.stringify($(this).data('strategy')));

            strategies.forEach(function(value, index) {
                this[index] = JSON.parse(value)
            }, strategies);

            let requiredShower = $('#question_required_'+question_id);
            let requiredInput = $('#question_is_required_'+question_id);

            let requiredCommentShower = $('#question_required_comment_'+question_id);
            let requiredCommentPhotoTypeInput = $('#question_required_comment_photo_input_'+question_id);

            let validationResult = validateStrategies(value, strategies);

            requiredShower.html(validationResult['requiredMessage']?? '');
            requiredInput.val(validationResult['requiredMessage']? '1' : '0');
            requiredCommentShower.html(validationResult['requiredCommentMessage']?? '');

            requiredCommentPhotoTypeInput.val(validationResult['requiredCommentPhotoType']?? '0');

            let questionScoreInput = $('#question_score_'+question_id);
            let questionScoreShower = $('#question_score_shower_'+question_id);
            let questionPossibleScoreShower = $('#question_possible_score_shower_'+question_id);
            let scores = scoringStrategies(value, [], possibleScore);
            questionScoreInput.val(scores.score);
            questionScoreShower.html(scores.score);
            questionPossibleScoreShower.html(scores.possibleScore);
            questionScoreInput.data('possible_score', scores.possibleScore);

            let categoryScore = 0;
            let sectionScore = 0;
            let categoryPossibleScore = 0;
            let sectionPossibleScore = 0;
            $('.question_score').each(function () {
                if($(this).data('category') == category_id) {
                    categoryScore += parseFloat($(this).val());
                    categoryPossibleScore += parseFloat($(this).data('possible_score'));
                }
                if($(this).data('section') == section_id) {
                    sectionScore += parseFloat($(this).val());
                    sectionPossibleScore += parseFloat($(this).data('possible_score'));
                }
            });

            $('#category_score_shower_'+category_id).html(categoryScore);
            $('.section_score_shower_'+section_id).html(sectionScore);

            $('#category_possible_score_shower_'+category_id).html(categoryPossibleScore);
            $('.section_possible_score_shower_'+section_id).html(sectionPossibleScore);

        });

        var currentQuestionToComment  = null;

        $(document).on('click','.btn-add-comment',function (e) {
            let question_id = $(this).data('id');
            currentQuestionToComment = question_id;
            var fileinput = $('#answer-attachment');

            $('#comment-question-id').val(question_id);
            $('#answer-comment-text').val($('#comment_'+question_id).val());
            fileinput.attr('data-target', 'attachment_'+question_id)
            $('#btn-save-comment').data('id', question_id)
            $('#comment-question-content').html($(this).data('title'))

            let attachments = $('#attachment_'+question_id).val().split(';')?? []

            $('#answer-comment-modal-opener').click();

            initFancyFileUpload(fileinput);

            let fInput = fileinput.data('fancy-fileupload').form.find('input[type=file]');
            attachments.forEach((item, index) => {
                if(item != ''){
                    var filename = 'Attachment '+ index;
                    fetch('{{url('/')}}/'+item).then(function(response) {
                        return response.blob();
                    }).then(function(myBlob) {
                        myBlob.name = filename;
                        fInput.fileupload('add', { files: [myBlob] });
                    });

                    setTimeout(() =>{
                        $(".ff_fileupload_filename input").each(function (){
                            if($(this).val()  === filename){
                                var btnRemove = $(this).parent().parent().next().find('.ff_fileupload_remove_file');
                                btnRemove.attr('file_url', item);
                            }
                        })
                    }, 2000);
                }
            });

            setTimeout(() =>{
                $('.ff_fileupload_start_upload').hide();
            }, 2000);
        });

       

        $(document).on('click','#btn-save-comment',function (e) {
            let question_id = $(this).data('id');

            $('#comment_'+question_id).val($('#answer-comment-text').val())
            $('#answer-comment-text').val('');

            try {
                fancyuploderData.ff_info?.RemoveFile();
            }catch (e){}

            $('#answer-comment-modal-closer').click();
        });


        $(document).on('click','.ff_fileupload_remove_file',function (e) {
            let fileUrl = $(this).attr('file_url');
            let attachmentInput = $('#attachment_'+currentQuestionToComment);
            let currentAttachments = attachmentInput.val().split(';');

            currentAttachments.splice(currentAttachments.indexOf(fileUrl), 1);
            attachmentInput.val(currentAttachments.join(';'));
        });





    </script>
@endsection
