<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\QAUserAnswerSelected;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use App\Classes\ValueObjects\Constants\QASystemSourceType;
use Carbon\Carbon;

class ExportsFeedback implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{

    use Exportable;

    public function headings(): array
    {
        return [
            'Version',
            'Question Set',
            'Question Text',
            'Answer Text',
            'Answer Value',
            'Source System',
            'Source Marking',
            'Source Email',
            'Created Date'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return QAUserAnswerSelected::whereHas('question', function ($query) {
            $query->whereHas('questionnaire', function ($innerQuery) {
                $innerQuery->where('group', 'feedback');
            }); //->where('created_at', '>',  Carbon::now()->subMonths(1));
        })->orderBy('created_at', 'desc');
    }

    /**
     * @param QAUserAnswerSelected $userAnswer
     *
     * @return array
     */
    public function map($userAnswer): array
    {
        $source = $userAnswer->userSource;
        $user = $userAnswer->source_id === 0 ? $userAnswer->user : null;
        $user_marking = '';
        if($user){
            $companyModule = $user->companyModule()->first();
            $user_marking = $companyModule ? $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference : "";
        }
        $answer = $userAnswer->answer;

        return [
            $userAnswer->question->questionnaire->version,
            $userAnswer->question->questionnaire->description,
            $userAnswer->question->question_text,
            $answer->display_text,
            $answer->value,
            $user ? QASystemSourceType::getText(QASystemSourceType::IZYIM) : QASystemSourceType::getText($source->system),
            $user ? $user_marking : $source->marking,
            $user ? $user->email : $source->email,
            Carbon::parse($userAnswer->created_at)->format('d-m-Y'),
        ];
    }
}
