<?php

namespace App\Exports;

use App\Song;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class SongsExport implements FromQuery, WithHeadings, WithMapping, WithColumnFormatting
{
    public function query()
    {
        return Song::query()->select('id', 'title', 'slug', 'lyrics', 'views', 'created_at', 'updated_at');
    }

    public function map($song): array
    {
        $song->loadMissing('artists');
        $artists = $song->artists->pluck('name')->implode(' / ');
        $lyrics = str_replace(["\r", "\n"], " | ", $song->lyrics);
        return [
            $song->id,
            $song->title,
            $song->slug,
            $artists,
            $lyrics,
            $song->views,
            $song->created_at,
            $song->updated_at,
        ];
    }

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

    public function headings(): array
    {
        return ['id', 'title', 'slug', 'artists', 'lyrics', 'views', 'created_at', 'updated_at'];
    }
}
