<?php
    use Illuminate\Support\Facades\Auth;
    $startDate = date('Y-m-d 00:00');
    $endDate = date('Y-m-d 23:59');
    $currMonth = date('m');
    $currYear = date('Y');

    $status_id = App\Models\Status::COMPLETED;
    $user_id = Auth::user()->id;

    $locations_user = App\Models\Location::whereHas('users', function ($query) use ($user_id) {
                $query->where('users.id', $user_id);
            })->pluck('id')->toArray();



    $question_set_jobs_completeds  = App\Models\QuestionSetJob::where('status_id',$status_id)->whereIn('location_id',$locations_user);
    $tasks = App\Models\Task::whereIn('location_id',$locations_user);


    if(!empty($request->get('filter_periode'))){
        $tab = explode(' - ',$request->get('filter_periode'));
        $datedeb = date('Y-m-d 00:00',strtotime(str_replace('/','-',$tab[0])));
        $datefin = date('Y-m-d 23:59',strtotime(str_replace('/','-',$tab[1])));

        $question_set_jobs_completeds = $question_set_jobs_completeds->where('start_at','>=', $datedeb);
        $question_set_jobs_completeds = $question_set_jobs_completeds->where('end_at','<=', $datefin);

        $tasks = $tasks->where('created_at','>=', $datedeb);
        $tasks = $tasks->where('created_at','<=', $datefin);
    }

    $locations_ids = array();
    if (!empty($request->get('location_id'))) {
            $location_ids = $request->get('location_id');
            $question_set_jobs_completeds = $question_set_jobs_completeds->whereIn('location_id', $location_ids);
            $tasks = $tasks->whereIn('location_id', $location_ids);
    }

    $question_set_jobs_completeds_= clone $question_set_jobs_completeds;

    $question_set_ids = $question_set_jobs_completeds_->pluck('question_set_id')->unique();
    $locations_ids = $question_set_jobs_completeds_->pluck('location_id')->unique();
    $question_set_jobs = $question_set_jobs_completeds_->get();

    $result =  App\Models\QuestionSetJob::computeIssues($question_set_jobs);

    $total_issues = $result['total_issues'];
    $critical_issues = $result['critical_issues'];

    $checklistData = [
        ['title' => 'Question-set', 'value' => count($question_set_ids),'subValue' => 0],
        ['title' => 'Submited', 'value' => count($question_set_jobs),'subValue' => 0],
        ['title' => 'Critical Issues', 'value' => $critical_issues,'subValue' => 0],
        ['title' => 'Total Issues', 'value' => $total_issues,'subValue' => 0],
    ];

    $tasks_begin = clone($tasks);
    $tasks_completed = clone($tasks);
    $tasks_create = clone($tasks);
    $tasks_late = clone($tasks);
    $tasks_rejected = clone($tasks);
    //$tasks_late = clone($tasks);

    $tasks_begin = $tasks_begin->where('status_id',App\Models\Status::STARTED)->get();
    $tasks_completed = $tasks_completed->where('status_id',App\Models\Status::COMPLETED)->get();
    $tasks_create = $tasks_create->where('status_id',App\Models\Status::CREATED)->get();
    $tasks_late = $tasks_late->where('status_id',App\Models\Status::LATE)->get();
    $tasks_rejected = $tasks_rejected->where('status_id',App\Models\Status::REJECTED)->get();
    //$tasks_late = $tasks_late->where('status_id',App\Models\Status::LATE)->get();

    $tasks = $tasks->orderBy('id', 'desc')->get();

    $tasksData = [
        ['title' => 'Tasks', 'value' => count($tasks),'subValue' => 0],
        ['title' => 'Created', 'value' => count($tasks_create),'subValue' => 0],
        ['title' => 'Begin', 'value' => count($tasks_begin ),'subValue' => 0],
        ['title' => 'Completed', 'value' => count($tasks_completed),'subValue' => 0],
        ['title' => 'Late', 'value' => count($tasks_late),'subValue' => 0],
    ];

    $question_set_jobs_completeds2 = clone $question_set_jobs_completeds;

    $question_set_jobs_completeds_by_locations = $question_set_jobs_completeds2->join('locations', 'question_set_jobs.location_id', '=', 'locations.id')
        ->select('question_set_jobs.location_id', 'locations.name', DB::raw('count(*) as total'))
        ->groupBy('question_set_jobs.location_id', 'locations.name')
        ->get();

    $locationNames = [];
    $totals = [];

    foreach ($question_set_jobs_completeds_by_locations as $location) {
        $locationNames[] = $location->name;
        $totals[] = $location->total;
    }
    $locationNamesJson = json_encode($locationNames);
    $totalsJson = json_encode($totals);
?>

<div class="row row-sm">
        <div class="col-xl-6 col-lg-6 col-md-6 col-xm-12">
            <div class="card bg-primary-gradient">
                <div class="card-body">
                    <div class="card-order">
                        <h5 class="mb-2 text-white">Checklist</h6>
                        <div class="row">
                            @foreach($checklistData as $d)
                                <div class="col-xl-3 col-lg-6 col-md-6 col-xm-12">
                                    <h3 class="text-end text-white">
                                        {{number_format($d['value'],0,0,' ')}}
                                    </h3>
                                    <h7 class="text-end text-white">
                                        <i class="text-white text-primary-shadow">{{$d['title']}}</i>
                                    </h7>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-6 col-lg-6 col-md-6 col-xm-12">
            <div class="card bg-danger-gradient">
                <div class="card-body">
                    <div class="card-order">
                        <h5 class="mb-2 text-white">Tasks</h6>
                        <div class="row">
                            @foreach($tasksData as $d)
                                <div class="col-xl-2 col-lg-6 col-md-6 col-xm-12">
                                    <h3 class="text-end text-white">
                                        {{number_format($d['value'],0,0,' ')}}
                                    </h3>
                                    <h7 class="text-end">
                                        <i class="text-white text-primary-shadow">{{$d['title']}}</i>
                                    </h7>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
</div>

<div class="row row-sm">
    <div class="col-md-6">
        <section>
            <div class="card">
                <div class="card-header tx-medium bd-0">
                    <h5 class="mb-0">Submitted checklists by locations <span class="badge badge-primary">{{count($question_set_jobs)}}</span></span></h5>
                    <span style="position: absolute; right: 10px; top:10px">
                        <a class="btn btn-sm btn-primary" id="checklist-location-tab-refresher"><i class="fa fa-list-alt"></i> Table</a>
                        <a class="btn btn-sm btn-danger mr-2" id="checklist-location-chart-refresher"><i class="fa fa-list"></i> Chart</a>
                    </span>
                </div>
                <div class="card-body">
                    <div id="checklist-location-view-container">

                    </div>

                </div>
            </div>
        </section>
    </div>
    <div class="col-md-6">
        <section>
            <div class="card">
                <div class="card-header tx-medium bd-0">
                    <h5 class="mb-0">Tasks by Locations</h5>
                    <a  style="display: none" id="task-location-tab-refresher"><i class="fa fa-list-alt"></i>click</a>
                </div>
                <div class="card-body">
                    <div id="task-location-view-container">

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


<div class="row row-sm">
    <div class="col-md-12  col-xl-12 col-lg-12 col-xm-6">
        <section>
            <div class="card">
                <div class="card-header tx-medium bd-0">
                    <h5 class="mb-0">Details of  checklists by locations</h5>
                    <span style="position: absolute; right: 10px; top:10px"><span id="">
                        <!--a target='_blank' class="btn btn-sm btn-outline-success mr-2">Export to excel</a-->
                        <!--a target="_blank" href="{{\Illuminate\Support\Facades\Request::fullUrl().'&excel=1'}}" class="btn btn-outline-success  btn-sm mr-2"> <i class="fa fa-file-excel-o"></i> Export to excel</a-->
                    </span></span>

                </div>
                <!--div class="card-body"-->
                <?php

                    $dico = [];
                    $results = [];

                    foreach ($question_set_jobs_completeds_by_locations as $q) {
                        $location= DB::table('locations')->where('name', $q->name)->first('id');

                        if ($location) {
                            $question_set_jobs_completeds2 = clone $question_set_jobs_completeds;
                            $filtered_jobs = $question_set_jobs_completeds2->where('location_id',$location->id);

                            $result =  App\Models\QuestionSetJob::computeIssues($filtered_jobs->get());
                            $total_issues = $result['total_issues'];
                            $critical_issues = $result['critical_issues'];

                            $results[] = [
                                'question_set_jobs' => $filtered_jobs,
                                'name' => $q->name,
                                'question_set_jobs_count' => count($filtered_jobs->get()),
                                'total_issues' => $total_issues,
                                'critical_issues' => $critical_issues,
                            ];
                        } else {
                            // Handle error
                        }
                    }
                ?>
                    <table class="table">
                        <thead class="thead-dark">
                            <tr>
                            <th scope="col">Location</th>
                            <th scope="col">Checklist</th>
                            <th scope="col">Completed by</th>
                            <th scope="col">Submitted</th>
                            <th scope="col">Total Issues</th>
                            <th scope="col">FS Level 3</th>
                            <th scope="col">Last Score</th>
                            <th scope="col">Last Overall Results</th>
                            <th scope="col">Score</th>
                            <th scope="col">Overall Results</th>
                            <th scope="col">Finished</th>
                            <th scope="col">Completed Duration</th>
                            </tr>
                        </thead>
                        <tbody>
                        @foreach($results as $result)
                            <?php
                                $question_set_jobs = $result['question_set_jobs']->get();
                                
                              

                                $cpt = 0;
                                $avg_score = 0;
                                foreach ($question_set_jobs as $question_set_job) {
                                    $cpt++;
                                    $possible_score = $question_set_job->answers->sum('possible_score');
                                    if($possible_score>0){
                                        //$score  =  number_format($question_set_job->getTotalScore()*100/$possible_score, 2,',', ' ');
                                        $avg_score +=  $question_set_job->getTotalScore()*100/$possible_score;
                                    }

                                    /*$questionSetJobLast = App\Models\QuestionSetJob::where('question_set_id',$question_set_job->question_set_id)
                                    ->where('status_id', App\Models\Status::COMPLETED)
                                    ->where('end_at','<',$question_set_job->end_at)
                                    ->where('location_id',$question_set_job->location_id)
                                    ->orderBy('end_at', 'desc')->first();
                                    
                                    

                                    $ratingsLast = '';
                                    $questionDataLast = '';
                                    $scoringsLast = '';
                                    $ratingFamiliesLast = '';

                                    $questionSet = $question_set_job->question_set;
                                    $ratingLast = "";
                                    if($questionSetJobLast){
                                        $questionDataLast =  App\Models\QuestionSet::computeChecklist($questionSet, $questionSetJobLast);
                                        $ratingsLast = $questionSetJobLast->calculateRating();
                                        $scoringsLast = $questionSetJobLast->calculateScoring();
                                        $ratingFamiliesLast = $ratingsLast->pluck('family_name')->unique()->toArray();

                                        $ratingLast = $questionSetJobLast->getDecision();

                                        if($ratingLast){
                                            $overall_rating_last = $ratingLast->label;
                                            //dd("---",$ratingLast->label);
                                        }

                                        foreach($scoringsLast as $scoring){
                                            //dd($scoring->label,$questionSetJobLast->getScorePercentText());
                                        }
                                    }*/


                                }
                                $avg_score  =  number_format($avg_score/$cpt, 2,',', ' ').'%';

                            ?>
                            <tr class="table-secondary text-primary">
                                <th scope="row">{{ $result['name'] }}</th>
                                <td></td>
                                <td></td>
                                <td>{{ $result['question_set_jobs_count'] }}</td>
                                <td>{{ $result['total_issues'] }}</td>
                                <td>{{ $result['critical_issues'] }}</td>
                                <td></td>
                                <td></td>
                                <td>{{$avg_score}} </td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>

                            @foreach($question_set_jobs as $question_set_job)
                                <?php
                                    $question_set = $question_set_job->question_set;

                                    $question_set_jobs_ids = [$question_set_job->id];

                                    $result =  App\Models\QuestionSetJob::computeIssues($question_set_jobs,$question_set_jobs_ids);
                                    $total_issues = $result['total_issues'];
                                    $critical_issues = $result['critical_issues'];

                                    $decision_rating_label = $question_set_job->getDecision()->label?? '';
                                    $decision_rating_color = $question_set_job->getDecision()->color?? '';
                                    
                                    
                                    //----------------
                                    $questionSetJobLast = App\Models\QuestionSetJob::where('question_set_id',$question_set_job->question_set_id)
                                    ->where('status_id', App\Models\Status::COMPLETED)
                                    ->where('end_at','<',$question_set_job->end_at)
                                    ->where('location_id',$question_set_job->location_id)
                                    ->orderBy('end_at', 'desc')->first();
                                    

                                    $ratingsLast = '';
                                    $questionDataLast = '';
                                    $scoringsLast = '';
                                    $ratingFamiliesLast = '';

                                    $questionSet = $question_set_job->question_set;
                                    $ratingLast = "";
                                    if($questionSetJobLast){
                                        $questionDataLast =  App\Models\QuestionSet::computeChecklist($questionSet, $questionSetJobLast);
                                        $ratingsLast = $questionSetJobLast->calculateRating();
                                        $scoringsLast = $questionSetJobLast->calculateScoring();
                                        $ratingFamiliesLast = $ratingsLast->pluck('family_name')->unique()->toArray();

                                        $ratingLast = $questionSetJobLast->getDecision();

                                        if($ratingLast){
                                            $overall_rating_last = $ratingLast->label;
                                            //dd("---",$ratingLast->label);
                                        }

                                        foreach($scoringsLast as $scoring){
                                            //dd($scoring->label,$questionSetJobLast->getScorePercentText());
                                        }
                                    }
                                    //-------------------
                                    
                                    
                                    
                                    

                                ?>
                                <tr class="">
                                    <th scope="row">{{date('d-m-Y H:i', strtotime($question_set_job->end_at))}}</th>
                                    <td>
                                        <a class="text-warning" href="{{url('checklist-job/details/'. $question_set_job->id)}}">
                                            {{ $question_set->title }}
                                        </a>
                                    </td>
                                    <td>
                                        {{$question_set_job->user->lastname." ".$question_set_job->user->firstname}}  
                                        <br>
                                        <span style="font-size: 12px; color: gray;">{{$question_set_job->user->email}}</span>
                                    </td>
                                    <td>{{count($question_set_jobs_ids) }}</td>
                                    <td>{{ $total_issues }}</td>
                                    <td>{{ $critical_issues }}</td>
                                    <td>@if($questionSetJobLast){{$questionSetJobLast->getScorePercentText()}}@endif</td>
                                    <td>@if($ratingLast)<span class="badge badge-secondary" style="background-color: {{$ratingLast->color}}"> {{$ratingLast->label}} </span>@endif</td>
                                    <td>{{$question_set_job->getScorePercentText()}}</td>
                                    <td><span class="badge badge-secondary" style="background-color: {{$decision_rating_color}}">{{$decision_rating_label}}</span></td>
                                    <td>
                                        @if($question_set_job->finished_at)
                                            <span class="badge badge-secondary" style="background-color: green"> YES </span
                                        @else
                                            <span class="badge badge-secondary" style="background-color: blue"> NO </span>
                                        @endif
                                    
                                    </td>
                                    <td>@if($question_set_job->finished_at)  <b>{{$question_set_job->getDurationBeforeFinished()}} days </b> @endif</td>
                                </tr>
                                
                                @endforeach
                            @endforeach
                        </tbody>
                    </table>
                <!--/div-->
            </div>
        </section>
    </div>
</div>

<script !src="">
     $('#checklist-location-chart-refresher').on('click', function () {

    var $container = $('#checklist-location-view-container');

    $container.html('<p>Loading...</p>');

    var req = $.ajax({
        url: '{{url(config('app.admin_prefix').'/refresh-checklist-location')}}',
        type: "GET",
        data: {location_id: $('#location-id').val() , filter_periode: $('#filter-period').val(),type: 'chart'},
        dataType: "html"
    });
    req.done(function (response, textStatus, jqXHR) {
            $('#checklist-location-view-container').html(response);
        });
        req.fail(function (jqXHR, textStatus) {
          swal("Erreur!", "Error during operation.", "warning");
        });
    });

    $('#checklist-location-tab-refresher').on('click', function () {

        var $container = $('#checklist-location-view-container');

        $container.html('<p>Loading...</p>');

        var req = $.ajax({
            url: '{{url(config('app.admin_prefix').'/refresh-checklist-location')}}',
            type: "GET",
            data: {location_id: $('#location-id').val() , filter_periode: $('#filter-period').val(), type: 'tab'},
            dataType: "html"
        });
        req.done(function (response, textStatus, jqXHR) {
                $('#checklist-location-view-container').html(response);
            });
            req.fail(function (jqXHR, textStatus) {
              swal("Erreur!", "Error during operation.", "warning");
            });
    });
    $('#checklist-location-tab-refresher').click();


    $('#task-location-tab-refresher').on('click', function () {
        var $container = $('#task-location-view-container');
        $container.html('<p>Loading...</p>');
        var req = $.ajax({
            url: '{{url(config('app.admin_prefix').'/refresh-task-location')}}',
            type: "GET",
            data: {location_id: $('#location-id').val() , filter_periode: $('#filter-period').val(), type: 'tab'},
            dataType: "html"
        });
        req.done(function (response, textStatus, jqXHR) {
                $('#task-location-view-container').html(response);
            });
            req.fail(function (jqXHR, textStatus) {
                swal("Erreur!", "Error during operation.", "warning");
            });
    });
    $('#task-location-tab-refresher').click();

</script>




