<?php

namespace App\Exports;

use App\Models\OPD;
use App\Models\Question;
use App\Models\Response;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class SKMExport implements FromCollection, WithHeadings, WithMapping
{
    protected $opdId;

    public function __construct($opdId)
    {
        $this->opdId = $opdId;
    }

    public function collection()
    {
        return Response::where('opd_id', $this->opdId)
            ->with(['question', 'opd', 'answerOption'])
            ->get();
    }

    public function headings(): array
    {
        return [
            'Tanggal',
            'OPD',
            'Kode Pertanyaan',
            'Elemen',
            'Pertanyaan',
            'Jawaban',
            'Score',
            'Weight',
            'Weighted Score',
            'Komentar',
            'Nama Responden',
            'Telepon',
            'Email',
        ];
    }

    public function map($response): array
    {
        $answerText = $response->answerOption ? $response->answerOption->label : 'N/A';
        $score = $response->answerOption ? $response->answerOption->score : $response->rating;
        $weight = $response->answerOption ? $response->answerOption->weight : 1;
        $weightedScore = $response->answerOption ? ($response->answerOption->score * $response->answerOption->weight) : $response->rating;
        
        return [
            $response->created_at->format('Y-m-d H:i:s'),
            $response->opd->name,
            $response->question->code,
            $response->question->element,
            $response->question->question,
            $answerText,
            $score,
            $weight,
            $weightedScore,
            $response->comment,
            $response->respondent_name,
            $response->respondent_phone,
            $response->respondent_email,
        ];
    }
}

