@extends('template')

@section('page-title') Add Question Set @endsection

@section('tag-title') Add Question Set @endsection

@section('page-sub-title')

@endsection

@section('main-content')

    <?php
        use \App\Models\Task;
        $q_sets_categories = DB::table('question_set_categories')->get();
        $departments = DB::table('departments')->get();
        $tags = DB::table('tags')->get();
        $priorities = DB::table('priorities')->get();
        $status = DB::table('status')->get();
        $oldTagIds = $model->tags->pluck('id')->toArray();
        $users = DB::table('users')->select('id', 'email', DB::raw('CONCAT(lastname, " ", firstname) as name'))->get();

        $users_notified_on_complete = explode(',', $model->users_notified_on_complete);
        $users_notified_on_late = explode(',', $model->users_notified_on_late);
        $users_notified_on_critical = explode(',', $model->users_notified_on_critical);
        $users_notified_on_planing = explode(',', $model->users_notified_on_planing);

        if(isset($task)) {
            $oldTaskTagIds = $task->tags->pluck('id')->toArray();
            $task_assigned_users = $task->users->pluck('id')->toArray();
        } else {
            $task = new Task();
            $oldTaskTagIds = [];
            $task_assigned_users = [];
        }

        $locations = DB::table('locations')->where('department_id', $model->department_id)->get();

    ?>

    <div class="row">
        <div class="col-xl-12">
            <div class="card">
                <div class="card-body">
                    <div class="panel panel-primary tabs-style-2">
                        <div class=" tab-menu-heading">
                            <div class="tabs-menu1">
                                <ul class="nav panel-tabs main-nav-line">
                                    <li><a href="#details" class="nav-link {{$task->id? '' : 'active'}}" data-bs-toggle="tab">Details</a></li>
                                    <li><a href="#tasks" class="nav-link {{$task->id? 'active' : ''}}" data-bs-toggle="tab">Planing</a></li>
                                </ul>
                            </div>
                        </div>

                        <div class="panel-body tabs-menu-body main-content-body-right border">
                            <div class="tab-content">
                                <div class="tab-pane {{$task->id? '' : 'active'}}" id="details">
                                    <form method="POST" id="question-set-form" autocomplete="off" action="" enctype="multipart/form-data" class="form-horizontal form-label-left input_mask form-step row">
                                        {{csrf_field()}}
                                        <input type="hidden" value="{{$model->id && !isset($duplication)? $model->id : 0}}" id="_id" name="_id">
                                        <input type="hidden" value="{{$duplication?? 0}}" id="duplication" name="duplication">

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="department_id" class="control-label">Department <span style="color: red">*</span></label>
                                                <select required id="department_id" name="department_id" class="form-control select2">
                                                    <option value="">*Choose</option>
                                                    @foreach($departments as $item)
                                                        <option  @if($item->id == $model->department_id) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="question_set_category_id" class="control-label">Category <span style="color: red">*</span></label>
                                                <select required id="question_set_category_id" name="question_set_category_id" class="form-control">
                                                    <option value="">*Choose</option>
                                                    @foreach($q_sets_categories as $item)
                                                        <option  @if($item->id == $model->question_set_category_id) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="title" class="control-label">Title <span style="color: red">*</span></label>
                                                <input required class="form-control" value="{{$model->title}}" name="title" id="title"  type="text" >
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="tags" class="control-label">Tags</label>
                                                <select data-placeholder="Sélectionner ..." class="form-control select2" name="tags[]" id="tags" multiple="multiple">
                                                    @foreach($tags as $item)
                                                        <option @if(in_array(old('tags',$item->id), $oldTagIds)) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="users_notified_on_complete" class="control-label">Notify On Complete</label>
                                                <select data-placeholder="Choose ..." class="form-control select2" name="users_notified_on_complete[]" id="users_notified_on_complete" multiple="multiple">
                                                    @foreach($users as $item)
                                                        <option @if(in_array(old('users_notified_on_complete',$item->email), $users_notified_on_complete)) selected @endif value="{{$item->email}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="users_notified_on_late" class="control-label">Notify On Late</label>
                                                <select data-placeholder="Choose ..." class="form-control select2" name="users_notified_on_late[]" id="users_notified_on_late" multiple="multiple">
                                                    @foreach($users as $item)
                                                        <option @if(in_array(old('users_notified_on_late',$item->email), $users_notified_on_late)) selected @endif value="{{$item->email}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="users_notified_on_planing" class="control-label">Notify On Planing</label>
                                                <select data-placeholder="Choose ..." class="form-control select2" name="users_notified_on_planing[]" id="users_notified_on_planing" multiple="multiple">
                                                    @foreach($users as $item)
                                                        <option @if(in_array(old('users_notified_on_planing',$item->email), $users_notified_on_planing)) selected @endif value="{{$item->email}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>


                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="active" class="control-label">Active  <span style="color: red">*</span></label>
                                                <select required id="active" name="active" class="form-control">
                                                    <option value="">*Choose</option>
                                                    <option @if($model->active===1) selected @endif value="1">Yes</option>
                                                    <option @if($model->active===0) selected @endif value="0">No</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-12 mt-3">
                                            <h4>Questions</h4>
                                        </div>

                                        <div id="questions-view-container" class="mt-3 col-sm-12">
                                        </div>

                                        <div class="col-sm-12 mt-">
                                            <button type="submit"  class="btn btn-success action-btn  float-right btn-submit-step">Save</button>
                                        </div>  
                                    </form>
                                    
                                </div>
                                <div class="tab-pane {{$task->id? 'active' : ''}}" id="tasks">

                                    <form method="POST" autocomplete="off" action="{{url('question-sets/'.$model->id.'/tasks')}}" enctype="multipart/form-data" class="form-horizontal form-label-left input_mask form-step row">
                                        {{csrf_field()}}

                                        <div class="col-sm-12 mb-2">
                                            <h4>{{$task->id? 'Edit task' : 'Add task' }}</h4>
                                        </div>

                                        <input type="hidden" value="{{$task->id?? 0}}" id="task_id" name="task_id">
                                        <input type="hidden" value="{{$model->id && !isset($duplication)? $model->id : 0}}" id="question_set_id" name="question_set_id">

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="location_id" class="control-label">Location <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 == $task->location_id) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="title" class="control-label">Name <span style="color: red">*</span></label>
                                                <input required class="form-control" value="{{$task->title}}" name="title" id="task_title"  type="text" >
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="open_at" class="control-label">Start On <span style="color: red">*</span></label>
                                                <input  required name="start_date" readonly id="start_date" type="text" class="form-control datetime-input" value="{{old('start_date' , $task->start_date? date('d/m/Y H:i', strtotime($task->start_date)) : '')}}" placeholder="dd/mm/YYYY hh:mm"  >
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="priority_id" class="control-label">Priority <span style="color: red">*</span></label>
                                                <select required id="priority_id" name="priority_id" class="form-control">
                                                    <option value="">*Choose</option>
                                                    @foreach($priorities as $item)
                                                        <option  @if($item->id == $task->priority_id) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="tags" class="control-label">Tags</label>
                                                <select data-placeholder="Sélectionner ..." class="form-control select2" name="tags[]" id="task_tags" multiple="multiple">
                                                    @foreach($tags as $item)
                                                        <option @if(in_array(old('tags',$item->id), $oldTaskTagIds)) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="frequency" class="control-label">Repeat every</label>
                                                <div class="pos-relative">
                                                    <input type="number" placeholder="Leave blank, if not repeated" value="{{$task->frequency}}" name="frequency" class="form-control pd-r-80">
                                                    <div class="d-flex pos-absolute t-0 r-0">
                                                        <select id="task_frequency_type" name="frequency_type" class="form-control">
                                                            <option value="DAY">Day(s)</option>
                                                            <option value="WEEK">Week(s)</option>
                                                            <option value="MONTH">Month(s)</option>
                                                            <option value="YEAR">Year(s)</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="end_date" class="control-label">Repeat until</label>
                                                <input  name="end_date" readonly id="end_date" type="text" class="form-control datetime-input" value="{{old('end_date' , $task->end_date!=null? date('d/m/Y H:i', strtotime($task->end_date)) : '')}}" placeholder="dd/mm/YYYY hh:mm"  >
                                            </div>
                                        </div>

                                        @if(!empty($task->id))
                                            <div class="col-sm-4">
                                                <div class="form-group">
                                                    <label for="status_id" class="control-label">Status  <span style="color: red">*</span></label>
                                                    <select required id="task_status_id" name="status_id" class="form-control">
                                                        <option value="">*Choose</option>
                                                        @foreach($status as $item)
                                                            <option  @if($item->id == $task->status_id) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        @endif

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="task_users" class="control-label">Assign to <span style="color: red">*</span></label>
                                                <select data-placeholder="Choose ..." class="form-control select2" name="task_users[]" id="task_users" multiple="multiple">
                                                    @foreach($users as $item)
                                                        <option @if(in_array(old('task_users',$item->id), $task_assigned_users)) selected @endif value="{{$item->id}}">{{$item->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-sm-4">
                                            <div class="form-group">
                                                <label for="description" class="control-label">Notes</label>
                                                <textarea class="form-control" name="description" id="task_description">{{$task->description}}</textarea>
                                            </div>
                                        </div>

                                        <div class="col-sm-12 mt-2">
                                            <button type="submit"  class="btn btn-success action-btn  float-right btn-submit-step">Save</button>
                                        </div>
                                    </form>

                                    @if(!empty($model->id) && !isset($duplication))
                                        <div class="table-responsive mt-3">
                                            <h4>Tasks list</h4>
                                            <table class="table table-bordered table-hover" id="task-data-table" style="width: 100%">
                                                <thead>
                                                <tr>
                                                    <th style="width: 10%" class="border-bottom-0">Name</th>
                                                    <th style="width: 20%" class="border-bottom-0">Location</th>
                                                    <th style="width: 30%" class="border-bottom-0">Start date</th>
                                                    <th style="width: 30%" class="border-bottom-0">Completed at</th>
                                                    <th style="width: 20%" class="border-bottom-0">Priority</th>
                                                    <th style="width: 10%" class="border-bottom-0">Status</th>
                                                    <th class="border-bottom-0" style="width: 10%; border-right: none;">Actions</th>
                                                </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>

                    </div>

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



@endsection

@section('page-style')
    <link href=" https://cdn.jsdelivr.net/npm/accordion@3.0.2/src/accordion.min.css " rel="stylesheet">
    <style>
        label{
            font-weight: bold;
            margin-bottom: 3px;
        }

        .question-accordion {
            height: auto !important;
        }

        .question-accordion > div {
            position: relative;
            display: flex;
            flex-direction: column;
            width: 100%;
            pointer-events: auto;
            border: 1px solid #e3e8f7;
            border-radius: 0.3rem;
            outline: 0;
        }

        .question-accordion > div.open{
            height: auto !important;
        }

        .question-accordion .acc-header{
            justify-content: space-between;
            padding: .5rem;
            border-bottom: 1px solid #e3e8f7;
            border-top-left-radius: 0.3rem;
            border-top-right-radius: 0.3rem;
            background-color: #f0f6ff;
            font-size: 15px;
            font-weight: bold;
        }

        .question-accordion .acc-header .btn-sm{
            padding: 1px 3px;
        }

        .question-accordion .acc-header .btn-sm i{
            font-size: 15px;
        }

        .question-accordion .open .indicator::before{
            content: "\f139";
        }

        .question-accordion .closed .indicator::before{
            content: "\f13a";
        }

        .question-accordion .acc-header .indicator{
            font-size: 18px;
        }

        .question-accordion .acc-body{
            position: relative;
            flex: 1 1 auto;
            padding: .5rem;
        }

        .question-form{
            padding: 10px;
            background-color: #f4f4f4;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .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;
        }
    </style>
    <link href="{{url('assets/plugins/datatable/css/jquery.dataTables.min.css')}}" rel="stylesheet">
@endsection

@section('page-script')
    <script src=" https://cdn.jsdelivr.net/npm/accordion@3.0.2/src/accordion.min.js "></script>
    <script src="{{url('assets/plugins/datatable/js/jquery.dataTables.min.js')}}"></script>

    <script>

        function refreshQuestionFormData(){
            $('#global-loader').show();
            var req = $.ajax({
                url: '{{url(config('app.admin_prefix').'/refresh-question-from-data')}}',
                type: "GET",
                data: {question_set_id: '{{$model->id}}'},
                dataType: "html"
            });
            req.done(function (response, textStatus, jqXHR) {
                $('#questions-view-container').html(response);
                $('#global-loader').hide();
            });
            req.fail(function (jqXHR, textStatus) {
                $('#global-loader').hide();
                swal("Erreur!", "Error during get data. Please refresh page", "warning");
            });
        }

        refreshQuestionFormData();

        $(document).on('submit','#question-set-form',function (e) {
            e.preventDefault();

            let formData = $(this).serializeArray();
            formData.push({
                'name' : 'questions',
                'value' : JSON.stringify(questions_data),
            });

            let req = $.ajax({
                url: '{{url(config('app.admin_prefix').'/question-sets')}}',
                type: "POST",
                data: formData,
                dataType: "json"
            });
            req.done(function (response, textStatus, jqXHR) {
                if(response.success){
                    swal('Success', response.message, 'success');
                    if(response.redirectTo !== undefined){
                        $('.confirm').on('click',function () {
                            window.location = response.redirectTo;
                        })
                    }
                }
            });
            req.fail(function (jqXHR, textStatus) {
                let response = JSON.parse(jqXHR.responseText)
                swal("Error!", response.message, "warning");
            });
        });

        function refreshData(){
            $('#task-data-table').DataTable({
                lengthMenu: [[10, 25, 50,100,200], [10, 25, 50, 100, 200]],
                pageLength: 50,
                responsive: true,
                processing : true,
                serverSide: true,
                ordering: false,
                ajax: '{{url('tasks/ajax_list?current_path='.Request::path())}}'+'&question_set_id={{$model->id}}',
                destroy : true,
                language: {
                    searchPlaceholder: 'Search...',
                    sSearch: '',
                    lengthMenu: '_MENU_',
                    sProcessing : "Loading..."
                },
            });
        }
        @if(!empty($model->id) && !isset($duplication))
            refreshData();
        @endif
    </script>
@endsection
