<?php

namespace App\Exports;

use App\Models\KelasMapel;
use App\Models\SiswaKelas;
use App\Models\Nilai;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class SiswaNilaiExport implements FromCollection, WithHeadings
{
    protected $kelasMapelId;

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

    public function collection()
{
    $km = KelasMapel::findOrFail($this->kelasMapelId);
    $kelasId = $km->kelas_id;

    $siswaks = SiswaKelas::with('siswa.user')
                ->where('kelas_id', $kelasId)
                ->get();

    $firstNilai = Nilai::where('kelas_mapel_id', $this->kelasMapelId)->first();
    $labels = [];
    if ($firstNilai) {
        $arr = is_string($firstNilai->s_nilai)
               ? json_decode($firstNilai->s_nilai, true)
               : ($firstNilai->s_nilai ?? []);
        $labels = array_keys($arr);
    }

    $rows = $siswaks->map(function($sk) use ($labels) {
        $nisn = $sk->siswa->nisn;
        $name = $sk->siswa->user->name;

        $nilai = Nilai::where('kelas_mapel_id', $this->kelasMapelId)
                      ->where('siswa_id', $sk->siswa->siswa_id)
                      ->first();

        $vals = [];
        if ($nilai) {
            $vals = is_string($nilai->s_nilai)
                    ? json_decode($nilai->s_nilai, true)
                    : ($nilai->s_nilai ?? []);
        }

        // Hitung nilai sesuai urutan label
        $nilaiArray = [];
        foreach ($labels as $lbl) {
            $nilaiArray[] = is_numeric($vals[$lbl] ?? null) ? (float)$vals[$lbl] : null;
        }

        // Hitung rata-rata dari nilai yang valid
        $validNilai = array_filter($nilaiArray, fn($v) => $v !== null);
        $avg = count($validNilai) ? round(array_sum($validNilai) / count($validNilai)) : '';

        $row = [$nisn, $name];
        foreach ($labels as $lbl) {
            $row[] = $vals[$lbl] ?? '';
        }
        $row[] = $avg;

        return $row;
    });

    return $rows;
}

public function headings(): array
{
    $firstNilai = Nilai::where('kelas_mapel_id', $this->kelasMapelId)->first();
    $labels = [];
    if ($firstNilai) {
        $arr = is_string($firstNilai->s_nilai)
               ? json_decode($firstNilai->s_nilai, true)
               : ($firstNilai->s_nilai ?? []);
        $labels = array_keys($arr);
    }
    return array_merge(['NISN', 'Nama'], $labels, ['Rata-rata']);
}


}
