@extends('layouts.app')
@section('title', 'Surveys')
@section('content')

    <!-- script js -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        function choose_type(type_name, type_value, questionDetails = null) {
            console.log(`#detail-${type_name}`);
            var nameType = type_name.split('[type]')[0];
            let result = '';

            // Setting default question detail
            if (questionDetails == null) {
                questionDetails = {
                    labelfrom: 'Sangat Tidak Setuju',
                    labelto: 'Sangat Setuju',
                    valuefrom: 0,
                    valueto: 5
                }
            }

            if (type_value == 'Skala') {
                result = `<div class="mt-3 col-lg-6">
                        <div class="d-flex mb-2">
                            <select name="${nameType}[valuefrom]" id="${nameType}[valuefrom]" class="form-select border-bottom" style="border: none; width: 85px;">
                                <option value="0" ${(questionDetails['valuefrom'] == 0) ? 'selected' : ''}>0</option>
                                <option value="1" ${(questionDetails['valuefrom'] == 1) ? 'selected' : ''}>1</option>
                            </select>
                            <input type="text" class="form-control ms-2" name="${nameType}[labelfrom]" style="width: 150px;" placeholder="Tidak Setuju" value="${questionDetails['labelfrom']}" required>

                            <p class="mx-3 my-auto"> sampai </p>

                            <select name="${nameType}[valueto]" id="${nameType}[valueto]" class="form-select border-bottom" style="border: none; width: 85px;">
                                @for ($i = 2; $i <= 10; $i++) <option value="{{ $i }}" ${(questionDetails['valueto'] == '{{ $i }}') ? 'selected' : ''}>{{ $i }}</option>@endfor
                            </select>
                            <input type="text" class="form-control ms-2" name="${nameType}[labelto]" style="width: 150px;" placeholder="Setuju" value="${questionDetails['labelto']}" required>
                        </div>
                    </div>`;
            } else if (type_value == 'Jawaban Angka') {
                result = `<div class="mt-3 col-lg-12">
                        <input type="number" class="form-control" id="${nameType}[angka]" rows="3" placeholder="Pertanyaan berupa angka" disabled>
                    </div>`;
            } else if (type_value == 'Jawaban Singkat') {
                result = `<div class="mt-3 col-lg-12">
                        <input type="text" class="form-control" id="${nameType}[teks]" rows="3" placeholder="Pertanyaan berupa teks singkat" disabled>
                    </div>`;
            } else if (type_value == 'Esai') {
                result = `<div class="mt-3 col-lg-12">
                        <textarea class="form-control" id="${nameType}[esai]" rows="3" placeholder="Pertanyaan berupa teks panjang atau esai" disabled></textarea>
                    </div>`;
            } else if (type_value == 'Master') {
                result = `<div class="mt-3 col-lg-12">
                        <select class="form-select" id="${nameType}[master]" name="${nameType}[master]">
                            @foreach ($management_master as $master)
                            <option value='["{{ $master->master_value }}", "{{ $master->master_column }}"]' ${(questionDetails == '{{ $master->master_value }}' ? 'selected' : null)}>{{ $master->master_code }}</option>
                            @endforeach
                        </select>
                    </div>`;
            } else {
                result = `<div class="mt-3 col-lg-6">
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" id="value${nameType}" value="1">
                            <label class="form-check-label" for="value${nameType}" id="label${nameType}" >
                                Iya
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" id="value${nameType}" value="0">
                            <label class="form-check-label" for="value${nameType}" id="label${nameType}" >
                                Tidak
                            </label>
                        </div>
                    </div>`;
            }

            document.getElementById(`detail-${type_name}`).innerHTML = result;
        }

        let id = '{{ isset($survey->questionSurveys->last()->id) ? $survey->questionSurveys->last()->id + 1 : 1 }}';

        function add_question() {
            $('#labelAddQuestion').html('Loading...')
            var form_data = new FormData($('#add-question')[0]);
            $.ajax({
                type: 'post',
                url: "{{ URL::to('admin/surveys/add-question', $survey->id) }}",
                data: form_data,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data) {
                    $('#labelAddQuestion').html('Tambah Pertanyaan')
                    console.log(data);
                    $('#question_all').append(`<div class="col-lg-12 mx-auto"  id="question-${data.id}">
                    <div class="card">
                        <div class="card-body">
                            <form method="post" id="delete-question-${data.id}">
                                @csrf
                                @method('DELETE')
                                <div class="d-flex">
                                    <a href="javascript:void(0)" onclick="delete_question('question-${data.id}')" class="badge text-bg-danger text-light ms-auto" id="label-delete-question-${data.id}">
                                        <i class="ti ti-trash"></i>
                                    </a>
                                </div>
                            </form>
                            <form method="post" id="form-question-${data.id}" onkeyup="save_question(this.id)" onchange="save_question(this.id)">
                                @csrf
                                @method('POST')
                                <div class="row">
                                    <label class="form-label">Pertanyaan</label>
                                    <div class="mb-3 col-lg-8">
                                        <input type="text" class="form-control" id="questionSurvey[${data.id}][question]" name="questionSurvey[${data.id}][question]" value="${data['name']}" placeholder="Tuliskan pertayaan anda?" required>
                                        <!-- error message -->
                                        @error('questionSurvey[${data.id}][question]')
                                        <div class="invalid-feedback">
                                            {{ $message }}
                                        </div>
                                        @enderror
                                    </div>
                                    <div class="mb-3 col-lg-4">
                                        <select class="form-select" id="questionSurvey[${data.id}][type]" name="questionSurvey[${data.id}][type]" onchange="choose_type(this.name, this.value)" required>
                                            <option value="">Pilih Tipe Pertanyaan</option>
                                            <option value="Iya atau Tidak" selected>Iya atau Tidak</option>
                                            <option value="Jawaban Angka">Jawaban Angka</option>
                                            <option value="Jawaban Singkat">Jawaban Singkat</option>
                                            <option value="Skala">Skala</option>
                                            <option value="Esai">Esai</option>
                                            <option value="Master">Master</option>
                                        </select>
                                        <!-- error message -->
                                        @error('questionSurvey[${data.id}][type]')
                                        <div class="invalid-feedback">
                                            {{ $message }}
                                        </div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="row mb-0" id="detail-questionSurvey[${data.id}][type]">
                                    <!-- Result detail type -->
                                </div>
                            </form>
                        </div>
                    </div>
                </div>`);

                    console.log(id);
                    id++; // add id
                },
                error: function() {
                    $('#labelAddQuestion').html('Tambah Pertanyaan')
                    console.log('Add question error');
                }
            });
        }

        function delete_question(id) {
            $('#label-delete-' + id).html('Loading...')
            var form_data = new FormData($('#delete-' + id)[0]);
            let question_id = id.split('-')[1];
            Swal.fire({
                title: 'Kamu yakin?',
                text: "Ingin menghapus pertanyaan ini!",
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Iya, saya yakin!',
                cancelButtonText: 'Tidak'
            }).then((result) => {
                console.log(result);
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'post',
                        url: "{{ URL::to('admin/surveys/delete-question') }}" + '/' + question_id,
                        data: form_data,
                        dataType: 'json',
                        processData: false,
                        contentType: false,
                        success: function(data) {
                            console.log(data);
                            document.getElementById(id).remove();
                        },
                        error: function() {
                            $('#label-delete-' + id).html('<i class="ti ti-trash"></i>')
                            console.log('Delete question error');
                        }
                    });
                } else if (result.isDismissed) {
                    $('#label-delete-' + id).html('<i class="ti ti-trash"></i>')
                }
            });

        }
    </script>

    <!-- button back -->
    <a href="{{ URL::to('admin/surveys') }}" class="mb-3 badge text-bg-light text-primary">
        <i class="ti ti-arrow-left">&nbsp;</i> Kembali
    </a>

    <!-- Surveys -->
    <div class="row d-flex align-items-strech">
        <form method="post" id="form-survey" onsubmit="save_survey()">
            @csrf
            @method('POST')
            <div class="col-lg-12 mx-auto">
                <div class="card">
                    <div class="card-header border-bottom d-flex">
                        <h3>Form Survey</h3>
                        <i class="ms-auto my-auto text-primary" id="labelAutoSaved">Auto Saved</i>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="mb-3 col-lg-6">
                                <label for="name" class="form-label">Judul Survey</label>
                                <input type="text" class="form-control" id="name" name="name"
                                    value="{{ $survey->name }}" onkeyup="save_survey()" required>
                                <!-- error message -->
                                @error('name')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                            <div class="mb-3 col-lg-2"></div>
                            <div class="mb-3 col-lg-4">
                                <label for="years" class="form-label">Tahun</label>
                                <input type="number" class="form-control" id="years" name="years"
                                    value="{{ $survey->years }}" onkeyup="save_survey()" required>
                                <!-- error message -->
                                @error('years')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>
                        <div class="row">
                            <div class="mb-3 col-lg-12">
                                <label for="description" class="form-label">Deskripsi</label>
                                <textarea class="form-control @error('description') is-invalid @enderror" id="description" name="description"
                                    rows="3" placeholder="Isikan penjelasan tentang tujuan survey anda" onkeyup="save_survey()" required>{{ $survey->description }}</textarea>
                                <!-- error message -->
                                @error('description')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Questions -->
    <div class="row d-flex align-items-strech" id="question_all">
        @foreach ($survey->questionSurveys as $questionSurveys)
            <div class="col-lg-12 mx-auto row" id="question-{{ $questionSurveys->id }}">
                <div class="card">
                    <div class="card-body">
                        <form method="post" id="delete-question-{{ $questionSurveys->id }}">
                            @csrf
                            @method('DELETE')
                            <div class="d-flex">
                                <a href="javascript:void(0)"
                                    onclick="delete_question('question-{{ $questionSurveys->id }}')"
                                    class="badge text-bg-danger text-light ms-auto"
                                    id="label-delete-question-{{ $questionSurveys->id }}">
                                    <i class="ti ti-trash"></i>
                                </a>
                            </div>
                        </form>
                        <form href="javascript:void(0)" method="post" id="form-question-{{ $questionSurveys->id }}"
                            onkeyup="save_question(this.id)" onchange="save_question(this.id)">
                            @csrf
                            @method('POST')
                            <div class="row">
                                <div class="col-lg-12">
                                    <label class="form-label">Pertanyaan</label>
                                </div>
                                <div class="mb-3 col-lg-8">
                                    <input type="text" class="form-control"
                                        id="questionSurvey[{{ $questionSurveys->id }}][question]"
                                        name="questionSurvey[{{ $questionSurveys->id }}][question]"
                                        value="{{ $questionSurveys->name }}" placeholder="Tuliskan pertayaan anda?"
                                        required>
                                    <!-- error message -->
                                    @error('questionSurvey[{{ $questionSurveys->id }}][question]')
                                        <div class="invalid-feedback">
                                            {{ $message }}
                                        </div>
                                    @enderror
                                </div>
                                <div class="mb-3 col-lg-4">
                                    <select class="form-select" id="questionSurvey[{{ $questionSurveys->id }}][type]"
                                        name="questionSurvey[{{ $questionSurveys->id }}][type]"
                                        onchange="choose_type(this.name, this.value)" required>
                                        <option value="">Pilih Tipe Pertanyaan</option>
                                        <option value="Iya atau Tidak" @if ($questionSurveys->type == 'Iya atau Tidak') selected @endif>Iya
                                            atau Tidak</option>
                                        <option value="Skala" @if ($questionSurveys->type == 'Skala') selected @endif>Skala
                                        </option>
                                        <option value="Jawaban Angka" @if ($questionSurveys->type == 'Jawaban Angka') selected @endif>
                                            Jawaban Angka</option>
                                        <option value="Jawaban Singkat" @if ($questionSurveys->type == 'Jawaban Singkat') selected @endif>
                                            Jawaban Singkat</option>
                                        <option value="Esai" @if ($questionSurveys->type == 'Esai') selected @endif>Esai
                                        </option>
                                        <option value="Master" @if ($questionSurveys->type == 'Master') selected @endif>Master
                                        </option>
                                    </select>
                                    <!-- error message -->
                                    @error('questionSurvey[{{ $questionSurveys->id }}][type]')
                                        <div class="invalid-feedback">
                                            {{ $message }}
                                        </div>
                                    @enderror
                                </div>
                            </div>
                            <div class="row mb-0" id="detail-questionSurvey[{{ $questionSurveys->id }}][type]">
                                <!-- Result detail type -->
                            </div>
                            <script>
                                var questionDetail = null;
                                if ('{{ isset($questionSurveys->questionDetails) ? 1 : 0 }}' && '{{ $questionSurveys->type }}' == 'Skala') {
                                    questionDetail = {
                                        labelfrom: '{{ isset($questionSurveys->questionDetails) && $questionSurveys->type == 'Skala' ? json_decode($questionSurveys->questionDetails->question_label)[0] : null }}',
                                        labelto: '{{ isset($questionSurveys->questionDetails) && $questionSurveys->type == 'Skala' ? json_decode($questionSurveys->questionDetails->question_label)[1] : null }}',
                                        valuefrom: '{{ isset($questionSurveys->questionDetails) && $questionSurveys->type == 'Skala' ? json_decode($questionSurveys->questionDetails->question_value)[0] : null }}',
                                        valueto: '{{ isset($questionSurveys->questionDetails) && $questionSurveys->type == 'Skala' ? json_decode($questionSurveys->questionDetails->question_value)[1] : null }}'
                                    }
                                } else if ('{{ $questionSurveys->type }}' == 'Master') {
                                    questionDetail =
                                        '{{ isset($questionSurveys->questionDetails) ? json_decode($questionSurveys->questionDetails->question_value)[0] : '' }}';
                                }
                                choose_type("questionSurvey[{{ $questionSurveys->id }}][type]", '{{ $questionSurveys->type }}', questionDetail);
                            </script>
                        </form>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    <!-- Add Question -->
    <div class="col-lg-12 text-end">
        <form method="POST" id="add-question">
            @csrf
            @method('POST')
            <a href="javascript:void(0)" onclick="add_question()" class="btn btn-sm bg-info-subtle text-info "
                data-bs-toggle="tooltip" title="Tambah Pertanyaan">
                <i class="ti ti-plus"></i> <span id="labelAddQuestion">Tambah Pertanyaan</span>
            </a>
        </form>
    </div>

    <!-- Save Survey -->
    <a href="{{ URL::to('admin/surveys') }}" class="btn btn-primary mt-3">Simpan</a>

    <script>
        // Dapatkan semua formulir
        var forms = document.getElementsByTagName("form");

        // Loop melalui setiap formulir
        for (var i = 0; i < forms.length; i++) {
            // Tambahkan event listener untuk setiap formulir
            forms[i].addEventListener("keydown", function(event) {
                // Hanya jalankan jika tombol Enter ditekan
                if (event.key === "Enter") {
                    // Mencegah default form submission
                    event.preventDefault();
                    // Tambahkan logika tambahan di sini jika diperlukan
                }
            });
        }
    </script>
    <script>
        function save_survey() {
            $('#labelAutoSaved').html('Loading...')
            var form_data = new FormData($('#form-survey')[0]);
            $.ajax({
                type: 'post',
                url: "{{ URL::to('admin/surveys/save-survey', $survey->id) }}",
                data: form_data,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data) {
                    $('#labelAutoSaved').html('Auto Saved')
                    console.log(data);
                },
                error: function() {
                    $('#labelAutoSaved').html('Auto Saved')
                    console.log('Saving data error');
                }
            });
        }

        function save_question(html_id) {
            $('#labelAutoSaved').html('Loading...')
            var form_data = new FormData($('#' + html_id)[0]);
            var question_id = html_id.split('-')[2];
            console.log('#' + html_id);
            $.ajax({
                type: 'post',
                url: "{{ URL::to('admin/surveys/save-question') }}/" + question_id,
                data: form_data,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data) {
                    $('#labelAutoSaved').html('Auto Saved')
                    console.log(data);
                },
                error: function() {
                    $('#labelAutoSaved').html('Auto Saved')
                    console.log('Saving data error');
                }
            });
        }
    </script>
@stop
