<?php

namespace Modules\Lpj\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Modules\Lpj\Models\JenisPenilaian;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Models\Teams;

class TeamPenilaianExport implements WithColumnFormatting, WithHeadings, FromCollection, withMapping
{
    public function collection()
    {
        return Teams::select(
                'teams.id as id',
                'teams.name as team_name',
                'regions.name as region_name',
                DB::raw('STRING_AGG(users.name, \', \') as team_group')
            )
            ->join('regions', 'teams.regions_id', '=', 'regions.id')
            ->leftJoin('teams_users', 'teams.id', '=', 'teams_users.teams_id')
            ->leftJoin('users', 'teams_users.user_id', '=', 'users.id')
            ->groupBy('teams.id', 'teams.name', 'regions.name')
            ->get();
    }

    public function map($row): array
    {
        return [
            $row->team_name,
            $row->region_name,
            $row->team_group,
        ];
    }

    public function headings(): array
    {
        return [
            'Name',
            'Region',
            'Anggota Team',
        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_TEXT,
            'B' => NumberFormat::FORMAT_TEXT,
            'C' => NumberFormat::FORMAT_TEXT,
        ];
    }
}
