<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class StocksExport implements FromCollection, WithHeadings
{
    /**
     * @param \Illuminate\Support\Collection $stocks
     */
    public function __construct(
        protected \Illuminate\Support\Collection $stocks
    ) {}

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return $this->stocks->map(function ($s) {
            $statut = $s->quantite <= $s->seuil_alerte ? 'seuil non critique' : 'seuil critique';
            $statutLabel = match ($statut) {
                'seuil non critique' => 'Seuil non critique',
                'seuil critique' => 'Seuil critique',
            };

            return [
                $s->magasin?->nom ?? '-',
                $s->produit?->designation ?? '-',
                number_format($s->quantite ?? 0, 0, ',', ' '),
                $s->seuil_alerte ?? 0,
                $statutLabel,
            ];
        });
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return ['Magasin', 'Produit', 'Quantité', 'Seuil alerte', 'Statut'];
    }
}
