<!-- resources/views/your-page.blade.php -->
@extends('layouts.theme1')

@section('title', 'Dashboard')

@section('style')

<link rel="stylesheet" href="{{ asset('theme1/dist/libs/select2/dist/css/select2.min.css') }}">
    <!-- Custom CSS -->
<link href="{{ asset('theme1/dist/css/style.min.css') }}" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.11.5/datatables.min.css"/>

@endsection

@section('content')
    <!-- Contenu de votre page -->
    


    <div class="col-md-12">
        <div class="card">
        <div class="border-bottom title-part-padding">
            <h4 class="card-title mb-0">Creation de plusieurs Questions</h4>
        </div>
        <div class="card-body">

            <form id="answerForm" class="row" action="{{ route('admin.questions.store') }}" enctype="multipart/form-data"  method="post">
                @csrf

                <!-- Ajoutez cette ligne pour la variable cachée -->
                <input type="hidden" name="question_id" id ="question_id" value="0">

                <div class="form-group mb-4">
                    <label class="mr-sm-2" for="parentSelect">Select le parent des questions</label>
                    <select 
                    class="form-control mr-sm-2" 
                    id="parentSelect" 
                    name="parentSelect"
                    style="width: 100%; height: 36px"
                    >
                        <option selected disabled>Choisir le parent de la question..</option>
                        <option value="Project"> Project</option>
                        <option value="Document"> Document</option>
                        <option value="Chapter"> Chapter</option>
                    </select>
                    
                </div>

                <div class="form-group mb-4" id="project-div">
                    <label class="mr-sm-2" for="projectSelect">Select a Project</label>
                    <select 
                    class="select2 form-control custom-select"
                    style="width: 100%; height: 36px"
                    id="projectSelect" 
                    name="projectSelect"
                    >
                         <option selected disabled>Choisir...</option>

                        @foreach ($projects as $project)
                            <option value="{{ $project->id }}">{{ $project->libelle }}</option>
                        @endforeach
                    </select>
                    
                </div>

                <div class="form-group mb-4" id="document-div">
                    <label class="mr-sm-2" for="documentSelect">Select a Document</label>
                    <select 
                    class="select2 form-control custom-select"
                    style="width: 100%; height: 36px"
                    id="documentSelect" 
                    name="documentSelect"
                    >
                         <option selected disabled>Choisir...</option>

                        @foreach ($documents as $document)
                            <option value="{{ $document->id }}">{{ $document->libelle }}</option>
                        @endforeach
                    </select>
                    
                </div>

                <div class="form-group mb-4" id="chapter-div">
                    <label class="mr-sm-2" for="chapterSelect">Select a Chapter</label>
                    <select 
                    class="select2 form-control custom-select"
                    style="width: 100%; height: 36px"
                    id="chapterSelect" 
                    name="chapterSelect"
                    >
                         <option selected disabled>Choisir...</option>

                        @foreach ($chapters as $chapter)
                            <option value="{{ $chapter->id }}">{{ $chapter->libelle }}</option>
                        @endforeach
                    </select>
                    
                </div>             

                <div class="form-group mb-4">
                    <textarea class="form-control" id="question" name="question" placeholder="Saisir votre nouvelle Question"></textarea>
                </div>

                <div class="row">
                    <div class="col-sm-8">
                        <div class="mb-8">
                        <textarea class="form-control" id="libelle" name="libelle[]" placeholder="Saisir votre Question"></textarea>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="mb-3">
                            <input type="file" class="form-control" name="image[]" accept="image/*">
                        </div>
                    </div>
                    
                    <div class="col-sm-1">
                        <div class="mb-1">
                            <button onclick="addQuestion();" class="btn rounded-pill px-4 btn-light-success text-success font-weight-medium waves-effect waves-light" type="button">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle feather-sm fill-white">
                                    <circle cx="12" cy="12" r="10"></circle>
                                    <line x1="12" y1="8" x2="12" y2="16"></line>
                                    <line x1="8" y1="12" x2="16" y2="12"></line>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                <div id="answerFields" class="my-4"></div>

                <button type="submit" class="
                            btn btn-primary
                            font-weight-medium
                            rounded-pill
                            px-4
                          ">Enregistrer les reponses</button>

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

    <div class="row">
        <div class="col-12">
            <div class="card">
            <div class="border-bottom title-part-padding">
                <h4 class="card-title mb-0">Answers</h4>
            </div>
            <div class="card-body">
                <h6 class="card-subtitle mb-3">
                    Description ici
                </h6>
                
                <div class="table-responsive">
                <table id="questions-table" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Libellé</th>
                            <th>imageName</th>
                            <th>chapter_id</th>
                            <th>project_id</th>
                            <th>document_id</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                </div>
            </div>
            </div>
        </div>
    </div>

    @include('admin.delete_modal')
   
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.11.5/datatables.min.js"></script>
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>

   
    <script>
        $(document).ready(function() {

            $("#question").hide();   
            $("#project-div").hide();     
            $("#document-div").hide();    
            $("#chapter-div").hide();    

            // Ajouter un gestionnaire d'événements au changement de la sélection

            $("#parentSelect").change(function() {
                var selectedValue = $(this).val();

                if (selectedValue === "Project") {
                    $("#project-div").show();
                    $("#document-div").hide();    
                    $("#chapter-div").hide();    

                } else if (selectedValue === "Document") {
                    $("#project-div").hide();
                    $("#document-div").show();    
                    $("#chapter-div").hide();   
                } else if (selectedValue === "Chapter") {
                    $("#project-div").hide();
                    $("#document-div").hide();    
                    $("#chapter-div").show();   
                    
                } else {
                    $("#question").hide();
                    $("#project-div").hide();
                    $("#document-div").hide();    
                    $("#chapter-div").hide();   
                }
                console.log("Option sélectionnée :", selectedValue);
            });

            $("#questionSelect").change(function() {
                // Récupérer la valeur sélectionnée
                var selectedValue = $(this).val();

                // Si la valeur est "0", afficher le champ de texte, sinon le cacher
                if (selectedValue === "0") {
                    $("#question").show();
                } else {
                    $("#question").hide();
                }
                console.log("Option sélectionnée :", selectedValue);
            });

            $('#questions-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ route('admin.questions.index') }}',
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'libelle', name: 'libelle' },
                    { data: 'image', name: 'image' },
                    { data: 'chapter_id', name: 'chapter_id' },
                    { data: 'project_id', name: 'project_id' },
                    { data: 'document_id', name: 'document_id' },
                    { 
                        data: 'action', 
                        name: 'action', 
                        orderable: false, 
                        searchable: false,
                        createdCell: function (td, cellData, rowData, row, col) {
                            $(td).attr('data-id', rowData.id);
                        }
                    },
                ]
            });

            // Gestionnaire d'événement pour le clic sur le bouton de suppression
            $('#questions-table tbody').on('click', '.deleteProject', function (e) {
                e.stopPropagation(); // Empêche la propagation de l'événement à la ligne
                var rowId = $(this).data('id');
                
                // Ouvrir le modal de confirmation
                $('#deleteConfirmationModal').modal('show');

                // Gestionnaire d'événement pour le clic sur le bouton de confirmation de suppression
                $('#confirmDelete').on('click', function () {
                    // Fermer le modal de confirmation
                    $('#deleteConfirmationModal').modal('hide');

                    // Effectuer la suppression en utilisant AJAX
                    $.ajax({
                        url: '/admin/questions/' + rowId,
                        type: 'DELETE',
                        data: {
                            _token: $('meta[name="csrf-token"]').attr('content'),
                        },
                        success: function (response) {
                            console.log(response.message);
                            $('#questions-table').DataTable().ajax.reload();
                            // Mettez à jour votre interface utilisateur ou effectuez d'autres actions nécessaires
                        },
                        error: function (error) {
                            console.error('Erreur AJAX:', error);
                            // Gérez l'erreur ici
                        }
                    });
                });
            });

            //Fin des fonctions
        });

        var questionCounter = 1;

        function addQuestion() {
            questionCounter++;
            var answerForm = document.getElementById("answerFields");
            var divAnswer = document.createElement("div");
            divAnswer.setAttribute("class", "mb-3 removeAnswer" + questionCounter);
            var removeAnswer = "removeAnswer" + questionCounter;
            divAnswer.innerHTML =
                '<div class="row">' +
                '<div class="col-sm-8"><div class="mb-3"><textarea class="form-control" name="libelle[' + questionCounter + ']" placeholder="Saisir votre question"></textarea></div></div>' +
                '<div class="col-sm-3"><div class="mb-3"><input type="file" class="form-control" name="image[' + questionCounter + ']" accept="image/*" ></div></div>' +
                '<div class="col-sm-1"><div class="mb-3"><button class="btn btn-danger" type="button" onclick="removeAnswer(' +
                questionCounter +
                ');"><i class="fa fa-minus"></i></button></div></div>' +
                '</div>';
                '</div>';

            answerForm.appendChild(divAnswer);
        }

        function removeAnswer(rid) {
            $(".removeAnswer" + rid).remove();
        }
                
    </script>
@endsection


@section('script')

    <script src="{{ asset('theme1/dist/libs/select2/dist/js/select2.full.min.js') }}"></script>
    <script src="{{ asset('theme1/dist/libs/select2/dist/js/select2.min.js') }}"></script>
    <script src="{{ asset('theme1/dist/js/pages/forms/select2/select2.init.js') }}"></script>

@endsection